cowstr 1.0.0-beta3

Copy-on-Write shared strings
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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
use core::mem::{align_of, size_of};
use std::alloc;
use std::alloc::Layout;
use std::ptr::{addr_of_mut, NonNull};

#[cfg(not(feature = "multithreaded"))]
use std::cell::Cell;

#[cfg(feature = "multithreaded")]
use std::sync::atomic::{fence, AtomicUsize, Ordering};

#[cfg(feature = "multithreaded")]
use threadcell::ThreadCell;

use crate::Error;

/// Wraps raw memory to a reference counted string.
///
/// Currently rust has no support for representing/reallocating DST's that contain a
/// header. To solve this problem we store the raw allocated *mut u8 pointing to our
/// allocation and cast it opportunistically into the desired data/header parts. This is safe
/// because `RcString` constructors ensure that objects are always properly initialized.
/// This approach fixes the stacked-borrows bugs miri reported in an earlier implementation.
///
/// A `RcString` must be explicitly deallocated otherwise it will leak.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub(crate) struct RcString(NonNull<u8>);

// # Safety
//
// RcString is for most parts immutable when shared. Mutations can happen only when the
// refcount is one or the unsafe try_push* API's are used.
//
//  - Reference counting is atomic.
//  - `try_push()` is Sync by using a ThreadCell and only increment the .len atomically
//    once data is in place
unsafe impl Send for RcString {}
unsafe impl Sync for RcString {}

// ctor/dtor/allocation
impl RcString {
    /// Creates a `RcString` from a raw pointer and layout.
    /// Panics when the pointer is null.
    #[inline]
    unsafe fn from_ptr(allocated: *mut u8, layout: Layout) -> Self {
        if allocated.is_null() {
            alloc::handle_alloc_error(layout);
        }
        Self(NonNull::new_unchecked(allocated))
    }

    /// Allocated a new empty `RcString` with at least the given capacity.
    pub(crate) fn allocate(capacity: usize) -> Self {
        unsafe {
            // Safety: using const RCSTRING_ALIGN which is defined by align_of the header.
            let layout = Layout::from_size_align_unchecked(
                capacity
                    .checked_add(HEADER_SIZE)
                    .expect("Capacity overflow"),
                RCSTRING_ALIGN,
            );

            let allocated = Self::from_ptr(alloc::alloc(layout), layout);

            // Safety: `allocated` is uninitialized, it becomes initialized below.
            // this is not a problem since we only access it via addr_of_mut/ptr.write()
            let rcstring = allocated.0.cast::<RcStringHeader>().as_ptr();
            #[cfg(feature = "multithreaded")]
            addr_of_mut!((*rcstring).refcount).write(AtomicUsize::new(1usize));
            #[cfg(not(feature = "multithreaded"))]
            addr_of_mut!((*rcstring).refcount).write(Cell::new(1usize));

            #[cfg(feature = "multithreaded")]
            addr_of_mut!((*rcstring).len).write(AtomicUsize::new(0));
            #[cfg(not(feature = "multithreaded"))]
            addr_of_mut!((*rcstring).len).write(Cell::new(0));

            addr_of_mut!((*rcstring).capacity).write(layout.size() - HEADER_SIZE);

            #[cfg(feature = "multithreaded")]
            addr_of_mut!((*rcstring).push_lock).write(ThreadCell::new_disowned(()));

            // everything safe and sound now
            allocated
        }
    }

    /// Grows an `RcString` to have free space for at least 'reserve' bytes.
    ///
    /// Panics: when the reference count is not one.
    pub(crate) unsafe fn grow(mut self, reserve: usize, tryreserve: bool) -> Result<Self, Error> {
        // Safety: Internal interface, the caller has to ensure that the refcount is one.
        // This is the same with all debug_asserts later down.
        debug_assert_eq!(self.strong_count(), 1);
        let layout = self.current_layout();
        let min_new_size = (self.len_relaxed() + HEADER_SIZE)
            .checked_add(reserve)
            .expect("Capacity overflow");

        let new_size = DEFAULT_ALLOCATION_STRATEGY
            .grow(layout.size(), min_new_size)
            .expect("Capacity overflow");

        // really grow
        if new_size > layout.size() {
            let ptr = alloc::realloc(self.0.as_ptr(), layout, new_size);
            if tryreserve && ptr.is_null() {
                return Err(Error::TryReserveError);
            }
            self = Self::from_ptr(ptr, layout);
            self.header_mut().capacity = new_size - HEADER_SIZE;
        }

        Ok(self)
    }

    /// Shrinks an `RcString` to at minimum `new_capacity` or its current length, whatever is
    /// larger.
    pub(crate) unsafe fn shrink(mut self, new_capacity: usize) -> Self {
        debug_assert_eq!(self.strong_count(), 1);

        let layout = self.current_layout();

        let new_size =
            DEFAULT_ALLOCATION_STRATEGY.align(self.len_relaxed().max(new_capacity) + HEADER_SIZE);

        // really shrink, or keep the old one when the shrinking fails
        if new_size < layout.size() {
            let ptr = alloc::realloc(self.0.as_ptr(), layout, new_size);
            if !ptr.is_null() {
                let mut new_self = Self::from_ptr(ptr, layout);
                new_self.header_mut().capacity = new_size - HEADER_SIZE;
                self = new_self;
            };
        }

        self
    }

    /// Creates a new `RcString` by copying from a &[u8] with some spare capacity.
    ///
    /// # Safety
    ///
    /// The source must be valid utf-8
    unsafe fn from_bytes_unchecked(source: &[u8], reserve: usize) -> Self {
        let mut allocated = Self::allocate(
            source
                .len()
                .checked_add(reserve)
                .expect("Capacity overflow"),
        );

        std::ptr::copy_nonoverlapping(source.as_ptr(), allocated.data_mut(), source.len());
        allocated.len_set_release(source.len());

        allocated
    }

    /// Creates a new `RcString` by copying from a &str with some spare capacity.
    #[inline]
    pub(crate) fn from_str(source: &str, reserve: usize) -> Self {
        // Safety: source is a valid utf-8 string
        unsafe { Self::from_bytes_unchecked(source.as_bytes(), reserve) }
    }

    /// Unconditionally deallocates a `RcString`.
    ///
    /// # Safety
    ///
    /// Must only be called with a valid `RcString` pointer whose refcount is zero.
    // The side effect here is that the memory becomes freed, which we can't easily test
    #[mutants::skip]
    pub(crate) unsafe fn dealloc(self) {
        debug_assert_eq!(self.strong_count(), 0);
        let layout = self.current_layout();
        alloc::dealloc(self.0.as_ptr(), layout);
    }

    /// Returns the current layout.
    #[inline]
    fn current_layout(&self) -> Layout {
        unsafe {
            // Safety: &self is a valid RcString
            Layout::from_size_align_unchecked(self.header().capacity + HEADER_SIZE, RCSTRING_ALIGN)
        }
    }
}

// push etc
impl RcString {
    /// Appends the given `char` to the end of this `RcString`.
    ///
    /// # Panics
    ///
    /// There is not enough space available. The capacity has to be extended before calling
    /// this.
    #[inline]
    pub(crate) unsafe fn push(&mut self, ch: char) {
        let mut buf = [0u8; 4];
        let bytes = ch.encode_utf8(&mut buf).as_bytes();

        debug_assert!(self.spare_capacity() >= bytes.len());

        std::ptr::copy_nonoverlapping(
            bytes.as_ptr(),
            self.data_mut().add(self.header().len_relaxed()),
            bytes.len(),
        );
        self.len_add_release(bytes.len());
    }

    /// Tries to append the given `char` to the end of this `RcString`.
    /// This locks the string for appending and will fail when there is not enough spare capacity.
    pub(crate) unsafe fn try_push(&self, ch: char) -> Result<(), Error> {
        let mut buf = [0u8; 4];
        let bytes = ch.encode_utf8(&mut buf).as_bytes();

        #[cfg(feature = "multithreaded")]
        if !self.header().push_lock.is_owned() {
            return Err(Error::ThreadOwnership);
        }
        if self.spare_capacity() >= bytes.len() {
            std::ptr::copy_nonoverlapping(
                bytes.as_ptr(),
                // can be safely cast to *mut here because we write into the uninitialized
                // threadcell protected part
                (self.data() as *mut u8).add(self.header().len_relaxed()),
                bytes.len(),
            );

            self.len_add_release(bytes.len());
            Ok(())
        } else {
            Err(Error::Capacity)
        }
    }

    /// Appends the given `str` to the end of this `RcString`.
    ///
    /// # Panics
    ///
    /// There is not enough space available. The capacity has to be extended before calling
    /// this.
    #[inline]
    pub(crate) unsafe fn push_str(&mut self, s: &str) {
        debug_assert!(self.spare_capacity() >= s.len());

        std::ptr::copy_nonoverlapping(
            s.as_ptr(),
            self.data_mut().add(self.header().len_relaxed()),
            s.len(),
        );
        self.len_add_release(s.len());
    }

    /// Tries to appends the given `str` to the end of this `RcString`.  Self should be
    /// acquired by the current thread, will fail when there is not enough spare capacity.
    pub(crate) unsafe fn try_push_str(&self, s: &str) -> Result<(), Error> {
        #[cfg(feature = "multithreaded")]
        if !self.header().push_lock.is_owned() {
            return Err(Error::ThreadOwnership);
        }
        if self.spare_capacity() >= s.len() {
            std::ptr::copy_nonoverlapping(
                s.as_ptr(),
                // can be safely cast to *mut here because we write into the uninitialized
                // threadcell protected part
                (self.data() as *mut u8).add(self.header().len_relaxed()),
                s.len(),
            );
            self.len_add_release(s.len());
            Ok(())
        } else {
            Err(Error::Capacity)
        }
    }

    // helper only used by the Guard
    #[cfg(feature = "multithreaded")]
    #[inline]
    pub(crate) fn acquire(&self) -> bool {
        self.header().push_lock.try_acquire_once()
    }

    // helper only used by the Guard
    #[cfg(feature = "multithreaded")]
    #[inline]
    pub(crate) fn release(&self) {
        self.header().push_lock.release();
    }

    /// Removes the last character and returns it.
    #[inline]
    pub(crate) unsafe fn pop(&mut self) -> Option<char> {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);
        let ch = self.as_str().chars().rev().next()?;
        self.len_sub_release(ch.len_utf8());
        Some(ch)
    }

    /// Truncates the string to zero length. keeps capacity.
    #[inline]
    pub(crate) unsafe fn clear(&mut self) {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);
        self.len_set_release(0);
    }

    /// Truncates the string to the supplied length. keeps capacity.
    #[inline]
    pub(crate) unsafe fn truncate(&mut self, new_len: usize) {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);
        // Safety: caller checks already.
        debug_assert!(self.as_str().is_char_boundary(new_len));
        self.len_set_release(new_len);
    }

    /// remove a character from a string
    pub(crate) unsafe fn remove(&mut self, idx: usize) -> char {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);

        let ch = match self.as_str()[idx..].chars().next() {
            Some(ch) => ch,
            None => panic!("cannot remove a char from the end of a string"),
        };

        let next = idx + ch.len_utf8();
        let len = self.len_relaxed();

        let data = self.data_mut();
        std::ptr::copy(data.add(next), data.add(idx), len - next);
        self.len_sub_release(next - idx);

        ch
    }

    /// replaces a range of a rcstring with another str
    pub(crate) unsafe fn replace_range<R>(&mut self, range: R, replace_with: &str)
    where
        R: std::slice::SliceIndex<str, Output = str>,
    {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);

        // PLANNED: this impl is a hack, make it more rusty
        let removed_slice = &self.as_str()[range];
        let old_len = self.as_str().len();
        let new_len = old_len + replace_with.len() - removed_slice.len();
        debug_assert!(self.capacity() >= new_len);

        let removed_start: usize = removed_slice
            .as_ptr()
            .offset_from(self.as_str().as_ptr())
            .try_into()
            .unwrap_unchecked();

        let tail_start = removed_start + removed_slice.len();
        let insert_end = removed_start + replace_with.len();

        let tail_len = old_len - tail_start;

        self.len_set_release(new_len);
        let data = self.data_mut();

        // shift the tail
        std::ptr::copy(data.add(tail_start), data.add(insert_end), tail_len);
        // copy replace_with
        std::ptr::copy_nonoverlapping(
            replace_with.as_ptr(),
            data.add(removed_start),
            replace_with.len(),
        );
    }
}

// conversions
impl RcString {
    /// Returns self as &str
    #[inline]
    pub(crate) fn as_str(&self) -> &str {
        // Safety: RcString always holds a valid utf-8 string
        unsafe {
            std::str::from_utf8_unchecked(std::slice::from_raw_parts(
                self.data(),
                self.len_acquire(),
            ))
        }
    }

    /// Returns self as &mut str
    ///
    /// # Safety
    ///
    /// must be called with refcount equal one.
    #[inline]
    pub(crate) unsafe fn as_mut_str(&mut self) -> &mut str {
        // Safety: caller must only call this on a mutable object.
        debug_assert_eq!(self.strong_count(), 1);
        // Safety: RcString always holds a valid utf-8 string
        std::str::from_utf8_unchecked_mut(std::slice::from_raw_parts_mut(
            self.data_mut(),
            self.len_acquire(),
        ))
    }
}

// header accessors
//
// # Safety
//
// A RcString always wraps a properly aligned and initialized block of memory. We need to view
// it as a header followed by capacity*bytes, where the bytes above header.len are not yet
// initialized. miri's stacked borrows wont let us make up objects within this block easily. However
// casting this opportunistically whenever needed is sound and safe.
//
// NOTE: I would be glad if someone can point out a less hacky way to implement such kinds of DST's.
impl RcString {
    #[inline(always)]
    fn header(&self) -> &RcStringHeader {
        unsafe { std::mem::transmute::<_, &RcStringHeader>(self.0) }
    }

    #[inline(always)]
    fn header_mut(&mut self) -> &mut RcStringHeader {
        unsafe { std::mem::transmute::<_, &mut RcStringHeader>(self.0) }
    }

    #[inline(always)]
    fn data(&self) -> *const u8 {
        unsafe { self.0.as_ptr().add(HEADER_SIZE) }
    }

    #[inline(always)]
    fn data_mut(&mut self) -> *mut u8 {
        unsafe { self.0.as_ptr().add(HEADER_SIZE) }
    }

    #[inline(always)]
    pub(crate) fn spare_capacity(&self) -> usize {
        self.header().spare_capacity()
    }

    #[inline(always)]
    pub(crate) fn capacity(&self) -> usize {
        self.header().capacity()
    }

    #[inline(always)]
    pub(crate) fn strong_count(&self) -> usize {
        self.header().strong_count()
    }

    #[inline(always)]
    pub(crate) fn increment_strong_count(&self) {
        self.header().increment_strong_count();
    }

    #[inline(always)]
    #[must_use = "Would leak when 'true' is ignored"]
    pub(crate) fn decrement_strong_count(&self) -> bool {
        self.header().decrement_strong_count()
    }

    /// Get len from atomic or Cell with relaxed semantic.
    #[inline(always)]
    #[mutants::skip]
    pub(crate) fn len_relaxed(&self) -> usize {
        self.header().len_relaxed()
    }

    /// Get len from atomic or Cell with Acquire semantic.
    #[inline(always)]
    fn len_acquire(&self) -> usize {
        self.header().len_acquire()
    }

    /// Add 'n' to the length with Release semantic.
    ///
    /// # Safety
    ///
    /// The new len must comply with valid utf-8 encoding.
    #[inline(always)]
    unsafe fn len_add_release(&self, n: usize) {
        self.header().len_add_release(n);
    }

    /// Add 'n' to the length with Release semantic.
    ///
    /// # Safety
    ///
    /// The new len must comply with valid utf-8 encoding.
    #[inline(always)]
    unsafe fn len_sub_release(&self, n: usize) {
        self.header().len_sub_release(n);
    }

    /// Sets a new length with Release semantic.
    ///
    /// # Safety
    ///
    /// The new len must comply with valid utf-8 encoding.
    #[inline(always)]
    unsafe fn len_set_release(&self, n: usize) {
        self.header().len_set_release(n);
    }
}

impl std::fmt::Debug for RcString {
    #[mutants::skip]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("RcString")
            .field("header", self.header())
            .field("str", &self.as_str())
            .finish()
    }
}

#[cfg(feature = "multithreaded")]
#[derive(Debug)]
#[repr(C, align(32))]
pub(crate) struct RcStringHeader {
    refcount: AtomicUsize,
    len: AtomicUsize,
    capacity: usize,
    push_lock: ThreadCell<()>, // protect data and len on try_push
}

#[cfg(not(feature = "multithreaded"))]
#[derive(Debug)]
#[repr(C, align(32))]
pub(crate) struct RcStringHeader {
    refcount: Cell<usize>,
    len: Cell<usize>,
    capacity: usize,
}

const HEADER_SIZE: usize = size_of::<RcStringHeader>();
const RCSTRING_ALIGN: usize = align_of::<RcStringHeader>();

impl RcStringHeader {
    /// Get len from atomic or Cell with relaxed semantic.
    #[cfg(feature = "multithreaded")]
    #[inline(always)]
    fn len_relaxed(&self) -> usize {
        self.len.load(Ordering::Relaxed)
    }

    #[doc(hidden)]
    #[cfg(not(feature = "multithreaded"))]
    #[mutants::skip]
    #[inline(always)]
    fn len_relaxed(&self) -> usize {
        self.len.get()
    }

    /// Get len from atomic or Cell with Acquire semantic.
    #[cfg(feature = "multithreaded")]
    #[inline(always)]
    fn len_acquire(&self) -> usize {
        self.len.load(Ordering::Acquire)
    }

    #[doc(hidden)]
    #[inline(always)]
    #[cfg(not(feature = "multithreaded"))]
    #[mutants::skip]
    fn len_acquire(&self) -> usize {
        self.len.get()
    }

    /// Add 'n' to the length with Release semantic.
    #[inline(always)]
    unsafe fn len_add_release(&self, n: usize) {
        #[cfg(feature = "multithreaded")]
        self.len.fetch_add(n, Ordering::Release);
        #[cfg(not(feature = "multithreaded"))]
        self.len.set(self.len.get() + n);
    }

    /// Sub 'n' from the length with Release semantic.
    #[inline(always)]
    unsafe fn len_sub_release(&self, n: usize) {
        #[cfg(feature = "multithreaded")]
        self.len.fetch_sub(n, Ordering::Release);
        #[cfg(not(feature = "multithreaded"))]
        self.len.set(self.len.get() - n);
    }

    /// Sets a new length with Release semantic.
    #[inline(always)]
    unsafe fn len_set_release(&self, n: usize) {
        #[cfg(feature = "multithreaded")]
        self.len.store(n, Ordering::Release);
        #[cfg(not(feature = "multithreaded"))]
        self.len.set(n);
    }

    /// Returns the amount of bytes that can be pushed without reallocation.  This is an
    /// acquire fenced load allowing any further access to len to be relaxed.
    #[inline]
    pub(crate) fn spare_capacity(&self) -> usize {
        self.capacity - self.len_acquire()
    }

    /// Returns the capacity of the allocation.
    #[inline]
    pub(crate) fn capacity(&self) -> usize {
        self.capacity
    }

    #[inline]
    #[cfg(feature = "multithreaded")]
    pub(crate) fn strong_count(&self) -> usize {
        self.refcount.load(Ordering::Relaxed)
    }

    #[inline]
    #[cfg(not(feature = "multithreaded"))]
    #[mutants::skip]
    pub(crate) fn strong_count(&self) -> usize {
        self.refcount.get()
    }

    // NOTE: incrementing the strong count can always be relaxed because for any existing
    //       object it is:
    //
    //        * '1' then we own the object (mutably), no one else can decrement the strong count
    //        * '>1' the object is immutable/shared it may be concurrently decremented, but
    //          since we own it here it can't be dropped and we are going to increment it at
    //          least to 2.
    #[cfg(feature = "multithreaded")]
    pub(crate) fn increment_strong_count(&self) {
        self.refcount.fetch_add(1, Ordering::Relaxed);
    }

    #[cfg(not(feature = "multithreaded"))]
    #[mutants::skip]
    pub(crate) fn increment_strong_count(&self) {
        self.refcount.set(self.refcount.get() + 1);
    }

    #[cfg(not(feature = "multithreaded"))]
    #[mutants::skip]
    #[must_use = "Would leak when 'true' is ignored"]
    pub(crate) fn decrement_strong_count(&self) -> bool {
        let count = self.refcount.get();
        self.refcount.set(count - 1);
        count == 1
    }

    #[cfg(feature = "multithreaded")]
    #[must_use = "Would leak when 'true' is ignored"]
    pub(crate) fn decrement_strong_count(&self) -> bool {
        if self.refcount.fetch_sub(1, Ordering::Release) == 1 {
            fence(Ordering::Acquire);
            true
        } else {
            false
        }
    }
}

const KB: usize = 1024;
const MB: usize = KB * 1024;
const GB: usize = MB * 1024;

/// The allocation strategy when resizing an allocation
struct AllocationStrategy {
    /// Minimum allocation size returned
    pub min_allocation: usize,
    /// first cut, below this the allocations will be doubled, above until grow_const they will be increased by 50%
    pub grow_half: usize,
    /// second cut, above this allocation will grow constantly by grow_const/2
    pub grow_const: usize,
}

const DEFAULT_ALLOCATION_STRATEGY: AllocationStrategy = AllocationStrategy {
    min_allocation: 32,
    grow_half: 8 * MB,
    grow_const: /* 1 */ GB,
};

impl AllocationStrategy {
    /// returns the new size that shall be allocated, either per allocation strategy or when
    /// that is not sufficient, the `minimum_needed` size rounded up to a multiple of `min_allocation`.
    #[inline]
    pub fn grow(&self, old_size: usize, minimum_needed: usize) -> Option<usize> {
        Some(
            self.align(
                if old_size < self.min_allocation {
                    self.min_allocation
                } else if old_size < self.grow_half {
                    old_size.checked_mul(2)?
                } else if old_size < self.grow_const {
                    old_size.checked_add(old_size / 2)?
                } else {
                    old_size.checked_add(self.grow_const / 2)?
                }
                .max(minimum_needed),
            ),
        )
    }

    /// rounds/aligns the size by the `min_allocation` bytes
    #[cfg(not(feature = "nightly_int_roundings"))]
    #[inline]
    #[mutants::skip]
    pub fn align(&self, size: usize) -> usize {
        size | (self.min_allocation - 1)
    }

    /// rounds/aligns the size by the `min_allocation` bytes
    #[cfg(feature = "nightly_int_roundings")]
    #[inline]
    #[mutants::skip]
    pub fn align(&self, size: usize) -> usize {
        size.next_multiple_of(self.min_allocation)
    }
}