pgrx 0.18.0

pgrx: A Rust framework for creating Postgres extensions
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//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.
//! Helper functions to work with Postgres `varlena *` structures

use crate::{PgBox, pg_sys};
use core::{ops::DerefMut, slice, str};

/// # Safety
///
/// The caller asserts the specified `ptr` really is a non-null, palloc'd [`pg_sys::varlena`] pointer
/// that is aligned to 4 bytes, and that the `len` is a half of [`i32::MAX`]
#[inline(always)]
pub unsafe fn set_varsize_4b(ptr: *mut pg_sys::varlena, len: i32) {
    // #ifdef WORDS_BIGENDIAN
    // #define SET_VARSIZE_4B(PTR,len) \
    // 	(((varattrib_4b *) (PTR))->va_4byte.va_header = (len) & 0x3FFFFFFF)
    // #else
    // #define SET_VARSIZE_4B(PTR,len) \
    // 	(((varattrib_4b *) (PTR))->va_4byte.va_header = (((uint32) (len)) << 2))
    // #endif

    // SAFETY:  A varlena can be safely cast to a varattrib_4b
    let header = &mut (*ptr.cast::<pg_sys::varattrib_4b>()).va_4byte.deref_mut().va_header;
    // Using core::ptr::write(), which never calls drop(), to prevent
    // automatically dropping a field of a ManuallyDrop<T>
    core::ptr::write(header, encode_vlen_4b(len))
}

pub(crate) fn encode_vlen_4b(len: i32) -> u32 {
    #[cfg(target_endian = "big")]
    let value = (len as u32) & 0x3FFFFFFFu32;
    #[cfg(target_endian = "little")]
    let value = (len as u32) << 2u32;
    value
}

pub(crate) fn encode_vlen_1b(len: i32) -> u8 {
    #[cfg(target_endian = "big")]
    let value = (len as u8) | 0x80;
    #[cfg(target_endian = "little")]
    let value = ((len as u8) << 1) | 0x01;
    value
}

/// # Safety
///
/// The caller asserts the specified `ptr` really is a non-null, palloc'd [`pg_sys::varlena`] pointer
/// that is aligned to 4 bytes.
#[inline(always)]
#[deprecated(since = "0.12.0", note = "you probably meant set_varsize_4b")]
pub unsafe fn set_varsize(ptr: *mut pg_sys::varlena, len: i32) {
    // #define SET_VARSIZE(PTR, len)				SET_VARSIZE_4B(PTR, len)
    set_varsize_4b(ptr, len)
}

/// # Safety
///
/// The caller asserts the specified `ptr` really is a non-null, palloc'd [`pg_sys::varlena`] pointer
#[inline(always)]
pub unsafe fn set_varsize_1b(ptr: *mut pg_sys::varlena, len: i32) {
    // #ifdef WORDS_BIGENDIAN
    // #define SET_VARSIZE_1B(PTR,len) \
    // 	(((varattrib_1b *) (PTR))->va_header = (len) | 0x80)
    // #else
    // #define SET_VARSIZE_1B(PTR,len) \
    // 	(((varattrib_1b *) (PTR))->va_header = (((uint8) (len)) << 1) | 0x01)
    // #endif

    // SAFETY:  A varlena can be safely cast to a varattrib_1b
    (*ptr.cast::<pg_sys::varattrib_1b>()).va_header = encode_vlen_1b(len);
}

/// # Safety
///
/// The caller asserts the specified `ptr` really is a non-null, palloc'd [`pg_sys::varlena`] pointer
#[inline(always)]
pub unsafe fn set_varsize_short(ptr: *mut pg_sys::varlena, len: i32) {
    //    #define SET_VARSIZE_SHORT(PTR, len)			SET_VARSIZE_1B(PTR, len)
    set_varsize_1b(ptr, len)
}

/// ```c
/// #define VARSIZE_EXTERNAL(PTR)                        (VARHDRSZ_EXTERNAL + VARTAG_SIZE(VARTAG_EXTERNAL(PTR)))
/// ```
#[inline]
pub unsafe fn varsize_external(ptr: *const pg_sys::varlena) -> usize {
    pg_sys::VARHDRSZ_EXTERNAL + vartag_size(vartag_external(ptr) as pg_sys::vartag_external::Type)
}

/// ```c
/// #define VARTAG_EXTERNAL(PTR)                        VARTAG_1B_E(PTR)
/// ```
#[inline]
pub unsafe fn vartag_external(ptr: *const pg_sys::varlena) -> u8 {
    vartag_1b_e(ptr)
}

/// ```c
/// #define VARTAG_IS_EXPANDED(tag) \
///      (((tag) & ~1) == VARTAG_EXPANDED_RO)
/// ```
#[inline]
pub unsafe fn vartag_is_expanded(tag: pg_sys::vartag_external::Type) -> bool {
    (tag & !1) == pg_sys::vartag_external::VARTAG_EXPANDED_RO
}

/// ```c
/// #define VARTAG_SIZE(tag) \
///      ((tag) == VARTAG_INDIRECT ? sizeof(varatt_indirect) : \
///       VARTAG_IS_EXPANDED(tag) ? sizeof(varatt_expanded) : \
///       (tag) == VARTAG_ONDISK ? sizeof(varatt_external) : \
///       TrapMacro(true, "unrecognized TOAST vartag"))
/// ```
#[inline]
pub unsafe fn vartag_size(tag: pg_sys::vartag_external::Type) -> usize {
    if tag == pg_sys::vartag_external::VARTAG_INDIRECT {
        std::mem::size_of::<pg_sys::varatt_indirect>()
    } else if vartag_is_expanded(tag) {
        std::mem::size_of::<pg_sys::varatt_expanded>()
    } else if tag == pg_sys::vartag_external::VARTAG_ONDISK {
        std::mem::size_of::<pg_sys::varatt_external>()
    } else {
        panic!("unrecognized TOAST vartag")
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARSIZE_4B(PTR) \
///   (((varattrib_4b *) (PTR))->va_4byte.va_header & 0x3FFFFFFF)
/// #else
/// #define VARSIZE_4B(PTR) \
///   ((((varattrib_4b *) (PTR))->va_4byte.va_header >> 2) & 0x3FFFFFFF)
/// #endif
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[inline]
pub unsafe fn varsize_4b(ptr: *const pg_sys::varlena) -> usize {
    let va4b = ptr as *const pg_sys::varattrib_4b__bindgen_ty_1; // 4byte
    #[cfg(target_endian = "big")]
    {
        ((*va4b).va_header & 0x3FFF_FFFF) as usize
    }
    #[cfg(target_endian = "little")]
    {
        (((*va4b).va_header >> 2) & 0x3FFF_FFFF) as usize
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARSIZE_1B(PTR) \
///   (((varattrib_1b *) (PTR))->va_header & 0x7F)
/// #else
/// #define VARSIZE_1B(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header >> 1) & 0x7F)
/// #endif
/// ```
#[inline]
pub unsafe fn varsize_1b(ptr: *const pg_sys::varlena) -> usize {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        ((*va1b).va_header & 0x7F) as usize
    }
    #[cfg(target_endian = "little")]
    {
        (((*va1b).va_header >> 1) & 0x7F) as usize
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARTAG_1B_E(PTR) \
///   (((varattrib_1b_e *) (PTR))->va_tag)
/// #else
/// #define VARTAG_1B_E(PTR) \
///   (((varattrib_1b_e *) (PTR))->va_tag)
/// #endif
/// ```
#[inline]
pub unsafe fn vartag_1b_e(ptr: *const pg_sys::varlena) -> u8 {
    let va1be = ptr as *const pg_sys::varattrib_1b_e;
    (*va1be).va_tag
}

#[inline]
pub unsafe fn varsize(ptr: *const pg_sys::varlena) -> usize {
    varsize_4b(ptr)
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_IS_4B(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x80) == 0x00)
/// #else
/// #define VARATT_IS_4B(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x01) == 0x00)
/// #endif
/// ```
#[inline]
pub unsafe fn varatt_is_4b(ptr: *const pg_sys::varlena) -> bool {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        (*va1b).va_header & 0x80 == 0x00
    }
    #[cfg(target_endian = "little")]
    {
        (*va1b).va_header & 0x01 == 0x00
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_IS_4B_U(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0xC0) == 0x00)
/// #else
/// #define VARATT_IS_4B_U(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x03) == 0x00)
/// #endif
/// ```
#[allow(clippy::verbose_bit_mask)]
#[inline]
pub unsafe fn varatt_is_4b_u(ptr: *const pg_sys::varlena) -> bool {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        (*va1b).va_header & 0xC0 == 0x00
    }
    #[cfg(target_endian = "little")]
    {
        (*va1b).va_header & 0x03 == 0x00
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_IS_4B_C(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0xC0) == 0x40)
/// #else
/// #define VARATT_IS_4B_C(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x03) == 0x02)
/// #endif
/// ```
#[inline]
pub unsafe fn varatt_is_4b_c(ptr: *const pg_sys::varlena) -> bool {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        (*va1b).va_header & 0xC0 == 0x40
    }
    #[cfg(target_endian = "little")]
    {
        (*va1b).va_header & 0x03 == 0x02
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_IS_1B(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x80) == 0x80)
/// #else
/// #define VARATT_IS_1B(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header & 0x01) == 0x01)
/// #endif
/// ```
#[inline]
pub unsafe fn varatt_is_1b(ptr: *const pg_sys::varlena) -> bool {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        (*va1b).va_header & 0x80 == 0x80
    }
    #[cfg(target_endian = "little")]
    {
        (*va1b).va_header & 0x01 == 0x01
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_IS_1B_E(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header) == 0x80)
/// #else
/// #define VARATT_IS_1B_E(PTR) \
///   ((((varattrib_1b *) (PTR))->va_header) == 0x01)
/// #endif
/// ```
#[inline]
pub unsafe fn varatt_is_1b_e(ptr: *const pg_sys::varlena) -> bool {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    #[cfg(target_endian = "big")]
    {
        (*va1b).va_header == 0x80
    }
    #[cfg(target_endian = "little")]
    {
        (*va1b).va_header == 0x01
    }
}

/// ```c
/// #ifdef WORDS_BIGENDIAN
/// #define VARATT_NOT_PAD_BYTE(PTR) \
///   (*((uint8 *) (PTR)) != 0)
/// #else
/// #define VARATT_NOT_PAD_BYTE(PTR) \
///   (*((uint8 *) (PTR)) != 0)
/// #endif
/// ```
#[inline]
pub unsafe fn varatt_not_pad_byte(ptr: *const pg_sys::varlena) -> bool {
    !ptr.is_null()
}

/// ```c
/// #define VARSIZE_ANY(PTR) \
///      (VARATT_IS_1B_E(PTR) ? VARSIZE_EXTERNAL(PTR) : \
///       (VARATT_IS_1B(PTR) ? VARSIZE_1B(PTR) : \
///        VARSIZE_4B(PTR)))
/// ```
#[inline]
pub unsafe fn varsize_any(ptr: *const pg_sys::varlena) -> usize {
    if varatt_is_1b_e(ptr) {
        varsize_external(ptr)
    } else if varatt_is_1b(ptr) {
        varsize_1b(ptr)
    } else {
        varsize_4b(ptr)
    }
}

/// ```c
/// /* Size of a varlena data, excluding header */
/// #define VARSIZE_ANY_EXHDR(PTR) \
///             (VARATT_IS_1B_E(PTR) ? \
///              VARSIZE_EXTERNAL(PTR)-VARHDRSZ_EXTERNAL : \
///                   ( \
///                  VARATT_IS_1B(PTR) ? \
///                        VARSIZE_1B(PTR)-VARHDRSZ_SHORT : \
///                             VARSIZE_4B(PTR)-VARHDRSZ \
///               ) \
///         )
/// ```
#[inline]
pub unsafe fn varsize_any_exhdr(ptr: *const pg_sys::varlena) -> usize {
    if varatt_is_1b_e(ptr) {
        varsize_external(ptr) - pg_sys::VARHDRSZ_EXTERNAL
    } else if varatt_is_1b(ptr) {
        varsize_1b(ptr) - pg_sys::VARHDRSZ_SHORT
    } else {
        varsize_4b(ptr) - pg_sys::VARHDRSZ
    }
}

/// ```c
/// #define VARDATA_1B(PTR)            (((varattrib_1b *) (PTR))->va_data)
/// ```
#[inline]
pub unsafe fn vardata_1b(ptr: *const pg_sys::varlena) -> *const std::os::raw::c_char {
    let va1b = ptr as *const pg_sys::varattrib_1b;
    (*va1b).va_data.as_slice(varsize_1b(ptr as *const pg_sys::varlena) as usize).as_ptr()
        as *const std::os::raw::c_char
}

/// ```c
/// #define VARDATA_4B(PTR)            (((varattrib_4b *) (PTR))->va_4byte.va_data)
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[inline]
pub unsafe fn vardata_4b(ptr: *const pg_sys::varlena) -> *const std::os::raw::c_char {
    let va1b = ptr as *const pg_sys::varattrib_4b__bindgen_ty_1; // 4byte
    (*va1b).va_data.as_slice(varsize_1b(ptr as *const pg_sys::varlena) as usize).as_ptr()
        as *const std::os::raw::c_char
}

/// ```c
/// #define VARDATA_4B_C(PTR)      (((varattrib_4b *) (PTR))->va_compressed.va_data)
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[inline]
pub unsafe fn vardata_4b_c(ptr: *const pg_sys::varlena) -> *const std::os::raw::c_char {
    let va1b = ptr as *const pg_sys::varattrib_4b__bindgen_ty_2; // compressed
    (*va1b).va_data.as_slice(varsize_1b(ptr as *const pg_sys::varlena) as usize).as_ptr()
        as *const std::os::raw::c_char
}

/// ```c
/// #define VARDATA_1B_E(PTR)      (((varattrib_1b_e *) (PTR))->va_data)
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[inline]
pub unsafe fn vardata_1b_e(ptr: *const pg_sys::varlena) -> *const std::os::raw::c_char {
    let va1b = ptr as *const pg_sys::varattrib_1b_e;
    (*va1b).va_data.as_slice(varsize_1b(ptr as *const pg_sys::varlena) as usize).as_ptr()
        as *const std::os::raw::c_char
}

/// ```c
/// /* caution: this will not work on an external or compressed-in-line Datum */
/// /* caution: this will return a possibly unaligned pointer */
/// #define VARDATA_ANY(PTR) \
///          (VARATT_IS_1B(PTR) ? VARDATA_1B(PTR) : VARDATA_4B(PTR))
/// ```
#[inline]
pub unsafe fn vardata_any(ptr: *const pg_sys::varlena) -> *const std::os::raw::c_char {
    if varatt_is_1b(ptr) { vardata_1b(ptr) } else { vardata_4b(ptr) }
}

/// Convert a Postgres `varlena *` (or `text *`) into a Rust `&str`.
///
/// ## Safety
///
/// This function is unsafe because it blindly assumes the provided varlena pointer is non-null.
///
/// Note also that this function is zero-copy and the underlying Rust &str is backed by Postgres-allocated
/// memory.  As such, the return value will become invalid the moment Postgres frees the varlena
#[inline]
pub unsafe fn text_to_rust_str<'a>(
    varlena: *const pg_sys::varlena,
) -> Result<&'a str, str::Utf8Error> {
    let len = varsize_any_exhdr(varlena);
    let data = vardata_any(varlena);

    str::from_utf8(slice::from_raw_parts(data as *mut u8, len))
}

/// Convert a Postgres `varlena *` (or `text *`) into a Rust `&str`.
///
/// ## Safety
///
/// As `text_to_rust_str` but with the additional safety contract that the data is UTF-8.
#[inline]
pub unsafe fn text_to_rust_str_unchecked<'a>(varlena: *const pg_sys::varlena) -> &'a str {
    let len = varsize_any_exhdr(varlena);
    let data = vardata_any(varlena);

    str::from_utf8_unchecked(slice::from_raw_parts(data as *mut u8, len))
}

/// Convert a Postgres `varlena *` (or `byte *`) into a Rust `&[u8]`.
///
/// ## Safety
///
/// This function is unsafe because it blindly assumes the provided varlena pointer is non-null.
///
/// Note also that this function is zero-copy and the underlying Rust `&[u8]` slice is backed by Postgres-allocated
/// memory.  As such, the return value will become invalid the moment Postgres frees the varlena
#[inline]
pub unsafe fn varlena_to_byte_slice<'a>(varlena: *const pg_sys::varlena) -> &'a [u8] {
    let len = varsize_any_exhdr(varlena);
    let data = vardata_any(varlena);

    std::slice::from_raw_parts(data as *const u8, len)
}

/// Convert a Rust `&str` into a Postgres `text *`.
///
/// This allocates the returned Postgres `text *` in `CurrentMemoryContext`.
#[inline]
pub fn rust_str_to_text_p(s: &str) -> PgBox<pg_sys::varlena> {
    let bytea = rust_byte_slice_to_bytea(s.as_bytes());

    // a pg_sys::bytea is a type alias for pg_sys::varlena so this cast is fine
    // SAFETY: bytea will be a valid pointer
    unsafe { PgBox::from_pg(bytea.as_ptr() as *mut pg_sys::varlena) }
}

/// Convert a Rust `&[u8]` into a Postgres `bytea *` (which is really a varchar)
///
/// This allocates the returned Postgres `bytea *` in `CurrentMemoryContext`.
#[inline]
pub fn rust_byte_slice_to_bytea(slice: &[u8]) -> PgBox<pg_sys::bytea> {
    // SAFETY:  `slice` will provide a valid pointer and pg_sys::cstring_to_text_with_len() will too
    unsafe {
        PgBox::from_pg(pg_sys::cstring_to_text_with_len(
            slice.as_ptr() as *const std::os::raw::c_char,
            slice.len() as i32,
        ))
    }
}