1
//! Macros for generating C-ABI-compatible collection types (`Vec`, `Option`, `Result`)
2
//! used throughout the codebase for FFI interop.
3
//!
4
//! Each macro produces `#[repr(C)]` types
5
//! with a destructor model: `DefaultRust` (library-owned), `NoDestructor` (`&'static`),
6
//! `External` (caller-provided destructor fn), and `AlreadyDestroyed` (post-drop guard).
7

            
8
#[macro_export]
9
macro_rules! impl_vec {
10
    (
11
        $struct_type:ident,
12
        $struct_name:ident,
13
        $destructor_name:ident,
14
        $destructor_type_name:ident,
15
        $slice_name:ident,
16
        $option_type:ident
17
    ) => {
18
        pub type $destructor_type_name = extern "C" fn(*mut $struct_name);
19

            
20
        /// C-compatible slice type for `$struct_name`.
21
        /// This is a non-owning view into a Vec's data.
22
        #[repr(C)]
23
        #[derive(Debug, Copy, Clone)]
24
        pub struct $slice_name {
25
            pub ptr: *const $struct_type,
26
            pub len: usize,
27
        }
28

            
29
        impl $slice_name {
30
            /// Creates an empty slice.
31
            #[inline]
32
            #[must_use]
33
8
            pub const fn empty() -> Self {
34
8
                Self {
35
8
                    ptr: core::ptr::null(),
36
8
                    len: 0,
37
8
                }
38
8
            }
39

            
40
            /// Returns the number of elements in the slice.
41
            #[inline]
42
            #[must_use]
43
12
            pub const fn len(&self) -> usize {
44
12
                self.len
45
12
            }
46

            
47
            /// Returns true if the slice is empty.
48
            #[inline]
49
            #[must_use]
50
2
            pub const fn is_empty(&self) -> bool {
51
2
                self.len == 0
52
2
            }
53

            
54
            /// Returns a pointer to the slice's data.
55
            #[inline]
56
            #[must_use]
57
            pub const fn as_ptr(&self) -> *const $struct_type {
58
                self.ptr
59
            }
60

            
61
            /// Converts the C-slice to a Rust slice.
62
            #[inline]
63
            #[must_use]
64
28
            pub const fn as_slice(&self) -> &[$struct_type] {
65
28
                if self.ptr.is_null() || self.len == 0 {
66
6
                    &[]
67
                } else {
68
22
                    unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
69
                }
70
28
            }
71

            
72
            /// Returns a reference to the element at the given index, or None if out of bounds.
73
            #[inline]
74
            #[must_use]
75
            pub fn get(&self, index: usize) -> Option<&$struct_type> {
76
                self.as_slice().get(index)
77
            }
78

            
79
            /// Returns an iterator over the elements.
80
            #[inline]
81
            pub fn iter(&self) -> core::slice::Iter<'_, $struct_type> {
82
                self.as_slice().iter()
83
            }
84
        }
85

            
86
        unsafe impl Send for $slice_name {}
87
        unsafe impl Sync for $slice_name {}
88

            
89
        impl<'a> IntoIterator for &'a $slice_name {
90
            type Item = &'a $struct_type;
91
            type IntoIter = core::slice::Iter<'a, $struct_type>;
92
            #[inline]
93
            fn into_iter(self) -> Self::IntoIter {
94
                self.iter()
95
            }
96
        }
97

            
98
        impl<'a> IntoIterator for &'a $struct_name {
99
            type Item = &'a $struct_type;
100
            type IntoIter = core::slice::Iter<'a, $struct_type>;
101
            #[inline]
102
3467321
            fn into_iter(self) -> Self::IntoIter {
103
3467321
                self.iter()
104
3467321
            }
105
        }
106

            
107
        #[repr(C)]
108
        pub struct $struct_name {
109
            ptr: *const $struct_type,
110
            len: usize,
111
            cap: usize,
112
            destructor: $destructor_name,
113
        }
114

            
115
        #[derive(Debug, Copy, Clone)]
116
        #[repr(C, u8)]
117
        pub enum $destructor_name {
118
            DefaultRust,
119
            NoDestructor,
120
            External($destructor_type_name),
121
            /// Destructor was already run — prevents double-free.
122
            /// Set by Drop impl after destruction.
123
            AlreadyDestroyed,
124
        }
125

            
126
        unsafe impl Send for $struct_name {}
127
        unsafe impl Sync for $struct_name {}
128

            
129
        impl $struct_name {
130
            #[inline]
131
            #[must_use]
132
811894
            pub const fn new() -> $struct_name {
133
                // lets hope the optimizer catches this
134
811894
                Self::from_vec(alloc::vec::Vec::new())
135
811894
            }
136

            
137
            #[inline]
138
            #[must_use]
139
1
            pub fn with_capacity(cap: usize) -> Self {
140
1
                Self::from_vec(alloc::vec::Vec::<$struct_type>::with_capacity(cap))
141
1
            }
142

            
143
            #[inline]
144
            #[must_use]
145
33082735
            pub const fn from_const_slice(input: &'static [$struct_type]) -> Self {
146
33082735
                Self {
147
33082735
                    ptr: input.as_ptr(),
148
33082735
                    len: input.len(),
149
33082735
                    cap: input.len(),
150
33082735
                    destructor: $destructor_name::NoDestructor, // because of &'static
151
33082735
                }
152
33082735
            }
153

            
154
            /// True when the buffer is heap memory THIS type allocated, and may
155
            /// therefore be realloc'd / deep-cloned / freed by us.
156
            ///
157
            /// Private, and deliberately not part of the C API surface. Lives here
158
            /// rather than in `impl_vec_mut!` because only `impl_vec!` is given the
159
            /// name of the destructor enum.
160
            #[inline]
161
381472
            const fn owns_buffer(&self) -> bool {
162
381472
                matches!(self.destructor, $destructor_name::DefaultRust)
163
381472
            }
164

            
165
            /// Records that the buffer is now heap memory we own. Must be called after
166
            /// any allocation that replaces a borrowed (`NoDestructor`/`External`)
167
            /// buffer, or `clone_self`/`Drop` keep believing it is borrowed.
168
            #[inline]
169
381472
            const fn mark_rust_owned(&mut self) {
170
381472
                self.destructor = $destructor_name::DefaultRust;
171
381472
            }
172

            
173
            #[inline]
174
            #[must_use]
175
120457454
            pub const fn from_vec(input: alloc::vec::Vec<$struct_type>) -> Self {
176
120457454
                let ptr = input.as_ptr();
177
120457454
                let len = input.len();
178
120457454
                let cap = input.capacity();
179

            
180
120457454
                let _ = ::core::mem::ManuallyDrop::new(input);
181

            
182
120457454
                Self {
183
120457454
                    ptr,
184
120457454
                    len,
185
120457454
                    cap,
186
120457454
                    destructor: $destructor_name::DefaultRust,
187
120457454
                }
188
120457454
            }
189

            
190
            #[inline]
191
9946089
            pub fn iter(&self) -> core::slice::Iter<'_, $struct_type> {
192
9946089
                self.as_ref().iter()
193
9946089
            }
194

            
195
            #[inline]
196
            #[must_use]
197
2569003
            pub const fn len(&self) -> usize {
198
2569003
                self.len
199
2569003
            }
200

            
201
            #[inline]
202
            #[must_use]
203
1457667
            pub const fn capacity(&self) -> usize {
204
1457667
                self.cap
205
1457667
            }
206

            
207
            #[inline]
208
            #[must_use]
209
96052922
            pub const fn is_empty(&self) -> bool {
210
96052922
                self.len == 0
211
96052922
            }
212

            
213
            /// Returns a reference to the element at the given index (Rust-only, inline).
214
            #[inline]
215
            #[must_use]
216
244330
            pub fn get(&self, index: usize) -> Option<&$struct_type> {
217
244330
                self.as_ref().get(index)
218
244330
            }
219

            
220
            /// C-API compatible get function. Returns a copy of the element at the given index.
221
            /// Returns None if the index is out of bounds.
222
            #[inline]
223
            #[must_use]
224
37
            pub fn c_get(&self, index: usize) -> $option_type
225
37
            where
226
37
                $struct_type: Clone,
227
            {
228
37
                self.get(index).cloned().into()
229
37
            }
230

            
231
            #[allow(dead_code)]
232
            #[inline]
233
106124
            unsafe fn get_unchecked(&self, index: usize) -> &$struct_type {
234
106124
                unsafe { self.as_ref().get_unchecked(index) }
235
106124
            }
236

            
237
            /// Returns the vec as a Rust slice (Rust-only, not C-API compatible).
238
            #[inline]
239
            #[must_use]
240
242876728
            pub fn as_slice(&self) -> &[$struct_type] {
241
242876728
                self.as_ref()
242
242876728
            }
243

            
244
            /// Returns a C-compatible slice of the entire Vec.
245
            #[inline]
246
            #[must_use]
247
26
            pub const fn as_c_slice(&self) -> $slice_name {
248
26
                $slice_name {
249
26
                    ptr: self.ptr,
250
26
                    len: self.len,
251
26
                }
252
26
            }
253

            
254
            /// Returns a C-compatible slice of a range within the Vec.
255
            /// If the range is out of bounds, it is clamped to the valid range.
256
            #[inline]
257
            #[must_use]
258
15
            pub fn as_c_slice_range(&self, start: usize, end: usize) -> $slice_name {
259
15
                let start = start.min(self.len);
260
15
                let end = end.min(self.len).max(start);
261
15
                let len = end - start;
262
15
                if len == 0 || self.ptr.is_null() {
263
7
                    $slice_name::empty()
264
                } else {
265
8
                    $slice_name {
266
8
                        ptr: unsafe { self.ptr.add(start) },
267
8
                        len,
268
8
                    }
269
                }
270
15
            }
271

            
272
            /// Returns a pointer to the Vec's data.
273
            /// Use `len()` to get the number of elements.
274
            #[inline]
275
            #[must_use]
276
11115
            pub const fn as_ptr(&self) -> *const $struct_type {
277
11115
                self.ptr
278
11115
            }
279
        }
280

            
281
        impl AsRef<[$struct_type]> for $struct_name {
282
888162686
            fn as_ref(&self) -> &[$struct_type] {
283
888162686
                if self.ptr.is_null() || self.len == 0 {
284
247348568
                    &[]
285
                } else {
286
640814118
                    unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
287
                }
288
888162686
            }
289
        }
290

            
291
        impl Default for $struct_name {
292
4865643
            fn default() -> Self {
293
4865643
                Self::from_vec(alloc::vec::Vec::new())
294
4865643
            }
295
        }
296

            
297
        impl core::iter::FromIterator<$struct_type> for $struct_name {
298
14
            fn from_iter<T>(iter: T) -> Self
299
14
            where
300
14
                T: IntoIterator<Item = $struct_type>,
301
            {
302
14
                Self::from_vec(alloc::vec::Vec::from_iter(iter))
303
14
            }
304
        }
305

            
306
        impl From<alloc::vec::Vec<$struct_type>> for $struct_name {
307
42804453
            fn from(input: alloc::vec::Vec<$struct_type>) -> $struct_name {
308
42804453
                $struct_name::from_vec(input)
309
42804453
            }
310
        }
311

            
312
        impl From<&'static [$struct_type]> for $struct_name {
313
5390
            fn from(input: &'static [$struct_type]) -> $struct_name {
314
5390
                Self::from_const_slice(input)
315
5390
            }
316
        }
317

            
318
        impl Drop for $struct_name {
319
174170191
            fn drop(&mut self) {
320
174170191
                match self.destructor {
321
                    $destructor_name::DefaultRust => {
322
                        // Defensive: a library-owned Vec only owns an allocation
323
                        // when `ptr` is non-null and `cap != 0`. A zeroed / moved-
324
                        // from FFI husk (e.g. a struct field a C++ wrapper move-
325
                        // cleared, leaving destructor == DefaultRust [tag 0] with a
326
                        // null ptr but a stale len) would otherwise hit
327
                        // `Vec::from_raw_parts(null, len, _)` and deref 0x0 on drop.
328
                        // Skip when there is nothing to free. (Empty Vecs have
329
                        // cap == 0; valid non-empty Vecs are unaffected.)
330
118098792
                        if !self.ptr.is_null() && self.cap != 0 {
331
87946439
                            drop(unsafe {
332
87946439
                                alloc::vec::Vec::from_raw_parts(
333
87946439
                                    self.ptr.cast_mut(),
334
87946439
                                    self.len,
335
87946439
                                    self.cap,
336
87946439
                                )
337
87946439
                            });
338
87946439
                        }
339
118098792
                        self.destructor = $destructor_name::AlreadyDestroyed;
340
                    }
341
29125
                    $destructor_name::External(f) => {
342
29125
                        f(self);
343
29125
                        self.destructor = $destructor_name::AlreadyDestroyed;
344
29125
                    }
345
56042274
                    $destructor_name::NoDestructor | $destructor_name::AlreadyDestroyed => {}
346
                }
347
174170191
            }
348
        }
349
    };
350
}
351

            
352
/// Implement the `From` trait for any type.
353
/// Example usage:
354
/// ```no_run,ignore
355
/// enum MyError<'a> {
356
///     Bar(BarError<'a>),
357
///     Foo(FooError<'a>)
358
/// }
359
///
360
/// impl_from!(BarError<'a>, MyError::Bar);
361
/// impl_from!(FooError<'a>, MyError::Foo);
362
/// ```
363
macro_rules! impl_from {
364
    // From a type with a lifetime to a type which also has a lifetime
365
    ($a:ident < $c:lifetime > , $b:ident:: $enum_type:ident) => {
366
        impl<$c> From<$a<$c>> for $b<$c> {
367
43750
            fn from(e: $a<$c>) -> Self {
368
43750
                $b::$enum_type(e)
369
43750
            }
370
        }
371
    };
372

            
373
    // (No "non-lifetime → lifetime-bearing target" arm: it can only generate
374
    // `impl<'a> From<A> for B<'a>` where 'a is single-use, which trips
375
    // single_use_lifetimes. Write those impls out by hand with `B<'_>` instead.)
376

            
377
    // From a type without a lifetime to a type which also does not have a lifetime
378
    ($a:ident, $b:ident:: $enum_type:ident) => {
379
        impl From<$a> for $b {
380
            fn from(e: $a) -> Self {
381
                $b::$enum_type(e)
382
            }
383
        }
384
    };
385
}
386

            
387
/// Implement `Display` for an enum.
388
///
389
/// Example usage:
390
/// ```no_run,ignore
391
/// enum Foo<'a> {
392
///     Bar(&'a str),
393
///     Baz(i32)
394
/// }
395
///
396
/// impl_display!{ Foo<'a>, {
397
///     Bar(s) => s,
398
///     Baz(i) => format!("{}", i)
399
/// }}
400
/// ```
401
#[macro_export]
402
macro_rules! impl_display {
403
    // For a type with a lifetime
404
    ($enum:ident<$lt:lifetime>, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
405

            
406
        impl ::core::fmt::Display for $enum<'_> {
407
1022
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
408
                use self::$enum::*;
409
1022
                match &self {
410
                    $(
411
580
                        $variant => write!(f, "{}", $fmt_string),
412
                    )+
413
                }
414
1022
            }
415
        }
416

            
417
    };
418

            
419
    // For a type without a lifetime
420
    ($enum:ident, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
421

            
422
        impl ::core::fmt::Display for $enum {
423
41
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
424
                use self::$enum::*;
425
41
                match &self {
426
                    $(
427
19
                        $variant => write!(f, "{}", $fmt_string),
428
                    )+
429
                }
430
41
            }
431
        }
432

            
433
    };
434
}
435

            
436
/// Implements `Debug` to use `Display` instead - assumes the that the type has implemented
437
/// `Display`
438
#[macro_export]
439
macro_rules! impl_debug_as_display {
440
    // For a type with a lifetime
441
    ($enum:ident < $lt:lifetime >) => {
442
        impl ::core::fmt::Debug for $enum<'_> {
443
105
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
444
105
                write!(f, "{}", self)
445
105
            }
446
        }
447
    };
448

            
449
    // For a type without a lifetime
450
    ($enum:ident) => {
451
        impl ::core::fmt::Debug for $enum {
452
10
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
453
10
                write!(f, "{}", self)
454
10
            }
455
        }
456
    };
457
}
458

            
459
#[macro_export]
460
macro_rules! impl_vec_as_hashmap {
461
    ($struct_type:ident, $struct_name:ident) => {
462
        impl $struct_name {
463
24
            pub fn insert_hm_item(&mut self, item: $struct_type) {
464
24
                if !self.contains_hm_item(&item) {
465
24
                    self.push(item);
466
24
                }
467
24
            }
468

            
469
            pub fn remove_hm_item(&mut self, remove_key: &$struct_type) {
470
                *self = Self::from_vec(
471
                    self.as_ref()
472
                        .iter()
473
                        .filter_map(|r| if *r == *remove_key { None } else { Some(*r) })
474
                        .collect::<Vec<_>>(),
475
                );
476
            }
477

            
478
24
            pub fn contains_hm_item(&self, searched: &$struct_type) -> bool {
479
24
                self.as_ref().iter().any(|i| i == searched)
480
24
            }
481
        }
482
    };
483
}
484

            
485
/// NOTE: `impl_vec_mut` can only exist for vectors that are known to be library-allocated!
486
#[macro_export]
487
macro_rules! impl_vec_mut {
488
    ($struct_type:ident, $struct_name:ident) => {
489
        impl<'a> IntoIterator for &'a mut $struct_name {
490
            type Item = &'a mut $struct_type;
491
            type IntoIter = core::slice::IterMut<'a, $struct_type>;
492
            #[inline]
493
845
            fn into_iter(self) -> Self::IntoIter {
494
845
                self.iter_mut()
495
845
            }
496
        }
497

            
498
        impl AsMut<[$struct_type]> for $struct_name {
499
6592994
            fn as_mut(&mut self) -> &mut [$struct_type] {
500
6592994
                unsafe { core::slice::from_raw_parts_mut(self.ptr.cast_mut(), self.len) }
501
6592994
            }
502
        }
503

            
504
        impl From<$struct_name> for alloc::vec::Vec<$struct_type> {
505
            #[allow(unused_mut)]
506
5537
            fn from(mut input: $struct_name) -> alloc::vec::Vec<$struct_type> {
507
5537
                input.into_library_owned_vec()
508
5537
            }
509
        }
510

            
511
        impl core::iter::Extend<$struct_type> for $struct_name {
512
1
            fn extend<T: core::iter::IntoIterator<Item = $struct_type>>(&mut self, iter: T) {
513
5
                for elem in iter {
514
4
                    self.push(elem);
515
4
                }
516
1
            }
517
        }
518

            
519
        impl $struct_name {
520
            #[inline]
521
1071873
            pub const fn as_mut_ptr(&mut self) -> *mut $struct_type {
522
1071873
                self.ptr.cast_mut()
523
1071873
            }
524

            
525
            #[inline]
526
240
            pub fn sort_by<F: FnMut(&$struct_type, &$struct_type) -> core::cmp::Ordering>(
527
240
                &mut self,
528
240
                compare: F,
529
240
            ) {
530
240
                self.as_mut().sort_by(compare);
531
240
            }
532

            
533
            #[inline]
534
986163
            pub fn push(&mut self, value: $struct_type) {
535
                // code is copied from the rust stdlib, since it's not possible to
536
                // create a temporary Vec here. Doing that would create two
537
986163
                if self.len == self.capacity() {
538
352993
                    self.buf_reserve(self.len, 1);
539
633172
                }
540
986163
                unsafe {
541
986163
                    let end = self.as_mut_ptr().add(self.len);
542
986163
                    core::ptr::write(end, value);
543
986163
                    self.len += 1;
544
986163
                }
545
986163
            }
546

            
547
4
            pub fn insert(&mut self, index: usize, element: $struct_type) {
548
4
                let len = self.len();
549
4
                if index > len {
550
2
                    return;
551
2
                }
552

            
553
                // space for the new element
554
2
                if len == self.capacity() {
555
1
                    self.reserve(1);
556
1
                }
557

            
558
2
                unsafe {
559
2
                    // infallible
560
2
                    // The spot to put the new value
561
2
                    {
562
2
                        let p = self.as_mut_ptr().add(index);
563
2
                        // Shift everything over to make space. (Duplicating the
564
2
                        // `index`th element into two consecutive places.)
565
2
                        core::ptr::copy(p, p.offset(1), len - index);
566
2
                        // Write it in, overwriting the first copy of the `index`th
567
2
                        // element.
568
2
                        core::ptr::write(p, element);
569
2
                    }
570
2
                    self.set_len(len + 1);
571
2
                }
572
4
            }
573

            
574
18
            pub fn remove(&mut self, index: usize) {
575
18
                let len = self.len();
576
18
                if index >= len {
577
2
                    return;
578
16
                }
579

            
580
16
                unsafe {
581
16
                    // infallible
582
16
                    let ret;
583
16
                    {
584
16
                        // the place we are taking from.
585
16
                        let ptr = self.as_mut_ptr().add(index);
586
16
                        // copy it out, unsafely having a copy of the value on
587
16
                        // the stack and in the vector at the same time.
588
16
                        ret = core::ptr::read(ptr);
589
16

            
590
16
                        // Shift everything down to fill in that spot.
591
16
                        core::ptr::copy(ptr.offset(1), ptr, len - index - 1);
592
16
                    }
593
16
                    self.set_len(len - 1);
594
16
                    // Named binding (not `let _ =` / `drop()`): this macro is
595
16
                    // generic over the element type, so a bare drop trips
596
16
                    // dropping_copy_types for Copy elements while `let _ =` trips
597
16
                    // let_underscore_drop for ones with a destructor. A named
598
16
                    // unused binding drops at scope end and satisfies both.
599
16
                    let _ret = ret;
600
16
                }
601
18
            }
602

            
603
            #[inline]
604
3
            pub const fn pop(&mut self) -> Option<$struct_type> {
605
3
                if self.len == 0 {
606
2
                    None
607
                } else {
608
                    unsafe {
609
1
                        self.len -= 1;
610
1
                        Some(core::ptr::read(self.ptr.add(self.len())))
611
                    }
612
                }
613
3
            }
614

            
615
            #[inline]
616
999260
            pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, $struct_type> {
617
999260
                self.as_mut().iter_mut()
618
999260
            }
619

            
620
            #[inline]
621
            #[must_use]
622
23
            pub fn into_iter(self) -> alloc::vec::IntoIter<$struct_type> {
623
23
                let v1: alloc::vec::Vec<$struct_type> = self.into();
624
23
                v1.into_iter()
625
23
            }
626

            
627
            #[inline]
628
381472
            fn amortized_new_size(
629
381472
                &self,
630
381472
                used_cap: usize,
631
381472
                needed_extra_cap: usize,
632
381472
            ) -> Result<usize, bool> {
633
                // Nothing we can really do about these checks :(
634
381472
                let required_cap = used_cap.checked_add(needed_extra_cap).ok_or(true)?;
635
                // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
636
381472
                let double_cap = self.cap * 2;
637
                // `double_cap` guarantees exponential growth.
638
381472
                Ok(core::cmp::max(double_cap, required_cap))
639
381472
            }
640

            
641
            #[inline]
642
381472
            const fn current_layout(&self) -> Option<core::alloc::Layout> {
643
381472
                if self.cap == 0 {
644
335104
                    None
645
                } else {
646
                    // We have an allocated chunk of memory, so we can bypass runtime
647
                    // checks to get our current layout.
648
                    unsafe {
649
46368
                        let align = core::mem::align_of::<$struct_type>();
650
46368
                        let size = core::mem::size_of::<$struct_type>() * self.cap;
651
46368
                        Some(core::alloc::Layout::from_size_align_unchecked(size, align))
652
                    }
653
                }
654
381472
            }
655

            
656
            #[inline]
657
381472
            const fn alloc_guard(alloc_size: usize) -> Result<(), bool> {
658
381472
                if core::mem::size_of::<usize>() < 8 && alloc_size > ::core::isize::MAX as usize {
659
                    Err(true)
660
                } else {
661
381472
                    Ok(())
662
                }
663
381472
            }
664

            
665
            #[inline]
666
            // the reallocated pointer comes from the global allocator with a Layout
667
            // computed for `$struct_type`, so it is correctly aligned for the cast.
668
            #[allow(clippy::cast_ptr_alignment)]
669
382355
            fn try_reserve(
670
382355
                &mut self,
671
382355
                used_cap: usize,
672
382355
                needed_extra_cap: usize,
673
382355
            ) -> Result<(), bool> {
674
                // NOTE: we don't early branch on ZSTs here because we want this
675
                // to actually catch "asking for more than usize::MAX" in that case.
676
                // If we make it past the first branch then we are guaranteed to
677
                // panic.
678

            
679
                // Don't actually need any more capacity.
680
                // Wrapping in case they give a bad `used_cap`
681
382355
                if self.capacity().wrapping_sub(used_cap) >= needed_extra_cap {
682
883
                    return Ok(());
683
381472
                }
684

            
685
381472
                let new_cap = self.amortized_new_size(used_cap, needed_extra_cap)?;
686
381472
                let new_layout =
687
381472
                    alloc::alloc::Layout::array::<$struct_type>(new_cap).map_err(|_| true)?;
688

            
689
381472
                $struct_name::alloc_guard(new_layout.size())?;
690

            
691
                // ONLY a buffer we allocated ourselves (`DefaultRust`) may be handed to
692
                // `realloc`. `current_layout()` reports `Some` for any `cap != 0`, which
693
                // is NOT the same question: a vec built by `from_const_slice` points at
694
                // `&'static` memory (`NoDestructor`), and one handed over by C owns its
695
                // buffer elsewhere (`External`). Realloc'ing either would tell the Rust
696
                // allocator to free memory it never handed out.
697
                //
698
                // Everything else therefore gets a fresh allocation with the existing
699
                // elements copied across.
700
381472
                let owns_buffer = self.owns_buffer();
701

            
702
381472
                let res = unsafe {
703
381472
                    match self.current_layout() {
704
46368
                        Some(layout) if owns_buffer => alloc::alloc::realloc(
705
46368
                            self.ptr.cast::<u8>().cast_mut(),
706
46368
                            layout,
707
46368
                            new_layout.size(),
708
                        ),
709
                        _ => {
710
335104
                            let fresh = alloc::alloc::alloc(new_layout);
711
                            // NOTE: for `External`, the original buffer is left for its
712
                            // owner to free — we must not touch it. That orphans its
713
                            // destructor, but leaking is strictly better than the
714
                            // cross-allocator free this used to do.
715
335104
                            if !fresh.is_null() && self.len > 0 {
716
                                core::ptr::copy_nonoverlapping(
717
                                    self.ptr,
718
                                    fresh.cast::<$struct_type>(),
719
                                    self.len,
720
                                );
721
335104
                            }
722
335104
                            fresh
723
                        }
724
                    }
725
                };
726

            
727
381472
                if res.is_null() {
728
                    return Err(false);
729
381472
                }
730

            
731
381472
                self.ptr = res as *mut $struct_type;
732
381472
                self.cap = new_cap;
733
                // The buffer is now heap memory WE own, whatever it was before, so the
734
                // tag has to follow. Leaving it as `NoDestructor` was a use-after-free:
735
                // `clone_self` branches on this tag and would take the shallow
736
                // pointer-copy path, so the clone and the original aliased one
737
                // allocation — and the next growth realloc'd it out from under the other
738
                // side. (`Drop` would also have leaked it.)
739
381472
                self.mark_rust_owned();
740

            
741
381472
                Ok(())
742
382355
            }
743

            
744
382355
            fn buf_reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
745
382355
                match self.try_reserve(used_cap, needed_extra_cap) {
746
                    Err(true /* Overflow */) => {
747
                        panic!("memory allocation failed: overflow");
748
                    }
749
                    Err(false /* AllocError(_) */) => {
750
                        panic!("memory allocation failed: error allocating new memory");
751
                    }
752
382355
                    Ok(()) => { /* yay */ }
753
                }
754
382355
            }
755

            
756
1816
            pub fn append(&mut self, other: &mut Self) {
757
1816
                unsafe {
758
1816
                    self.append_elements(core::ptr::from_ref(other.as_slice()));
759
1816
                    other.set_len(0);
760
1816
                }
761
1816
            }
762

            
763
1834
            unsafe fn set_len(&mut self, new_len: usize) {
764
1834
                debug_assert!(new_len <= self.capacity());
765
1834
                self.len = new_len;
766
1834
            }
767

            
768
1817
            pub fn reserve(&mut self, additional: usize) {
769
1817
                self.buf_reserve(self.len, additional);
770
1817
            }
771

            
772
            /// Appends elements to `Self` from other buffer.
773
            #[inline]
774
1816
            unsafe fn append_elements(&mut self, other: *const [$struct_type]) {
775
1816
                unsafe {
776
1816
                    let count = (&(*other)).len();
777
1816
                    self.reserve(count);
778
1816
                    let len = self.len();
779
1816
                    core::ptr::copy_nonoverlapping(
780
1816
                        other as *const $struct_type,
781
1816
                        self.as_mut_ptr().add(len),
782
1816
                        count,
783
1816
                    );
784
1816
                    self.len += count;
785
1816
                }
786
1816
            }
787

            
788
4
            pub fn truncate(&mut self, len: usize) {
789
                // This is safe because:
790
                //
791
                // * the slice passed to `drop_in_place` is valid; the `len > self.len` case avoids
792
                //   creating an invalid slice, and
793
                // * the `len` of the vector is shrunk before calling `drop_in_place`, such that no
794
                //   value will be dropped twice in case `drop_in_place` were to panic once (if it
795
                //   panics twice, the program aborts).
796
                unsafe {
797
4
                    if len > self.len {
798
1
                        return;
799
3
                    }
800
3
                    let remaining_len = self.len - len;
801
3
                    let s = core::ptr::slice_from_raw_parts_mut(
802
3
                        self.as_mut_ptr().add(len),
803
3
                        remaining_len,
804
                    );
805
3
                    self.len = len;
806
3
                    core::ptr::drop_in_place(s);
807
                }
808
4
            }
809

            
810
88531
            pub fn retain<F>(&mut self, mut f: F)
811
88531
            where
812
88531
                F: FnMut(&$struct_type) -> bool,
813
            {
814
88531
                let len = self.len();
815
88531
                let mut del = 0;
816

            
817
                {
818
106504
                    for i in 0..len {
819
106124
                        if unsafe { !f(self.get_unchecked(i)) } {
820
128
                            del += 1;
821
105996
                        } else if del > 0 {
822
127
                            self.as_mut().swap(i - del, i);
823
105869
                        }
824
                    }
825
                }
826

            
827
88531
                if del > 0 {
828
2
                    self.truncate(len - del);
829
88529
                }
830
88531
            }
831
        }
832
    };
833
}
834

            
835
#[macro_export]
836
macro_rules! impl_vec_debug {
837
    ($struct_type:ident, $struct_name:ident) => {
838
        impl core::fmt::Debug for $struct_name {
839
1704
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
840
1704
                self.as_ref().fmt(f)
841
1704
            }
842
        }
843
    };
844
}
845

            
846
#[macro_export]
847
macro_rules! impl_vec_partialord {
848
    ($struct_type:ident, $struct_name:ident) => {
849
        impl PartialOrd for $struct_name {
850
39
            fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
851
39
                self.as_ref().partial_cmp(rhs.as_ref())
852
39
            }
853
        }
854
    };
855
}
856

            
857
#[macro_export]
858
macro_rules! impl_vec_ord {
859
    ($struct_type:ident, $struct_name:ident) => {
860
        impl Ord for $struct_name {
861
42
            fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
862
42
                self.as_ref().cmp(rhs.as_ref())
863
42
            }
864
        }
865
    };
866
}
867

            
868
#[macro_export]
869
macro_rules! impl_vec_clone {
870
    ($struct_type:ident, $struct_name:ident, $destructor_name:ident) => {
871
        impl $struct_name {
872
            // Creates a `Vec` from a `Cow<'static, [T]>` - useful to avoid allocating in the case
873
            // of &'static memory
874
            #[inline]
875
            #[must_use]
876
            pub fn from_copy_on_write(
877
                input: alloc::borrow::Cow<'static, [$struct_type]>,
878
            ) -> $struct_name {
879
                match input {
880
                    alloc::borrow::Cow::Borrowed(static_array) => {
881
                        Self::from_const_slice(static_array)
882
                    }
883
                    alloc::borrow::Cow::Owned(owned_vec) => Self::from_vec(owned_vec),
884
                }
885
            }
886

            
887
            /// Creates a Vec containing a single element
888
            #[inline]
889
            #[must_use]
890
17
            pub fn from_item(item: $struct_type) -> Self {
891
17
                Self::from_vec(alloc::vec![item])
892
17
            }
893

            
894
            /// Copies elements from a C array pointer into a new Vec.
895
            ///
896
            /// # Safety
897
            /// - `ptr` must be valid for reading `len` elements
898
            /// - The memory must be properly aligned for `$struct_type`
899
            /// - The elements are cloned, so `$struct_type` must implement `Clone`
900
            #[inline]
901
            #[must_use]
902
            pub unsafe fn copy_from_ptr(ptr: *const $struct_type, len: usize) -> Self {
903
                unsafe {
904
                    if ptr.is_null() || len == 0 {
905
                        return Self::new();
906
                    }
907
                    let slice = core::slice::from_raw_parts(ptr, len);
908
                    Self::from_vec(slice.to_vec())
909
                }
910
            }
911

            
912
            /// NOTE: CLONES the memory if the memory is external or &'static
913
            /// Moves the memory out if the memory is library-allocated
914
            #[inline]
915
            #[must_use]
916
36433759
            pub fn clone_self(&self) -> Self {
917
36433759
                match self.destructor {
918
21971844
                    $destructor_name::NoDestructor | $destructor_name::AlreadyDestroyed => Self {
919
21971844
                        ptr: self.ptr,
920
21971844
                        len: self.len,
921
21971844
                        cap: self.cap,
922
21971844
                        destructor: $destructor_name::NoDestructor,
923
21971844
                    },
924
                    $destructor_name::External(_) | $destructor_name::DefaultRust => {
925
14461915
                        Self::from_vec(self.as_ref().to_vec())
926
                    }
927
                }
928
36433759
            }
929

            
930
            /// NOTE: CLONES the memory if the memory is external or &'static
931
            /// Moves the memory out if the memory is library-allocated
932
            #[inline]
933
            #[must_use]
934
4443491
            pub fn into_library_owned_vec(self) -> alloc::vec::Vec<$struct_type> {
935
4443491
                match self.destructor {
936
                    $destructor_name::NoDestructor
937
                    | $destructor_name::External(_)
938
2064355
                    | $destructor_name::AlreadyDestroyed => self.as_ref().to_vec(),
939
                    $destructor_name::DefaultRust => {
940
2379136
                        let v = unsafe {
941
2379136
                            alloc::vec::Vec::from_raw_parts(self.ptr.cast_mut(), self.len, self.cap)
942
                        };
943
2379136
                        core::mem::forget(self);
944
2379136
                        v
945
                    }
946
                }
947
4443491
            }
948
        }
949
        impl Clone for $struct_name {
950
28905799
            fn clone(&self) -> Self {
951
28905799
                self.clone_self()
952
28905799
            }
953
        }
954
    };
955
}
956

            
957
#[macro_export]
958
macro_rules! impl_vec_partialeq {
959
    ($struct_type:ident, $struct_name:ident) => {
960
        impl PartialEq for $struct_name {
961
2974435
            fn eq(&self, rhs: &Self) -> bool {
962
2974435
                self.as_ref().eq(rhs.as_ref())
963
2974435
            }
964
        }
965
    };
966
}
967

            
968
#[macro_export]
969
macro_rules! impl_vec_eq {
970
    ($struct_type:ident, $struct_name:ident) => {
971
        impl Eq for $struct_name {}
972
    };
973
}
974

            
975
#[macro_export]
976
macro_rules! impl_vec_hash {
977
    ($struct_type:ident, $struct_name:ident) => {
978
        impl core::hash::Hash for $struct_name {
979
365889
            fn hash<H>(&self, state: &mut H)
980
365889
            where
981
365889
                H: core::hash::Hasher,
982
            {
983
365889
                self.as_ref().hash(state);
984
365889
            }
985
        }
986
    };
987
}
988

            
989
#[macro_export]
990
macro_rules! impl_option_inner {
991
    ($struct_type:ident, $struct_name:ident) => {
992
        impl From<$struct_name> for Option<$struct_type> {
993
146
            fn from(o: $struct_name) -> Option<$struct_type> {
994
146
                match o {
995
73
                    $struct_name::None => None,
996
73
                    $struct_name::Some(t) => Some(t),
997
                }
998
146
            }
999
        }
        impl From<Option<$struct_type>> for $struct_name {
2662168
            fn from(o: Option<$struct_type>) -> $struct_name {
2662168
                match o {
2174918
                    None => $struct_name::None,
487250
                    Some(t) => $struct_name::Some(t),
                }
2662168
            }
        }
        impl Default for $struct_name {
5003671
            fn default() -> $struct_name {
5003671
                $struct_name::None
5003671
            }
        }
        impl $struct_name {
            #[must_use]
69588
            pub const fn as_option(&self) -> Option<&$struct_type> {
69588
                match self {
46942
                    $struct_name::None => None,
22646
                    $struct_name::Some(t) => Some(t),
                }
69588
            }
            // Returns the PREVIOUS value (mem::replace semantics); callers may discard it,
            // so #[must_use] would be wrong here.
            #[allow(clippy::return_self_not_must_use)]
19
            pub const fn replace(&mut self, value: $struct_type) -> $struct_name {
19
                ::core::mem::replace(self, $struct_name::Some(value))
19
            }
            #[must_use]
70222
            pub const fn is_some(&self) -> bool {
70222
                match self {
64023
                    $struct_name::None => false,
6199
                    $struct_name::Some(_) => true,
                }
70222
            }
            #[must_use]
2948
            pub const fn is_none(&self) -> bool {
2948
                !self.is_some()
2948
            }
            #[must_use]
244452
            pub const fn as_ref(&self) -> Option<&$struct_type> {
244452
                match *self {
168236
                    $struct_name::Some(ref x) => Some(x),
76216
                    $struct_name::None => None,
                }
244452
            }
1604
            pub const fn as_mut(&mut self) -> Option<&mut $struct_type> {
1604
                match self {
189
                    $struct_name::Some(x) => Some(x),
1415
                    $struct_name::None => None,
                }
1604
            }
40
            pub fn map<U, F: FnOnce($struct_type) -> U>(self, f: F) -> Option<U> {
40
                match self {
35
                    $struct_name::Some(x) => Some(f(x)),
5
                    $struct_name::None => None,
                }
40
            }
13
            pub fn and_then<U, F>(self, f: F) -> Option<U>
13
            where
13
                F: FnOnce($struct_type) -> Option<U>,
            {
13
                match self {
3
                    $struct_name::None => None,
10
                    $struct_name::Some(x) => f(x),
                }
13
            }
        }
    };
}
#[macro_export]
macro_rules! impl_option {
    ($struct_type:ident, $struct_name:ident, copy = false, clone = false, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        pub enum $struct_name {
            None,
            Some($struct_type)
        }
        impl $struct_name {
            pub fn into_option(self) -> Option<$struct_type> {
                match self {
                    $struct_name::None => None,
                    $struct_name::Some(t) => Some(t),
                }
            }
        }
        impl_option_inner!($struct_type, $struct_name);
    );
    ($struct_type:ident, $struct_name:ident, copy = false, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        // This arm (copy = false) deliberately does NOT derive Copy so the
        // wrapper can hold non-Copy payloads; missing_copy_implementations is a
        // false positive for the Copy-payload instantiations routed through here.
        #[allow(missing_copy_implementations, variant_size_differences)]
        pub enum $struct_name {
            None,
            Some($struct_type)
        }
        impl $struct_name {
638294
            #[must_use] pub fn into_option(&self) -> Option<$struct_type> {
638294
                match self {
523982
                    $struct_name::None => None,
114312
                    $struct_name::Some(t) => Some(t.clone()),
                }
638294
            }
        }
        impl_option_inner!($struct_type, $struct_name);
    );
    ($struct_type:ident, $struct_name:ident, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        // This (default) arm does NOT derive Copy so the wrapper can hold
        // non-Copy payloads; missing_copy_implementations is a false positive
        // for the Copy-payload instantiations routed through here.
        #[allow(missing_copy_implementations, variant_size_differences)]
        pub enum $struct_name {
            None,
            Some($struct_type)
        }
        impl $struct_name {
188961
            #[must_use] pub fn into_option(&self) -> Option<$struct_type> {
188961
                match self {
83341
                    $struct_name::None => None,
105620
                    $struct_name::Some(t) => Some(t.clone()),
                }
188961
            }
        }
        impl_option_inner!($struct_type, $struct_name);
    );
}
#[macro_export]
macro_rules! impl_result_inner {
    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident) => {
        impl From<$struct_name> for Result<$ok_struct_type, $err_struct_type> {
2
            fn from(o: $struct_name) -> Result<$ok_struct_type, $err_struct_type> {
2
                match o {
1
                    $struct_name::Ok(o) => Ok(o),
1
                    $struct_name::Err(e) => Err(e),
                }
2
            }
        }
        impl From<Result<$ok_struct_type, $err_struct_type>> for $struct_name {
32
            fn from(o: Result<$ok_struct_type, $err_struct_type>) -> $struct_name {
32
                match o {
29
                    Ok(o) => $struct_name::Ok(o),
3
                    Err(e) => $struct_name::Err(e),
                }
32
            }
        }
        impl $struct_name {
26
            pub fn as_result(&self) -> Result<&$ok_struct_type, &$err_struct_type> {
26
                match self {
3
                    $struct_name::Ok(o) => Ok(o),
23
                    $struct_name::Err(e) => Err(e),
                }
26
            }
299
            pub fn is_ok(&self) -> bool {
299
                match self {
7
                    $struct_name::Ok(_) => true,
292
                    $struct_name::Err(_) => false,
                }
299
            }
292
            pub fn is_err(&self) -> bool {
292
                !self.is_ok()
292
            }
        }
    };
}
#[macro_export]
macro_rules! impl_result {
    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident, copy = false, clone = false, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        pub enum $struct_name {
            Ok($ok_struct_type),
            Err($err_struct_type)
        }
        impl $struct_name {
4
            pub fn into_result(self) -> Result<$ok_struct_type, $err_struct_type> {
4
                match self {
2
                    $struct_name::Ok(o) => Ok(o),
2
                    $struct_name::Err(e) => Err(e),
                }
4
            }
        }
        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
    );
    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident, copy = false, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        pub enum $struct_name {
            Ok($ok_struct_type),
            Err($err_struct_type)
        }
        impl $struct_name {
            pub fn into_result(&self) -> Result<$ok_struct_type, $err_struct_type> {
                match self {
                    $struct_name::Ok(o) => Ok(o.clone()),
                    $struct_name::Err(e) => Err(e.clone()),
                }
            }
        }
        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
    );
    ($ok_struct_type:ident, $err_struct_type:ident,  $struct_name:ident, [$($derive:meta),* ]) => (
        $(#[derive($derive)])*
        #[repr(C, u8)]
        pub enum $struct_name {
            Ok($ok_struct_type),
            Err($err_struct_type)
        }
        impl $struct_name {
            pub fn into_result(&self) -> Result<$ok_struct_type, $err_struct_type> {
                match self {
                    $struct_name::Ok(o) => Ok(*o),
                    $struct_name::Err(e) => Err(*e),
                }
            }
        }
        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
    );
}
macro_rules! impl_color_value_fmt {
    ($struct_name:ty) => {
        impl FormatAsRustCode for $struct_name {
            fn format_as_rust_code(&self, _tabs: usize) -> String {
                format!(
                    "{} {{ inner: {} }}",
                    stringify!($struct_name),
                    format_color_value(&self.inner)
                )
            }
        }
    };
}
macro_rules! impl_enum_fmt {($enum_name:ident, $($enum_type:ident),+) => (
    impl crate::codegen::format::FormatAsRustCode for $enum_name {
3
        fn format_as_rust_code(&self, _tabs: usize) -> String {
3
            match self {
                $(
                    $enum_name::$enum_type => {
1
                        String::from(
                            concat!(stringify!($enum_name), "::", stringify!($enum_type))
                        )
                    },
                )+
            }
3
        }
    }
)}