1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
//LICENSE
//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
//LICENSE
//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
//LICENSE
//LICENSE All rights reserved.
//LICENSE
//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
// Polyfill while #![feature(strict_provenance)] is unstable
#[cfg(not(nightly))]
use sptr::Strict;
use std::ptr::NonNull;

/// Postgres defines the "Datum" type as uintptr_t, so bindgen decides it is usize.
/// Normally, this would be fine, except Postgres uses it more like void*:
/// A pointer to anything that could mean anything, check your assumptions before using.
///
///
/// Accordingly, the "Datum" type from bindgen is not entirely correct, as
/// Rust's `usize` may match the size of `uintptr_t` but it is not quite the same.
/// The compiler would rather know which integers are integers and which are pointers.
/// As a result, Datum is now a wrapper around `*mut DatumBlob`.
/// This type need not be exported unless the details of the type idiom become important.
// This struct uses a Rust idiom invented before `extern type` was designed,
// but should probably be replaced when #![feature(extern_type)] stabilizes
#[repr(C)]
struct DatumBlob {
    _data: [u8; 0],
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

/// Datum is an abstract value that is effectively a union of all scalar types
/// and all possible pointers in a Postgres context. That is, it is either
/// "pass-by-value" (if the value fits into the platform's `uintptr_t`) or
/// "pass-by-reference" (if it does not).
///
/// In Rust, it is best to treat this largely as a pointer while passing it around
/// for code that doesn't care about what the Datum "truly is".
/// If for some reason it is important to manipulate the address/value
/// without "knowing the type" of the Datum, cast to a pointer and use pointer methods.
///
/// Only create Datums from non-pointers when you know you want to pass a value, as
/// it is erroneous for `unsafe` code to dereference the address of "only a value" as a pointer.
/// It is still a "safe" operation to create such pointers: validity is asserted by dereferencing,
/// **or by creating a safe reference such as &T or &mut T**. Also be aware that the validity
/// of Datum's Copy is premised on the same implicit issues with pointers being Copy:
/// while any `&T` is live, other `*mut T` must not be used to write to that `&T`,
/// and `&mut T` implies no other `*mut T` even exists outside an `&mut T`'s borrowing ancestry.
/// It is thus of dubious soundness for Rust code to receive `*mut T`, create another `*mut T`,
/// cast the first to `&mut T`, and then later try to use the second `*mut T` to write.
/// It _is_ sound for Postgres itself to pass a copied pointer as a Datum to Rust code, then later
/// to mutate that data through its original pointer after Rust creates and releases a `&mut T`.
///
/// For all intents and purposes, Postgres counts as `unsafe` code that may be relying
/// on you communicating pointers correctly to it. Do not play games with your database.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Datum(*mut DatumBlob);

impl Datum {
    /// Assume the datum is a value and extract the bits from
    /// the memory address, interpreting them as an integer.
    #[inline]
    pub fn value(self) -> usize {
        #[allow(unstable_name_collisions)]
        self.0.addr()
    }

    /// True if the datum is equal to the null pointer.
    #[inline]
    pub fn is_null(self) -> bool {
        self.0.is_null()
    }

    /// Assume the datum is a pointer and cast it to point to T.
    /// It is recommended to explicitly use `datum.cast_mut_ptr::<T>()`.
    #[inline]
    pub fn cast_mut_ptr<T>(self) -> *mut T {
        #[allow(unstable_name_collisions)]
        self.0.cast()
    }
}

impl From<usize> for Datum {
    #[inline]
    fn from(val: usize) -> Datum {
        #[allow(unstable_name_collisions)]
        Datum(NonNull::<DatumBlob>::dangling().as_ptr().with_addr(val))
    }
}

impl From<Datum> for usize {
    #[inline]
    fn from(val: Datum) -> usize {
        #[allow(unstable_name_collisions)]
        val.0.addr()
    }
}

impl From<isize> for Datum {
    #[inline]
    fn from(val: isize) -> Datum {
        Datum::from(val as usize)
    }
}

impl From<u8> for Datum {
    #[inline]
    fn from(val: u8) -> Datum {
        Datum::from(usize::from(val))
    }
}

impl From<u16> for Datum {
    #[inline]
    fn from(val: u16) -> Datum {
        Datum::from(usize::from(val))
    }
}

impl From<u32> for Datum {
    #[inline]
    fn from(val: u32) -> Datum {
        Datum::from(val as usize)
    }
}

impl From<u64> for Datum {
    #[inline]
    fn from(val: u64) -> Datum {
        Datum::from(val as usize)
    }
}

impl From<i8> for Datum {
    #[inline]
    fn from(val: i8) -> Datum {
        Datum::from(isize::from(val))
    }
}

impl From<i16> for Datum {
    #[inline]
    fn from(val: i16) -> Datum {
        Datum::from(isize::from(val))
    }
}

impl From<i32> for Datum {
    #[inline]
    fn from(val: i32) -> Datum {
        Datum::from(val as usize)
    }
}

impl From<i64> for Datum {
    #[inline]
    fn from(val: i64) -> Datum {
        Datum::from(val as usize)
    }
}

impl From<bool> for Datum {
    #[inline]
    fn from(val: bool) -> Datum {
        Datum::from(val as usize)
    }
}

impl<T> From<*mut T> for Datum {
    #[inline]
    fn from(val: *mut T) -> Datum {
        Datum(val.cast())
    }
}

impl<T> From<*const T> for Datum {
    #[inline]
    fn from(val: *const T) -> Datum {
        Datum(val as *mut _)
    }
}

impl<T> PartialEq<*mut T> for Datum {
    #[inline]
    fn eq(&self, other: &*mut T) -> bool {
        &self.0.cast() == other
    }
}

impl<T> PartialEq<Datum> for *mut T {
    #[inline]
    fn eq(&self, other: &Datum) -> bool {
        self == &other.0.cast()
    }
}

/// This struct consists of a Datum and a bool, matching Postgres's definition
/// as of Postgres 12. This isn't efficient in terms of storage size, due to padding,
/// but sometimes it's more cache-friendly, so sometimes it is the preferred type.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct NullableDatum {
    pub value: Datum,
    pub isnull: bool,
}

impl TryFrom<NullableDatum> for Datum {
    type Error = ();

    #[inline]
    fn try_from(nd: NullableDatum) -> Result<Datum, ()> {
        let NullableDatum { value, isnull } = nd;
        if isnull {
            Err(())
        } else {
            Ok(value)
        }
    }
}

impl From<NullableDatum> for Option<Datum> {
    #[inline]
    fn from(nd: NullableDatum) -> Option<Datum> {
        Some(Datum::try_from(nd).ok()?)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn roundtrip_integers() {
        #[cfg(target_pointer_width = "64")]
        mod types {
            pub type UnsignedInt = u64;
            pub type SignedInt = i64;
        }
        #[cfg(target_pointer_width = "32")]
        mod types {
            // 64-bit integers would be truncated on 32 bit platforms
            pub type UnsignedInt = u32;
            pub type SignedInt = i32;
        }
        use types::*;

        let val: SignedInt = 123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as SignedInt, val);

        let val: isize = 123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as isize, val);

        let val: SignedInt = -123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as SignedInt, val);

        let val: isize = -123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as isize, val);

        let val: UnsignedInt = 123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as UnsignedInt, val);

        let val: usize = 123456;
        let datum = Datum::from(val);
        assert_eq!(datum.value() as usize, val);
    }
}