ndd 0.2.12

Non De-Duplicated cell. For statics guaranteed not to share memory with any other static/const.
Documentation
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
// Override link URLs for local rustdoc and for docs.rs.
//
// Keep the following links in the same order as they appear in ../README.md. See also bottom of
// ../README.md.
//! [`ndd::NonDeDuplicated`]: crate::NonDeDuplicated
//! [`ndd::NonDeDuplicatedStr`]: crate::NonDeDuplicatedStr
//! [`ndd::NonDeDuplicatedCStr`]: crate::NonDeDuplicatedCStr
//! [`src/lib.rs`]: https://github.com/peter-lyons-kehl/ndd/blob/main/src/lib.rs
//! [`demo_fix/callee/src/lib.rs`]:
//!     https://github.com/peter-lyons-kehl/ndd/blob/main/demo_fix/callee/src/lib.rs
//! [`core::ptr::eq`]: core::ptr::eq
//! [`core::ptr::addr_eq`]: core::ptr::addr_eq
//! [`src/lib.rs` -> `tests_without_ndd` -> `addresses_unique_between_statics()`]:
//!     https://github.com/peter-lyons-kehl/ndd/blob/main/src/lib.rs#L269
//! [`demo_bug/`]: https://github.com/peter-lyons-kehl/ndd/tree/main/demo_bug
//! [`core::cell::Cell`]: core::cell::Cell
//! [`core::marker::Sync`]: core::marker::Sync
//! [`core::marker::Send`]: core::marker::Send
//! [`std::sync::Mutex`]: std::sync::Mutex#impl-Sync-for-Mutex<T>
//! [`src/lib.rs` -> `tests_with_ndd`]:
//!     https://github.com/peter-lyons-kehl/ndd/blob/main/src/lib.rs#L355
//! [`alloc`]: alloc
//! [`core::ops::Drop`]: core::ops::Drop
//! [`pre-commit`]: https://github.com/peter-lyons-kehl/ndd/blob/main/pre-commit
//! [GitHub Actions]: https://github.com/peter-lyons-kehl/ndd/blob/main/.github/workflows/main.yml
//!
//! [`core::cell::Cell::as_array_of_cells`]: core::cell::Cell::as_array_of_cells
//! [`core::ops::Deref`]: core::ops::Deref
//! [`core::convert::From`]: core::convert::From
//!
//! [`demo_bug/non_lto`]: https://github.com/peter-lyons-kehl/ndd/tree/main/demo_bug/non_lto/
//! [`demo_bug/fat_lto`]: https://github.com/peter-lyons-kehl/ndd/tree/main/demo_bug/fat_lto/
//! [`demo_fix/fat_lto`]: https://github.com/peter-lyons-kehl/ndd/tree/main/demo_fix/fat_lto/
//! [`non_dedup.sh`]:
//!     https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_scripts/non_dedup.sh
//! [`dedup_out.sh`]:
//!     https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_scripts/dedup_out.sh
//! [`liter_str`]: https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_src/liter_str.rs
//! [`const_str`]: https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_src/const_str.rs
//! [`const_opt`]: https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_src/const_opt.rs
//! [`const_u8s`]: https://github.com/peter-lyons-kehl/ndd/blob/main/demo_shared_src/const_u8s.rs
#![doc = include_str!("../README.md")]
#![cfg_attr(not(any(doc, test)), no_std)]
#[cfg(doc)]
extern crate alloc;

use core::any::Any;
use core::cell::Cell;
use core::ffi::CStr;
use core::marker::PhantomData;

/// A zero-cost  wrapper guaranteed not to share its memory location with any other valid (in-scope)
/// variable (even `const` equal to the inner value). Use for `static` variables that have their
/// addresses compared with [core::ptr::eq].
///
/// It has same size, layout and alignment as type parameter `OWN`.
///
/// `T` must implement [Any]. That is automatic for any types that don't have any lifetimes (other
/// than `'static`). This requirement gives an earlier error when `NonDeDuplicated` is used other
/// than intended.
///
/// We don't just limit to be `:'static`, because then `NonDeDuplicated` could still be somewhat
/// used with non-static lifetimes, and the error would surface only later. The following **would**
/// compile:
/// ```rust
/// # use core::cell::Cell;
///
/// pub struct NonDeDuplicatedStatic<T: 'static> {
///    cell: Cell<T>,
///}
///
/// type NddU8ref<'a> = NonDeDuplicatedStatic<&'a u8>;
///
/// fn callee<'a>(r: NddU8ref<'a>) {}
/// ```
/// Only the following would then fail (to compile):
/// ```rust,ignore
/// fn caller<'a>(r: &'a u8) { let u = 0u8; callee(NonDeDuplicatedStatic::new(uref)); }
/// ```
///
/// But, by requiring [NonDeDuplicatedFlexible]'s generic parameter `OWN` (or [NonDeDuplicated]'s
/// generic parameter `T`) to implement [Any] the first example above fails, too. That prevents
/// mistakes earlier.
///
/// Do not use [NonDeDuplicatedFlexible] directly. Instead, use [NonDeDuplicated],
/// [NonDeDuplicatedStr] and [NonDeDuplicatedCStr].
#[repr(transparent)]
pub struct NonDeDuplicatedFlexible<OWN: Any + Send + Sync, TO: Any + Send + Sync + ?Sized> {
    cell: Cell<OWN>,
    _t: PhantomData<TO>,
}

/// For non-de-duplicated objects stored in `static` variables. NOT for string slices - for those
/// use [NonDeDuplicatedStr] and [NonDeDuplicatedCStr].
#[allow(type_alias_bounds)]
pub type NonDeDuplicated<T: Any + Send + Sync> = NonDeDuplicatedFlexible<T, T>;

impl<T: Any + Send + Sync> NonDeDuplicated<T> {
    /// Construct a new instance.
    pub const fn new(value: T) -> Self {
        Self {
            //Using core::hint::black_box() seems unnecessary.
            //cell: Cell::new(core::hint::black_box(value)),
            cell: Cell::new(value),
            _t: PhantomData,
        }
    }

    /// Get a reference.
    pub const fn get(&self) -> &T {
        let ptr = self.cell.as_ptr();
        unsafe { &*ptr }
    }
}

/// Separate from [bytes_to_array], so that we help monomorphization surface area to be smaller.
const fn copy_bytes_to_array(to: &mut [u8], from: &[u8], len: usize) {
    if from.len() > len {
        let msg = match from.len() - len {
            1 => "Target length is 1 byte too small.",
            2 => "Target length is 2 bytes too small.",
            3 => "Target length is 3 bytes too small.",
            4 => "Target length is 4 bytes too small.",
            _ => "Target length is more than 4 bytes too small.",
        };
        panic!("{}", msg)
    }
    if from.len() < len {
        let msg = match len - from.len() {
            1 => "Target length is 1 byte too large.",
            2 => "Target length is 2 bytes too large.",
            3 => "Target length is 3 bytes too large.",
            4 => "Target length is 4 bytes too large.",
            _ => "Target length is more than 4 bytes too large.",
        };
        panic!("{}", msg)
    }
    if to.len() != len {
        panic!("Target slice length differs to the specified length.")
    }

    let mut i = 0;
    while i < len {
        to[i] = from[i];
        i += 1;
    }
}

const fn bytes_to_array<const N: usize>(bytes: &[u8]) -> [u8; N] {
    let mut arr = [0u8; N];
    copy_bytes_to_array(&mut arr, bytes, N);
    arr
}

/// For non-de-duplicated string slices stored in `static` variables.
pub type NonDeDuplicatedStr<const N: usize> = NonDeDuplicatedFlexible<[u8; N], str>;
impl<const N: usize> NonDeDuplicatedStr<N> {
    /// Construct a new instance.
    pub const fn new(s: &str) -> Self {
        Self {
            cell: Cell::new(bytes_to_array(s.as_bytes())),
            _t: PhantomData,
        }
    }

    /// Get a reference.
    ///
    /// Implementation details: Since this type, and this function, is intended to be used for
    /// `static` variables only, speed doesn't matter here. So, we use [core::str::from_utf8]
    /// (instead of [core::str::from_utf8_unchecked]).
    pub const fn get(&self) -> &str {
        let ptr = self.cell.as_ptr();
        let bytes = unsafe { &*ptr };
        match core::str::from_utf8(bytes) {
            Ok(s) => s,
            Err(_) => unreachable!(),
        }
    }
}

/// For non-de-duplicated string slices stored in `static` variables.
pub type NonDeDuplicatedCStr<const N: usize> = NonDeDuplicatedFlexible<[u8; N], CStr>;
impl<const N: usize> NonDeDuplicatedCStr<N> {
    /// Construct a new instance.
    pub const fn new(s: &CStr) -> Self {
        Self {
            cell: Cell::new(bytes_to_array(s.to_bytes())),
            _t: PhantomData,
        }
    }

    /// The given `arr` must be a well-formed C string, that is,
    /// - **not** containing any internal NUL bytes, and
    /// - end with a NUL byte, like `b"abc\0"`.
    pub const fn new_from_bytes(arr: [u8; N]) -> Self {
        // Validate early, rather than waiting for validation by .get()
        let _ = core::hint::black_box(CStr::from_bytes_with_nul(&arr));
        Self {
            cell: Cell::new(arr),
            _t: PhantomData,
        }
    }

    ///  The `given &`[str] must, like C string, not contain any internal NUL bytes. However, do
    ///  **not** include the trailing NUL byte - that is added automatically.
    pub const fn new_from_str(s: &str) -> Self {
        let mut arr = [0u8; N];
        if let Some((_, sub_slice)) = arr.split_last_mut() {
            crate::copy_bytes_to_array(sub_slice, s.as_bytes(), s.len());
        } else {
            unreachable!()
        }
        Self::new_from_bytes(arr)
    }

    /// Get a reference.
    ///
    /// Implementation details: Since this type, and this function, is intended to be used for
    /// `static` variables only, speed doesn't matter here. So, we use [CStr::from_bytes_with_nul]
    /// (instead of [CStr::from_bytes_with_nul_unchecked]).
    pub const fn get(&self) -> &CStr {
        let ptr = self.cell.as_ptr();
        let bytes = unsafe { &*ptr };
        match CStr::from_bytes_with_nul(bytes) {
            Ok(s) => s,
            Err(_) => unreachable!(),
        }
    }
}

/// For now, [Sync] (and [NonDeDuplicatedFlexible] in general) requires that `OWN` is both [Sync]
/// AND [Send], following
/// [std::sync::Mutex](https://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E).
/// However, from <https://doc.rust-lang.org/nightly/core/marker/trait.Sync.html> it seems that `T:
/// Send` may be unnecessary? Please advise.
///
/// Either way, [NonDeDuplicated], [NonDeDuplicatedStr] and [NonDeDuplicatedCStr] (and underlying
/// [NonDeDuplicatedFlexible]) exist specifically for static variables. Those get never moved out.
/// So, (unlike [std::sync::Mutex]) they do **not** need to implement [Send].
///
/// Also, unclear if `TO` needs to be [Send] and [Sync].
unsafe impl<OWN: Any + Send + Sync, TO: Any + Send + Sync + ?Sized> Sync
    for NonDeDuplicatedFlexible<OWN, TO>
{
}

/// [NonDeDuplicated] and friends are intended for `static` (immutable) variables only. So
/// [Drop::drop] panics in debug/miri builds.
impl<OWN: Any + Send + Sync, TO: Any + Send + Sync + ?Sized> Drop
    for NonDeDuplicatedFlexible<OWN, TO>
{
    fn drop(&mut self) {
        // If the client uses Box::leak() or friends, then drop() will NOT happen. That is OK: A
        // leaked reference will have static lifetime.
        #[cfg(any(debug_assertions, miri))]
        panic!("Do not use for local variables, const, or on heap. Use for static variables only.")
    }
}

#[cfg(test)]
mod tests_shared {
    pub const STR_CONST_FROM_BYTE_ARRAY_HI: &str = {
        match str::from_utf8(&[b'H', b'i']) {
            Ok(s) => s,
            Err(_) => unreachable!(),
        }
    };

    pub const STR_CONST_FROM_BYTE_STRING_HELLO: &str = {
        match str::from_utf8(b"Hello") {
            Ok(s) => s,
            Err(_) => unreachable!(),
        }
    };
}

/// These tests don't actually test `ndd`, but they test the behavior **without** `ndd`.
#[cfg(test)]
mod tests_without_ndd {
    use crate::tests_shared::{STR_CONST_FROM_BYTE_ARRAY_HI, STR_CONST_FROM_BYTE_STRING_HELLO};
    use core::ptr;

    const U8_CONST: u8 = b'A';
    static U8_STATIC_1: u8 = b'A';
    static U8_STATIC_2: u8 = b'A';

    #[test]
    fn addresses_unique_between_statics() {
        assert!(!ptr::eq(&U8_STATIC_1, &U8_STATIC_2));
    }

    #[cfg(not(any(debug_assertions, miri)))]
    /// In release, [U8_CONST] gets optimized away and points to the same address as
    /// [U8_STATIC_1]!
    #[should_panic(expected = "assertion failed: !ptr::eq(&U8_STATIC_1, &U8_CONST)")]
    #[test]
    fn u8_global_const_and_global_static_release() {
        assert!(!ptr::eq(&U8_STATIC_1, &U8_CONST));
    }
    #[cfg(any(debug_assertions, miri))]
    /// In debug/MIRI, [ARR_CONST] and [ARR_STATIC_1] have unique/separate addresses!
    #[test]
    fn u8_global_const_global_and_static_debug_and_miri() {
        assert!(!ptr::eq(&U8_STATIC_1, &U8_CONST));
    }

    #[cfg(not(miri))]
    #[test]
    #[should_panic(expected = "assertion failed: !ptr::eq(STR_CONST_FROM_BYTE_ARRAY_HI, \"Hi\")")]
    fn str_global_byte_slice_const_and_local_str_release_and_debug() {
        assert!(!ptr::eq(STR_CONST_FROM_BYTE_ARRAY_HI, "Hi"));
    }
    #[cfg(miri)]
    #[test]
    fn str_global_byte_slice_const_and_local_str_miri() {
        assert!(!ptr::eq(STR_CONST_FROM_BYTE_ARRAY_HI, "Hi"));
    }

    /// This is the same for all three: release, debug AND miri!
    #[test]
    fn str_global_byte_by_byte_const_and_local_static() {
        assert!(ptr::eq(STR_CONST_FROM_BYTE_STRING_HELLO, "Hello"));
    }

    static STR_STATIC: &str = "Ciao";

    #[cfg(not(miri))]
    #[should_panic(expected = "assertion failed: !ptr::eq(local_const_based_slice, STR_STATIC)")]
    #[test]
    fn str_local_const_based_and_global_static_release_and_debug() {
        str_local_const_based_and_global_static_impl();
    }
    #[cfg(miri)]
    #[test]
    fn str_local_const_based_and_global_static_miri() {
        str_local_const_based_and_global_static_impl();
    }
    fn str_local_const_based_and_global_static_impl() {
        const LOCAL_CONST_ARR: [u8; 4] = [b'C', b'i', b'a', b'o'];
        let local_const_based_slice: &str = str::from_utf8(&LOCAL_CONST_ARR).unwrap();
        assert!(!ptr::eq(local_const_based_slice, STR_STATIC));
    }

    mod cross_module_static {
        pub static STATIC_OPT_U8_A: Option<u8> = Some(b'A');
    }
    mod cross_module_const {
        use core::ptr;
        pub const CONST_OPT_U8_A: Option<u8> = Some(b'A');

        #[cfg(not(any(debug_assertions, miri)))]
        #[test]
        #[should_panic(
            expected = "assertion failed: !ptr::eq(&CONST_OPT_U8_A, &super::cross_module_static::STATIC_OPT_U8_A)"
        )]
        fn option_u8_global_const_global_static_release() {
            assert!(!ptr::eq(
                &CONST_OPT_U8_A,
                &super::cross_module_static::STATIC_OPT_U8_A
            ));
        }
        #[cfg(any(debug_assertions, miri))]
        #[test]
        fn option_u8_global_const_global_static_debug_and_miri() {
            assert!(!ptr::eq(
                &CONST_OPT_U8_A,
                &super::cross_module_static::STATIC_OPT_U8_A
            ));
        }
    }
}

#[cfg(test)]
mod tests_with_ndd {
    use super::*;
    use crate::tests_shared::{STR_CONST_FROM_BYTE_ARRAY_HI, STR_CONST_FROM_BYTE_STRING_HELLO};
    use core::ptr;

    const U8_CONST: u8 = b'A';
    static U8_STATIC_1: u8 = b'A';
    static U8_STATIC_2: u8 = b'A';

    #[allow(dead_code)]
    const fn expect_sync_ref<T: Sync>() {}
    #[allow(dead_code)]
    const _: () = expect_sync_ref::<NonDeDuplicated<u8>>();

    static U8_NDD: NonDeDuplicated<u8> = NonDeDuplicated::new(U8_CONST);
    static U8_NDD_REF: &u8 = U8_NDD.get();
    #[test]
    fn u8_global_const_and_ndd() {
        assert!(!ptr::eq(U8_NDD_REF, &U8_CONST));
        assert!(!ptr::eq(U8_NDD_REF, &U8_STATIC_1));
        assert!(!ptr::eq(U8_NDD_REF, &U8_STATIC_2));
    }

    static STR_NDD_HI: NonDeDuplicatedStr<5> = NonDeDuplicatedStr::new("Hello");
    #[test]
    fn str_ndd_hi() {
        assert!(!ptr::eq(STR_NDD_HI.get(), "Hi"));
        assert!(!ptr::eq(STR_NDD_HI.get(), STR_CONST_FROM_BYTE_ARRAY_HI));
        assert!(!ptr::eq(STR_NDD_HI.get(), STR_CONST_FROM_BYTE_STRING_HELLO));
    }

    static STR_NDD_CIAO: NonDeDuplicatedStr<4> = NonDeDuplicatedStr::new("Ciao");
    #[test]
    fn str_local_const_based_and_str_ndd() {
        const LOCAL_CONST_ARR: [u8; 4] = [b'C', b'i', b'a', b'o'];
        let local_const_based_slice: &str = str::from_utf8(&LOCAL_CONST_ARR).unwrap();
        assert!(!ptr::eq(local_const_based_slice, STR_NDD_CIAO.get()));
    }

    #[test]
    #[cfg(any(debug_assertions, miri))]
    #[should_panic(
        expected = "Do not use for local variables, const, or on heap. Use for static variables only."
    )]
    fn drop_panics_in_debug_and_miri() {
        let _: NonDeDuplicated<()> = NonDeDuplicated::new(());
    }

    #[cfg(not(any(debug_assertions, miri)))]
    #[test]
    fn drop_silent_in_release() {
        let _: NonDeDuplicated<()> = NonDeDuplicated::new(());
    }
}