olis_string 0.1.3

Small-string optimization for Rust, aims to replace std::string::String
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
use std::{
    borrow::{Borrow, Cow},
    cmp,
    collections::TryReserveError,
    fmt,
    mem::{self, ManuallyDrop},
    ops::RangeBounds,
    ops::{self, Deref},
    ptr::{self, NonNull},
    slice,
    string::{Drain, FromUtf16Error, FromUtf8Error},
};

use crate::{
    duck_impl, never_impl, todo_impl, unified_alloc,
    unsafe_field::{UnsafeAssign, UnsafeField},
};

#[derive(Clone, Copy)]
#[repr(C)]
pub struct RawBuf<T> {
    pub(crate) data: NonNull<T>,
}

#[derive(Debug)]
pub struct InvalidArgumentError;

impl<T> RawBuf<T> {
    pub const fn dangling() -> Self {
        Self {
            data: NonNull::dangling(),
        }
    }

    pub fn new(capacity: usize) -> (Self, usize) {
        if capacity == 0 {
            return (Self::dangling(), 0);
        }

        let data = unified_alloc::alloc_slice::<T>(capacity);

        (Self { data: data.cast() }, data.len())
    }

    /// Deallocates the buffer. Returns [`InvalidArgumentError`] if `len` is impossibly big.
    ///
    /// # Safety
    /// - `len` must be the exact length of the allocated object, using the value returned
    ///   with `RawBuf::new() -> (_, len)` will guarantee safety.
    /// - this must be the first time that you call this function (aka self.data cannot be dangling)
    pub unsafe fn dealloc(mut self, len: usize) -> Result<Self, InvalidArgumentError> {
        // SAFETY: cast temporarily for method, pointer is non-null still
        let nonnull_slice = unsafe {
            NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(self.data.as_ptr(), len))
        };
        // SAFETY:
        // - nonnull_slice points to an allocation created by RawBuf<T>
        // - the allocation should not be deallocated (caller contract)
        // - the len of the allocation should be the same as what was returned by new (caller
        //   contract)
        unsafe {
            unified_alloc::dealloc_slice(nonnull_slice);
        }
        // we need to self.data explicitly dangle, so that general slice functions are
        // perceived as safe by Miri. If we allocate, and deallocate, Miri has a tag for the
        // region and will think slice_from_raw_parts is valid.
        self.data = NonNull::dangling();
        Ok(self)
    }

    /// Returns the head of this buffer as a raw pointer, this pointer is guaranteed to be non-null
    /// aligned, and point to a valid allocation of `[T]`. The number of elements is the same as
    /// the second element that is returned by `RawBuf::new`
    ///
    /// [`RawBuf::new`]: sso::RawBuf::new
    pub const fn as_ptr(&self) -> *mut T {
        self.data.as_ptr()
    }
}

#[derive(Clone, Copy)]
#[repr(C)]
#[repr(align(8))]
pub struct ShortString64 {
    /// # Safety
    /// - `1` is always a valid value
    /// - the last bit must always be `1`
    /// when shifted by >> 1:
    /// - `len` must be less than or equal to `ShortString64::MAX_CAPACITY`
    len_and_flag: UnsafeField<u8, 0>,
    /// # Safety
    /// - Must always be valid utf8
    buf: UnsafeField<[u8; Self::MAX_CAPACITY], 1>,
}

impl ShortString64 {
    pub const MAX_CAPACITY: usize = 23;

    /// Constructs and empty ShortString64
    pub fn new() -> Self {
        Self {
            // SAFETY: 1 is always a valid value
            len_and_flag: unsafe { UnsafeField::new(1) }, // 0, 1
            buf: unsafe { UnsafeField::new([0; 23]) },
        }
    }

    /// in a union with a long string, returns `true` if this has been upgraded
    pub const fn is_short(&self) -> bool {
        (*self.len_and_flag.get() & 1) == 1
    }

    /// Although not unsafe, sa the string is zeroed, you shold uphold that `len` is all
    /// user-initialised. This depends on the function that you are implementing with this.
    ///
    /// SAFETY:
    /// - `len` must be less than or equal to `ShortString64::MAX_CAPACITY`
    pub unsafe fn set_len(&mut self, len: usize) {
        let mask = *self.len_and_flag.get() & 1;
        // SAFETY:
        // - len is masked `mask` which sets the last bit to 1 no matter what and does not affect
        //   the first 7 bits at all
        // - len >> 1 is len, the safety contract is passed to the caller
        self.len_and_flag.set(mask | ((len as u8) << 1));
    }

    /// Returns the length of this short string, `len` upholds fewer invariants on a short string,
    /// than on a long, these are
    ///
    /// - `self.len() <= self.capacity()` Note that `self.capacity()` is a constant
    pub const fn len(&self) -> usize {
        ((*self.len_and_flag.get() & (u8::MAX << 1)) >> 1) as usize
    }

    /// Returns the capacity of this short string, this is a constant, which is equal to
    /// [`Self::MAX_CAPACITY`]
    pub const fn capacity(&self) -> usize {
        Self::MAX_CAPACITY
    }

    pub const fn remaining_capacity(&self) -> usize {
        Self::MAX_CAPACITY - self.len()
    }

    /// Returns the next pointer where we should allocate our string. This validates Stacked
    /// Borrows, by using the write access of `self`.
    ///
    /// # Safety
    /// - the returned pointer is only writable if self.len() < self.capacity()
    /// - you must only write to this pointer if you know it is valid utf8
    pub fn next_ptr(&mut self) -> NonNull<u8> {
        // SAFETY:
        // - no issues with overflow or invalid value as self.len() < Self::MAX_CAPACITY, which is
        //   23.
        // - ... which is also the size of the buffer, so we're either one past buf, or within
        //   the buffer
        unsafe {
            let raw = self.buf.get_mut().cast::<u8>().as_ptr();
            // SAFETY: raw is non-null because it is 'within' a valid allocation
            NonNull::new_unchecked(raw.add(self.len()))
        }
    }

    /// # Safety
    /// - `s.len()` must be equal to or less than `self.remaining_capacity()`
    pub unsafe fn push_str_unchecked(&mut self, s: &str) {
        // SAFETY:
        // - src is valid for reads of count s.len(), as it is s
        // - dst is valid for writes of count s.len() as s.len() self.remaining_capacity(), and
        //   buf[self.len()] will point to a buffer of size remaining_capacity()
        // - both are cast from aligned pointers
        // - both are non-overlapping, we just created new_buf on the stack
        ptr::copy_nonoverlapping(s.as_bytes().as_ptr(), self.next_ptr().as_ptr(), s.len());
        // SAFETY:
        // - len is at most self.len() + self.remaining_capacity(), which is by definition
        //   Self::MAX_CAPACITY
        // - self.buf[len..len + s.len()] has just been initialised as valid utf8 from a str
        self.set_len(self.len() + s.len());
    }

    /// Push a string `s` to the end o this string. If `s` does not fit, do nothing.
    pub fn push_str(&mut self, s: &str) {
        if s.len() > self.remaining_capacity() {
            return;
        }
        // SAFETY: bounds check done such that all code that for all code that reaches this point,
        // s.len() <= self.remaining_capacity()
        unsafe {
            self.push_str_unchecked(&s);
        }
    }

    pub fn push(&mut self, ch: char) {
        let mut buf = [0; 4];
        let utf8 = ch.encode_utf8(&mut buf);
        self.push_str(utf8);
    }

    /// Converts this to a [`LongString`]. Where the capacity is equal to or greater than
    /// `Self::MAX_CAPACITY + additional_capacity`.
    pub fn into_long(&self, additional_capacity: usize) -> LongString {
        let mut long = LongString::with_capacity(Self::MAX_CAPACITY + additional_capacity);
        // SAFETY: long has at least Self::MAX_CAPACITY space, so it can fit any string this
        // short string contains
        unsafe {
            long.push_str_unchecked(self.as_str());
        }
        long
    }

    /// Returns a slice of bytes that is always valid utf-8
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: always safe to convert to &[u8]
        unsafe { &*self.get_sized_buf().as_ptr() }
    }

    /// interpret this string as a `&str`
    pub fn as_str(&self) -> &str {
        // SAFETY: always valid utf-8, by definition
        unsafe { std::str::from_utf8_unchecked(self.as_bytes()) }
    }

    /// Returns `buf[0..len]` as a `NonNull<[u8]>` with len `len`, you may cast the resulting slice
    /// to a `&'self str`  at any time, assuming all unsafe functions are called with their
    /// preconditions satisified.
    ///
    /// This is different from the restrictions on the method of the same name on `LongString`,
    /// where this is not always convertable.
    pub fn get_sized_buf(&self) -> NonNull<[u8]> {
        let ptr = self as *const Self as *const u8;
        unsafe {
            // SAFETY:
            // - note that we construct this from a `&self`, to comply with Stacked Borrows
            // - this operation is not safe, but we make assertions about the result, namely that
            //   it can be used as slice, so long as its lifetime is tied to a self parameter.
            //   Therefore, we must make sure that the slice is valid for slice::from_raw_parts
            //
            // - ptr add is within the object and len is at most sizeof(ShortString) - 1
            // - ptr.add(1).add(self.len()) is always guaranteed to be within the allocated object
            // - both are properly aligned because we're working with bytes
            let raw = ptr::slice_from_raw_parts(ptr.add(1), self.len());
            // SAFETY: ptr.add(1) cannot be null, as it is also a valid &[u8]
            NonNull::new_unchecked(raw as *mut [u8])
        }
    }

    /// Returns `buf[0..len]` as a `NonNull<[u8]>` with len `len`, you may cast the resulting slice
    /// to a `&'self str`  at any time, assuming all unsafe functions are called with their
    /// preconditions satisified.
    ///
    /// This is different from the restrictions on the method of the same name on `LongString`,
    /// where this is not always convertable.
    ///
    /// We need this method for this variant because the provenance of the returned slice is
    /// determined by the provenance of self. Therefore, if we used a `&self`, the region would be
    /// tagged with SharedReadOnly
    pub fn get_sized_buf_mut(&mut self) -> NonNull<[u8]> {
        let ptr = self as *mut Self as *mut u8;
        unsafe {
            // SAFETY:
            // - note that we construct this from a `&self`, to comply with Stacked Borrows
            // - this operation is not safe, but we make assertions about the result, namely that
            //   it can be used as slice, so long as its lifetime is tied to a self parameter.
            //   Therefore, we must make sure that the slice is valid for slice::from_raw_parts
            //
            // - ptr add is within the object and len is at most sizeof(ShortString) - 1
            // - ptr.add(1).add(self.len()) is always guaranteed to be within the allocated object
            // - both are properly aligned because we're working with bytes
            let raw = ptr::slice_from_raw_parts_mut(ptr.add(1), self.len());
            // SAFETY: ptr.add(1) cannot be null, as it is also a valid &[u8]
            NonNull::new_unchecked(raw as *mut [u8])
        }
    }

    /// interpret this string as a `&str`
    pub fn as_mut_str(&mut self) -> &mut str {
        // SAFETY: cast to `&'self mut [u8]` is always valid according to function description
        let buf = unsafe { &mut *self.get_sized_buf_mut().as_ptr() };
        // SAFETY: always valid utf-8, by definition
        unsafe { std::str::from_utf8_unchecked_mut(buf) }
    }
}

impl fmt::Display for ShortString64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl fmt::Debug for ShortString64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_str())
    }
}

// SAFETY: all structs contain different integers
#[repr(C)]
pub struct LongString {
    /// # Safety
    /// - `0` is always a valid value
    /// - the last bit is always 0
    /// when shifted by >> 1:
    /// - `len <= capacity`
    /// - `buf[0..len]` is always a valid SharedReadWrite slice of valid u8, if the string is not
    ///    borrowed, otherwise the permissions become that of the borrow
    len: UnsafeField<usize, 0>,
    /// # Safety
    /// buf and capacity are linked, so we can only modify either if we update the entire struct
    /// simultaneously. As a result, we cannot implement Drop. The size of the allocated object
    /// starting at buf.data is always exactly capacity bytes long.
    buf: UnsafeField<RawBuf<u8>, 1>,
    /// # Safety
    /// buf and capacity are linked, so we can only modify either if we update the entire struct
    /// simultaneously. As a result, we cannot implement Drop. The size of the allocated object
    /// starting at buf.data is always exactly capacity bytes long.
    capacity: UnsafeField<usize, 2>,
}

impl LongString {
    /// Construct a new `LongString` with at least `capacity` as the `capacity`. Note that this
    /// will panic in the case of an impossible allocation (e.g. `capacity > isize::MAX`)
    pub fn with_capacity(capacity: usize) -> Self {
        let (buf, capacity) = RawBuf::new(capacity);

        unsafe {
            Self {
                // SAFETY: a value of `0` is always valid
                len: UnsafeField::new(0),
                // SAFETY: by definition of RawBuf::new, capacity and buf match, so both these
                // constructions are safe
                capacity: UnsafeField::new(capacity),
                buf: UnsafeField::new(buf),
            }
        }
    }

    /// interpret this as a `&str`
    pub fn as_str(&self) -> &str {
        // SAFETY: `LongString` always contains valid utf-8, buf[0..len] is always initialised
        unsafe { std::str::from_utf8_unchecked(self.as_bytes()) }
    }

    pub fn as_mut_str(&mut self) -> &mut str {
        // SAFETY: conversion to `&'self mut [u8]` is valid, since we have not modified the buffer,
        // since acquiring the pointer (we immediately derefrenced)
        let buf = unsafe { &mut *self.get_sized_buf().as_ptr() };
        // SAFETY: always valid utf-8, by definition
        unsafe { std::str::from_utf8_unchecked_mut(buf) }
    }

    /// alias for `self.as_str().as_bytes()`
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY:
        // - valid for reads of u8, since we are within 0..len, which is by definition,
        //   initialised and allocated
        // - we cannot mutate the slice, since the returned slice lives as long as the borrow
        //   to self
        // - allocations are no larger than isize::MAX, so len can never be greater than that
        unsafe { slice::from_raw_parts(self.buf().data.as_ptr(), self.len()) }
    }

    /// Returns a sized buffer representing the whole buffer of the string, can be safely written to
    /// so long as utf-8 constraints are not invalidated, and the buffer is not resized
    pub fn get_sized_buf(&self) -> NonNull<[u8]> {
        unsafe {
            // SAFETY:
            // - region specified is allocated and within the same allocation, since it is always
            //   within RawBuf.data
            // - region specified is valid for writes, because it is SharedReadWrite
            let buf = ptr::slice_from_raw_parts_mut(self.buf().data.as_ptr(), self.capacity());
            // SAFETY:
            // - `raw` is constructed froma a NonNull and is thus valid to cast to a NonNull
            NonNull::new_unchecked(buf)
        }
    }

    pub fn get_non_null_slice(&self, index: usize, len: usize) -> Option<NonNull<[u8]>> {
        if index + len > self.capacity() {
            return None;
        }
        let data = self.get_non_null(index).expect("index <= self.capacity()");

        unsafe {
            // SAFETY:
            // - region specified is allocated and within the same allocation, since it is always
            //   within RawBuf.data
            // - region specified is valid for writes, because it is SharedReadWrite
            let raw = ptr::slice_from_raw_parts_mut(data.as_ptr(), len);
            // SAFETY:
            // - `raw` is constructed froma a NonNull and is thus valid to cast to a NonNull
            Some(NonNull::new_unchecked(raw))
        }
    }

    /// get unchecked [`NonNull<u8>`] to an index in the buffer, use `get_non_null` for a safe
    /// version of this function
    ///
    /// # Safety
    /// - You must uphold `index <= self.capacity()`
    pub unsafe fn get_non_null_unchecked(&self, index: usize) -> NonNull<u8> {
        // SAFETY:
        // - the maxmimum index is capacity, which is within the specified boundary of the allocated
        //   object (RawBuf.data), or one byte past the end
        // - we cannot allocate a buffer of more than isize::MAX, thus capacity must be less than
        //   `isize::MAX`
        // - allocations are fully within the address space, so we cannot wrap around
        let ptr = self.buf().data.as_ptr().add(index);
        // SAFETY:
        // - valid ptr.add() on a valid NonNull is guaranteed to produce a valid NonNull
        NonNull::new_unchecked(ptr)
    }

    /// returns a pointer to the element of the buffer that is at an offset of `index` from the
    /// start, or `None` if the pointer is out of bounds
    pub fn get_non_null(&self, index: usize) -> Option<NonNull<u8>> {
        if index > self.capacity() {
            return None;
        }

        // SAFETY: exact required bounds check performed, no mutations following bounds check
        unsafe { Some(self.get_non_null_unchecked(index)) }
    }

    /// returns a pointer to the next element of the buffer that we want to allocate to, note that
    /// the pointer might not be writeable, as it could be outside of the buffer. In order to write
    /// to the pointer, ensure that `len < capacity`
    pub fn next_ptr(&mut self) -> NonNull<u8> {
        // SAFETY: len, by definition, always satisfies `len <= capacity`
        unsafe { self.get_non_null_unchecked(self.len()) }
    }

    /// returns the length of this string in bytes, length upholds the following invariants, that
    /// you needn't check
    ///
    /// - `self.len() < self.capacity()`
    /// - `self.len() < isize::MAX` (derived invariant from `self.capacity() < isize::MAX`)
    pub const fn len(&self) -> usize {
        *self.len.get() >> 1
    }

    /// Returns the capacity of this string, that is, how many bytes it can fit before a realloc.
    /// Note that this does not mean *extra bytes*, but total bytes. Use `remaining_capacity` for
    /// that.
    ///
    /// `self.capacity()` upholds the following invariants:
    ///
    /// - `self.capacity() < isize::MAX`
    /// - `self.capacity()` is the exact size of the allocated buffer
    pub const fn capacity(&self) -> usize {
        *self.capacity.get()
    }

    /// Gets the underyling buffer being used for this string
    pub const fn buf(&self) -> &RawBuf<u8> {
        self.buf.get()
    }

    /// returns the remaining capacity of this string (how many bytes we can allcoate before a
    /// realloc must occur)
    pub const fn remaining_capacity(&self) -> usize {
        self.capacity() - self.len()
    }

    /// clones this string, with at least `additional_capacity` extra space
    pub fn clone_with_additional_capacity(&self, additional_capacity: usize) -> Self {
        let mut new = Self::with_capacity(self.capacity() + additional_capacity);
        // SAFETY: new has at least self.capacity() space, so it can allocate anything that
        // self holds
        unsafe {
            new.push_str_unchecked(self.as_str());
        }
        new
    }

    /// realloc to fit at least `remaining_capacity` more bytes
    pub fn realloc(&mut self, remaining_capacity: usize) {
        let new = self.clone_with_additional_capacity(cmp::max(
            remaining_capacity - self.remaining_capacity(),
            self.capacity() * 2,
        ));
        self.free();
        *self = new;
    }

    /// # Safety
    /// - `self.remaining_capacity()`` must be at least `s.len()`
    pub unsafe fn push_str_unchecked(&mut self, s: &str) {
        // SAFETY:
        // - src (s) is valid for reads of s.len() by slice definition
        // - dst is valid for writes of count s.len(), since remaining_capacity >= s.len()
        //   and self.next_ptr() points to a buffer of size remaining_capacity
        // - both dst and src are cast from aligned pointers
        // - the regions may not overlap, as `&mut` uniquely borrows the the buffer, thus
        //   `&str` must point somewhere else
        ptr::copy_nonoverlapping(s.as_bytes().as_ptr(), self.next_ptr().as_ptr(), s.len());
        // SAFETY: just copied a valid str of s.len() into the section starting at len
        self.set_len(self.len() + s.len());
    }

    /// Push a `str` to this string, allocating if needed. Note that the current realloc schema
    /// might only allocate exactly enough extra space for `s`
    pub fn push_str(&mut self, s: &str) {
        if self.remaining_capacity() < s.len() {
            self.realloc(s.len());
        }

        // SAFETY: if remaining capacity is less than s.len(), we realloc to fit at least s.len()
        // therefore, the remaining capacity is at least s.len()
        unsafe { self.push_str_unchecked(s) }
    }

    /// Push a `char` to this string, allocating if needed. Like [`LongString::push_str`] this might
    /// only allocate enough extra space for `ch`, but that is very unlikely in this case.
    pub fn push(&mut self, ch: char) {
        let mut buf = [0; 4];
        let utf8 = ch.encode_utf8(&mut buf);
        self.push_str(utf8);
    }

    /// `len` is truncated to a 63-bit number.
    ///
    /// # Safety
    /// - everything from `buf[0..len]` must be initialised.
    /// - you must uphold `len <= capacity`
    unsafe fn set_len(&mut self, len: usize) {
        // SAFETY: safety contract passed to caller
        self.len.set(len << 1);
    }

    /// free the buffer of this string, setting the `len` and `capacity` to `0`
    pub fn free(&mut self) {
        let capacity = self.capacity();
        *self = unsafe {
            Self {
                // SAFETY: 0 always satisfies len's invaraints
                len: UnsafeField::new(0),
                // SAFETY: the buffer is dangling and the capacity is 0, which is a valid
                // state for LongString, these two fields have a linked invariant
                capacity: UnsafeField::new(0),
                buf: UnsafeField::new(
                    self.buf
                        .own()
                        // SAFETY: capacity is the exact size of the buffer
                        .dealloc(capacity)
                        .expect("should be the exact capacity"),
                ),
            }
        };
    }

    /// Construct a new `LongString` from a `length`, `buf` and `capacity`
    ///
    /// # Safety
    /// - invariants of `length`
    ///     - `0` is always a valid value
    ///     - `len <= capacity`
    ///     - `buf[0..len]` is always a valid SharedReadWrite slice of valid u8, if the string is not
    ///        borrowed, otherwise the permissions become that of the borrow
    /// - invariants of `buf` and `capacity`
    ///     - The size of the allocated object starting at buf is *exactly* `capacity` bytes long
    ///     - `buf` must be allocated with std::allocator::Global
    pub unsafe fn from_raw_parts(buf: NonNull<u8>, length: usize, capacity: usize) -> Self {
        Self {
            // SAFETY: invariants of `.len()` are passed to caller, so we must ensure the final bit
            // is `0`, which we do by shifting left 1.
            len: UnsafeField::new(length << 1),
            // SAFETY: passed to caller
            buf: UnsafeField::new(RawBuf { data: buf }),
            // SAFETY: passed to caller
            capacity: UnsafeField::new(capacity),
        }
    }

    pub fn from_str(s: &str) -> Self {
        let mut long = Self::with_capacity(s.len());
        // SAFETY: we allocate long with_capacity(s.len()). It is empty, therefore it must have
        // remaining_capacity == capacity == s.len()
        unsafe {
            long.push_str_unchecked(s);
        }
        long
    }
}

impl fmt::Display for LongString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl fmt::Debug for LongString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_str())
    }
}

impl Clone for LongString {
    fn clone(&self) -> Self {
        self.clone_with_additional_capacity(0)
    }
}

pub enum TaggedSsoString64Mut<'a> {
    Short(&'a mut ShortString64),
    Long(&'a mut LongString),
}

pub enum TaggedSsoString64<'a> {
    Short(&'a ShortString64),
    Long(&'a LongString),
}

#[cfg(all(target_endian = "little", target_pointer_width = "64"))]
#[repr(C)]
pub union SsoString {
    pub(crate) short: ManuallyDrop<ShortString64>,
    pub(crate) long: ManuallyDrop<LongString>,
}

impl Drop for SsoString {
    fn drop(&mut self) {
        match self.tagged_mut() {
            TaggedSsoString64Mut::Long(long) => {
                long.free();
            }
            _ => {}
        }
    }
}

impl<'a> From<&'a str> for SsoString {
    fn from(value: &'a str) -> Self {
        let mut s = Self::new();
        s.push_str(value);
        s
    }
}

// we only allow this feature on stable, because I have no idea how the API is going to change for
// swap-in allocators and it makes me shiver in my boots to think about the implications of this
#[cfg(not(feature = "nightly"))]
impl From<String> for SsoString {
    fn from(value: String) -> Self {
        // perform a memcpy if the `String` is short enough, this is more likely to result in a
        // cache miss than a stack ptr swap, but is probably fine for most use-cases of this
        // function, where we immediately turn a small std::string::String into an SsoString
        if value.len() < ShortString64::MAX_CAPACITY {
            let mut short = ManuallyDrop::new(ShortString64::new());
            short.push_str(&value);
            return SsoString { short };
        }

        // otherwise, we need to swap stack values
        let mut value = mem::ManuallyDrop::new(value);
        let long = unsafe {
            // SAFETY:
            // - since `value.len()` is always greater than `0`, we can be sure that it is not
            //   dangling or null.
            let ptr = NonNull::new_unchecked(value.as_mut_ptr());
            // SAFETY:
            // - all length and capacity invariants are upheld by `std::string::String`
            // - RawBuf uses `Global` internally, so handing over `String`'s allocation is just
            //   fine
            // - ptr has SharedReadWrite provenance.. I think
            LongString::from_raw_parts(ptr, value.len(), value.capacity())
        };

        SsoString {
            long: ManuallyDrop::new(long),
        }
    }
}

/// A wrapper around `str`, so that we can implement `ToOwned` where `ToOwned::Owned` is
/// `sso::String`
#[repr(transparent)]
#[derive(Debug, PartialEq)]
pub struct SsoStr(str);

impl Deref for SsoStr {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl SsoStr {
    /// cast a `&str` to a `&SsoStr`
    pub fn from_str(s: &str) -> &Self {
        // SAFETY:
        // - repr transparent wrapper around a T is always transmutable to that T
        // - if T -> U then &'a T -> &'a U
        unsafe { mem::transmute(s) }
    }

    /// cast a `&mut str` to a `&mut SsoStr`
    pub fn from_mut_str(s: &mut str) -> &mut Self {
        // SAFETY:
        // - repr transparent wrapper around a T is always transmutable to that T
        // - if T -> U then &'a mut T -> &'a mut U
        unsafe { mem::transmute(s) }
    }
}

impl ToOwned for SsoStr {
    type Owned = SsoString;

    fn to_owned(&self) -> Self::Owned {
        let s: &str = self;
        let owned = SsoString::from(s);
        owned
    }
}

impl SsoString {
    pub fn new() -> Self {
        Self {
            short: ManuallyDrop::new(ShortString64::new()),
        }
    }

    /// Returns `true` if this string is a short string (no heap allocations), and `false` otherwise
    pub fn is_short(&self) -> bool {
        // SAFETY: transmuting anything to a byte array is always valid, which is essentially what
        // we're doing when we do this.
        unsafe { self.short.is_short() }
    }

    /// Returns `!self.is_short()`
    pub fn is_long(&self) -> bool {
        !self.is_short()
    }

    /// Returns the underlying union as an enum, allowing you to access the underlying short or
    /// long variant for the string
    pub fn tagged(&self) -> TaggedSsoString64 {
        if self.is_short() {
            TaggedSsoString64::Short(unsafe { &self.short })
        } else {
            TaggedSsoString64::Long(unsafe { &self.long })
        }
    }

    /// Same as [`SsoString::tagged`], but returns allows mutation of the underlying values instead
    pub fn tagged_mut(&mut self) -> TaggedSsoString64Mut {
        if self.is_short() {
            TaggedSsoString64Mut::Short(unsafe { &mut self.short })
        } else {
            TaggedSsoString64Mut::Long(unsafe { &mut self.long })
        }
    }

    duck_impl! {
        /// Returns a slice of bytes of this string's contents
        pub fn as_bytes(&self) -> &[u8];
    }

    duck_impl! {
        pub fn as_mut_str(&mut self) -> &mut str;
    }

    never_impl! {
        /// A method with the same name exists on `std::string::String`, but cannot exist on this
        /// version, as it does not use a vector internally (ever). I don't think this method is
        /// good anyway, since it doesn't scope the unsafe behaviour appropriately.
        ///
        /// If you desperately want to use this kind of method, you can simply create `&str`s
        /// with unsafe unchecked methods. Probably not needed though, but I won't judge `:o)`
        pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8>;
    }

    duck_impl! {
        pub fn as_str(&self) -> &str;
    }

    duck_impl! {
        pub fn capacity(&self) -> usize;
    }

    duck_impl! {
        pub fn clear(&mut self as duck) {
            // SAFETY: 0 is always a valid value for len on both variants
            unsafe { duck.set_len(0) }
        }
    }

    todo_impl! {
        pub fn drain<R>(&mut self, _range: R) -> Drain<'_>
        where
            R: RangeBounds<usize>,
    }

    todo_impl! {
        pub fn extend_from_within<R>(&mut self, _src: R)
        where
            R: RangeBounds<usize>,
    }

    /// Creates a new `SsoString::Long` from a length, capacity and pointer. This method only
    /// exists to match `std::string::String`'s method of the same signature and name. It will
    /// always create a long string, which is probably what you want if you are using this method.
    ///
    /// # Safety (from [`std::string::String`])
    ///
    /// This is highly unsafe, due to the numer of invariants that aren't checked:
    ///
    /// - The memory at buf needs to have been previously allocated by the same allocator the
    ///   standard library uses, with a required alignment of exactly 1.
    /// - `length` needs to be less than or equal to capacity.
    /// - `capacity` needs to be the correct value.
    /// - The first length bytes at buf need to be valid UTF-8.
    pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> Self {
        // SAFETY: safety contract passed to caller (buf must be nonnull)
        let ptr = NonNull::new_unchecked(buf);
        // SAFETY: safety contract passed to caller
        SsoString {
            long: ManuallyDrop::new(LongString::from_raw_parts(ptr, length, capacity)),
        }
    }

    todo_impl!(pub fn from_utf16(_v: &[u16]) -> Result<SsoString, FromUtf16Error>);

    todo_impl!(pub fn from_utf16_lossy(_v: &[u16]) -> SsoString);

    pub fn from_utf8(v: Vec<u8>) -> Result<SsoString, FromUtf8Error> {
        std::string::String::from_utf8(v).map(|s| s.into())
    }

    todo_impl!(pub fn from_utf8_lossy(_v: &[u8]) -> Cow<'_, SsoStr>);

    todo_impl!(pub unsafe fn from_utf8_unchecked(_v: &[u8]) -> SsoString);

    todo_impl!(pub fn insert(&mut self, _idx: usize, _c: char));

    todo_impl!(pub fn insert_str(&mut self, _idx: usize, _s: &str));

    todo_impl!(pub fn into_boxed_str(self) -> Box<str>);

    todo_impl!(pub fn leak<'a>(self) -> &'a mut str);

    duck_impl! {
        pub fn len(&self) -> usize;
    }

    pub fn push(&mut self, ch: char) {
        let mut buf = [0; 4];
        let utf8 = ch.encode_utf8(&mut buf);
        self.push_str(utf8);
    }

    /// Push a str `s` onto the end of this string
    pub fn push_str(&mut self, s: &str) {
        match self.tagged_mut() {
            TaggedSsoString64Mut::Short(short) => {
                if s.len() <= short.remaining_capacity() {
                    // SAFETY: exact bounds check just completed
                    unsafe {
                        short.push_str_unchecked(s);
                    }
                } else {
                    let mut long = ManuallyDrop::new(short.into_long(s.len()));
                    long.push_str(s);
                    *self = SsoString { long };
                }
            }
            TaggedSsoString64Mut::Long(long) => {
                long.push_str(s);
            }
        }
    }

    todo_impl!(pub fn remove(&mut self, _idx: usize) -> char);

    todo_impl!(
        pub fn replace_range<R>(&mut self, _range: R, _replace_with: &str)
        where
            R: RangeBounds<usize>,
    );

    pub fn reserve(&mut self, additional: usize) {
        match self.tagged_mut() {
            TaggedSsoString64Mut::Short(short) => {
                let long = ManuallyDrop::new(short.into_long(additional));
                *self = SsoString { long };
            }
            TaggedSsoString64Mut::Long(long) => {
                long.realloc(additional);
            }
        }
    }

    duck_impl! {
        pub unsafe fn set_len(&mut self, len: usize);
    }

    duck_impl! {
        pub fn pop(&mut self as duck) -> Option<char> {
            let ch = duck.as_str().chars().rev().next()?;
            // SAFETY: will always still be valid utf8, as we are 'removing' a correctly sized utf8
            // byte sequence from the end of this string. For added assurance that this is safe,
            // this is basically exactly the same code as the std library impementation.
            unsafe {
                duck.set_len(duck.len() - ch.len_utf8());
            }
            Some(ch)
        }
    }

    /// This doesn't actually reserve exactly `additional` extra bytes, it might allocate a few
    /// extra, just because of the implementation of `Global`.
    pub fn reserve_exact(&mut self, additional: usize) {
        match self.tagged_mut() {
            TaggedSsoString64Mut::Short(short) => {
                let long = ManuallyDrop::new(short.into_long(additional));
                *self = SsoString { long };
            }
            TaggedSsoString64Mut::Long(old) => {
                let long = ManuallyDrop::new(old.clone_with_additional_capacity(additional));
                old.free();
                *self = SsoString { long };
            }
        }
    }

    /// Retains only the characters specified by the predicate.
    ///
    /// # TODO
    ///
    /// This is a bad implementation of a simple function, it creates an entirely new string, it
    /// doesn't require `&mut`. The better version would be easier to implement with `as_mut_str`.
    ///
    /// I don't think I'm going to bother with this any time soon.
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(char) -> bool,
    {
        macro_rules! duck_body {
            ($duck:ident, $f:ident) => {
                for ch in self.chars() {
                    if $f(ch) {
                        $duck.push(ch)
                    }
                }
            };
        }

        let mut result = SsoString::with_capacity(self.capacity());
        match result.tagged_mut() {
            TaggedSsoString64Mut::Long(long) => {
                duck_body!(long, f)
            }
            TaggedSsoString64Mut::Short(short) => {
                duck_body!(short, f)
            }
        }
        *self = result;
    }

    pub fn with_capacity(capacity: usize) -> Self {
        if capacity <= ShortString64::MAX_CAPACITY {
            Self {
                short: ManuallyDrop::new(ShortString64::new()),
            }
        } else {
            Self {
                long: ManuallyDrop::new(LongString::with_capacity(capacity)),
            }
        }
    }

    pub fn shrink_to(&mut self, min_capacity: usize) {
        match self.tagged_mut() {
            TaggedSsoString64Mut::Long(old) => {
                let min_capacity = cmp::max(min_capacity, old.len());
                if min_capacity <= ShortString64::MAX_CAPACITY {
                    let mut short = ShortString64::new();
                    // SAFETY:
                    // 1. short is empty, therefore remaining_capacity == MAX_CAPACITY
                    // 2. old.len() <= min_capacity is true (cmp::max)
                    // 3. min_capacity <= MAX_CAPACITY is true (if statement)
                    // - therefore old.len() <= short.remaining_capacity() because of the following
                    //   derivation:
                    // -> simplifies... old.len() <= MAX_CAPACITY (1)
                    // -> given... old.len() <= min_capacity <= MAX_CAPACITY (2, 3)
                    // -> old.len() <= MAX_CAPACITY == true
                    unsafe {
                        short.push_str_unchecked(old.as_str());
                    }
                    old.free();
                    *self = SsoString {
                        short: ManuallyDrop::new(short),
                    };
                } else {
                    let mut long = LongString::with_capacity(min_capacity);
                    // SAFETY:
                    // - min_capacity >= old.len(), therefore old.len() <= min_capacity
                    // - we have allocated at least min_capacity for long, which is empty
                    // - therefore old.as_str() can be pushed
                    unsafe {
                        long.push_str_unchecked(old.as_str());
                    }
                    old.free();
                    *self = SsoString {
                        long: ManuallyDrop::new(long),
                    };
                }
            }
            TaggedSsoString64Mut::Short(..) => {
                // cannot shrink capacity any further
            }
        }
    }

    /// This is currently just an alias for `self.shrink_to(self.len())`, it doesn't avoid any
    /// branches just because it's always valid
    ///
    /// # TODO
    /// Implement this better
    pub fn shrink_to_fit(&mut self) {
        self.shrink_to(self.len());
    }

    todo_impl!(pub fn split_off(&mut self, _at: usize) -> String);

    todo_impl!(pub fn truncate(&mut self, _new_len: usize));

    todo_impl!(pub fn try_reserve(&mut self, _additional: usize) -> Result<(), TryReserveError>);

    todo_impl! {
        pub fn try_reserve_exact(&mut self, _additional: usize) -> Result<(), TryReserveError>;
    }
}

impl PartialEq<SsoString> for SsoString {
    fn eq(&self, other: &SsoString) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<str> for SsoString {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<SsoString> for str {
    fn eq(&self, other: &SsoString) -> bool {
        self == other.as_str()
    }
}

impl Deref for SsoString {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for SsoString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.tagged() {
            TaggedSsoString64::Short(short) => write!(f, "{}", short),
            TaggedSsoString64::Long(long) => write!(f, "{}", long),
        }
    }
}

impl fmt::Debug for SsoString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.tagged() {
            TaggedSsoString64::Short(short) => write!(f, "{:?}", short),
            TaggedSsoString64::Long(long) => write!(f, "{:?}", long),
        }
    }
}

impl ops::AddAssign<&str> for SsoString {
    fn add_assign(&mut self, rhs: &str) {
        self.push_str(rhs);
    }
}

impl ops::Add<&str> for SsoString {
    type Output = Self;

    fn add(mut self, rhs: &str) -> Self::Output {
        self += rhs;
        self
    }
}

impl Borrow<SsoStr> for SsoString {
    fn borrow(&self) -> &SsoStr {
        // SAFETY: transmute from &T to #[repr(transparent)] &Wrapper(T)
        unsafe { mem::transmute(self.as_str()) }
    }
}

#[macro_export]
macro_rules! format {
    ($($arg:tt)*) => {
        SsoString::from(format!($($arg)*))
    }
}