suiteki 0.1.1

A no_std string type that stores short strings inline, borrows static ones and reference-counts owned ones
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
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
#![doc = include_str!("../README.md")]
#![no_std]
extern crate alloc;

mod impls;
mod shared;
use alloc::{
    borrow::Cow,
    boxed::Box,
    string::{FromUtf8Error, String, ToString},
    vec::Vec,
};
use shared::Shared;

use core::{
    borrow::Borrow,
    mem::{ManuallyDrop, take},
    num::NonZeroUsize,
    ops::Deref,
    ptr::{self, NonNull},
    slice,
};

#[cfg(feature = "nami")]
nami_core::impl_constant!(Str);

/// The width of a machine word, in bytes.
const WORD: usize = size_of::<usize>();

/// How many bytes a `Str` holds without touching the allocator: every byte of
/// its two words except the one the tag lives in. Fifteen on a 64-bit target,
/// seven on a 32-bit one.
const INLINE_CAPACITY: usize = 2 * WORD - 1;

/// Set in the tagged word when the bytes are stored inline.
const INLINE_MARK: usize = 1 << (usize::BITS - 1);

/// Set in the tagged word when the bytes belong to a `&'static str`.
const STATIC_MARK: usize = 1 << (usize::BITS - 2);

/// The bits of the tagged word that carry a heap length.
const LEN_MASK: usize = STATIC_MARK - 1;

/// The longest string a `Str` can describe, in bytes. Both marks are held out
/// of the length, so this is a quarter of the address space: four exabytes on a
/// 64-bit target, a gibibyte on a 32-bit one.
const MAX_LEN: usize = LEN_MASK;

/// The tag byte of an inline string: the mark, then the byte count.
const INLINE_TAG: u8 = 0b1000_0000;

/// The bits of the tag byte that carry the inline byte count.
const INLINE_LEN_MASK: usize = 0b0111_1111;

/// Which of the three representations a `Str` is in.
#[derive(Clone, Copy)]
enum Repr {
    /// The bytes live in the `Str` itself.
    Inline,
    /// The bytes belong to a `&'static str`.
    Static,
    /// The bytes belong to a reference-counted [`Shared`].
    Shared,
}

/// The first word of a `Str`: a data pointer, or the first inline bytes.
///
/// Which one it is, is what `Str::repr` answers. The inline representation
/// initialises every byte, so reading `bytes` is only ever reading initialised
/// memory; `ptr` is only read when a pointer is what was stored.
#[repr(C)]
#[derive(Clone, Copy)]
union Payload {
    ptr: NonNull<()>,
    bytes: [u8; WORD],
}

/// A string type that stores short strings inline, borrows static ones and
/// reference-counts owned ones.
///
/// `Str` is two words wide and never spends more than that. A borrowed `&str`
/// of up to fifteen bytes — seven on a 32-bit target — is copied into those
/// two words with no allocation at all; a `&'static str` is borrowed as-is;
/// and a nonempty owned `String` is moved into a reference-counted box that
/// keeps its buffer and capacity, so cloning it is a counter increment rather
/// than a copy of the bytes.
#[repr(C)]
pub struct Str {
    /// A data pointer, or the first `WORD` inline bytes.
    payload: Payload,

    /// The tagged word: the discriminant, plus either a length or the last
    /// inline bytes.
    ///
    /// It is stored little-endian first, so that its most significant byte —
    /// the one holding the marks — is the *last* byte of the `Str` on every
    /// target. That is what lets the inline bytes run contiguously from the
    /// start of the `Str` up to the tag, whatever the host's byte order.
    ///
    /// Every representation sets at least one bit of that byte, which is what
    /// makes the word non-zero and keeps `Option<Str>` two words wide.
    meta: NonZeroUsize,
}

impl Drop for Str {
    /// Decrements the reference count for owned strings and frees the memory
    /// when the reference count reaches zero.
    ///
    /// For inline and static strings, this is a no-op.
    #[inline]
    fn drop(&mut self) {
        let Some(shared) = self.as_shared() else {
            return;
        };

        if shared.is_unique() {
            // SAFETY: `as_shared` returning `Some` proves `ptr` is the leaked
            // `Shared` box this `Str` holds a count on, and the borrow above has
            // ended. `Drop` runs once, so the last owner reclaims the box once.
            let ptr = unsafe { self.payload.ptr }.cast::<Shared>().as_ptr();
            // SAFETY: as above; the box was leaked by `from_string`.
            drop(unsafe { Box::from_raw(ptr) });
        } else {
            // SAFETY: `Shared::decrement_count` asks for an unreleased count on
            // a live `Shared` that is not the last one. `as_shared` returning
            // `Some` proves the allocation is live and that this `Str` owns a
            // count on it, `is_unique` answering `false` proves the count is not
            // the last, and `Drop` runs once, so it is released once.
            unsafe {
                shared.decrement_count();
            }
        }
    }
}

impl Clone for Str {
    /// Creates a clone of the string.
    ///
    /// For inline and static strings, this is a copy of the two words.
    /// For owned strings, this increments the reference count.
    #[inline]
    fn clone(&self) -> Self {
        if let Some(shared) = self.as_shared() {
            // SAFETY: `Shared::increment_count` asks for an unreleased count on
            // a live `Shared`, and that the count it creates go to exactly one
            // new `Str`. `as_shared` returning `Some` proves this `Str` owns
            // such a count, and the `Str` returned below is the sole taker of
            // the new one.
            unsafe {
                shared.increment_count();
            }
        }

        Self {
            payload: self.payload,
            meta: self.meta,
        }
    }
}

impl Deref for Str {
    type Target = str;

    /// Provides access to the underlying string slice.
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl Borrow<str> for Str {
    /// Allows borrowing a `Str` as a string slice.
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<str> for Str {
    /// Converts `Str` to a string slice reference.
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<[u8]> for Str {
    /// Converts `Str` to a byte slice reference.
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Default for Str {
    /// Creates a new empty `Str`.
    fn default() -> Self {
        Self::new()
    }
}

impl From<Cow<'static, str>> for Str {
    /// Creates a `Str` from a `Cow<'static, str>`.
    ///
    /// This will borrow from static strings and own dynamic strings.
    fn from(value: Cow<'static, str>) -> Self {
        match value {
            Cow::Borrowed(s) => s.into(),
            Cow::Owned(s) => s.into(),
        }
    }
}

/// Implementations of the traits whose types only exist in the standard
/// library, behind the default-on `std` feature.
#[cfg(feature = "std")]
mod std_on {
    use alloc::{string::FromUtf8Error, vec::IntoIter};

    use crate::Str;

    extern crate std;

    use core::{net::SocketAddr, ops::Deref};
    use std::{
        ffi::{OsStr, OsString},
        io,
        net::ToSocketAddrs,
        path::Path,
    };

    impl AsRef<OsStr> for Str {
        /// Converts `Str` to an OS string slice reference.
        fn as_ref(&self) -> &OsStr {
            self.deref().as_ref()
        }
    }

    impl AsRef<Path> for Str {
        /// Converts `Str` to a path reference.
        fn as_ref(&self) -> &Path {
            self.deref().as_ref()
        }
    }

    impl TryFrom<OsString> for Str {
        type Error = FromUtf8Error;

        /// Attempts to create a `Str` from an `OsString`.
        ///
        /// This will fail if the `OsString` contains invalid UTF-8 data.
        fn try_from(value: OsString) -> Result<Self, Self::Error> {
            Self::from_utf8(value.into_encoded_bytes())
        }
    }

    impl ToSocketAddrs for Str {
        type Iter = IntoIter<SocketAddr>;

        /// Converts a string to a socket address.
        fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
            self.deref().to_socket_addrs()
        }
    }
}

impl Str {
    /// Creates a `Str` from a static string slice.
    ///
    /// This method allows creating a `Str` from a string with a static lifetime,
    /// which will be stored as a pointer to the static data without any allocation
    /// and without copying its bytes.
    ///
    /// # Panics
    ///
    /// Panics if the string is longer than a quarter of the address space, which
    /// is the most a `Str` can describe.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s = Str::from_static("hello");
    /// assert_eq!(s, "hello");
    /// // Reference count is intentionally not exposed
    /// ```
    #[must_use]
    #[inline]
    pub const fn from_static(s: &'static str) -> Self {
        let len = s.len();
        assert!(len <= MAX_LEN, "a `Str` cannot describe a string this long");

        // SAFETY: a `&'static str` never has a null data pointer.
        let ptr = unsafe { NonNull::new_unchecked(s.as_ptr().cast_mut().cast::<()>()) };
        // SAFETY: `STATIC_MARK` is set, so the word is not zero, and `to_le`
        // maps zero to zero and everything else to something else.
        let meta = unsafe { NonZeroUsize::new_unchecked((STATIC_MARK | len).to_le()) };

        Self {
            payload: Payload { ptr },
            meta,
        }
    }

    /// Stores the bytes of `s` followed by `suffix` in the `Str` itself.
    ///
    /// # Panics
    ///
    /// Panics if `s` and `suffix` together are longer than `INLINE_CAPACITY`.
    #[inline]
    fn from_inline(s: &str, suffix: &str) -> Self {
        let len = s
            .len()
            .checked_add(suffix.len())
            .expect("inline string length overflow");
        assert!(len <= INLINE_CAPACITY, "the string does not fit inline");

        // Two fixed-width overlapping copies into the bytes of the `Str` laid
        // end to end. Splitting them into the two words afterwards is two
        // copies of a length the compiler knows, which is no copy at all.
        let mut bytes = [0u8; 2 * WORD];
        Self::copy_inline(s.as_bytes(), &mut bytes[..s.len()]);
        Self::copy_inline(suffix.as_bytes(), &mut bytes[s.len()..len]);

        #[expect(
            clippy::cast_possible_truncation,
            reason = "the assert above bounds `len` by `INLINE_CAPACITY`, at most 15"
        )]
        let tag = INLINE_TAG | len as u8;
        bytes[2 * WORD - 1] = tag;

        let mut head = [0u8; WORD];
        let mut tail = [0u8; WORD];
        head.copy_from_slice(&bytes[..WORD]);
        tail.copy_from_slice(&bytes[WORD..]);

        Self {
            payload: Payload { bytes: head },
            // SAFETY: the last byte carries `INLINE_TAG`, so at least one byte
            // of the word is non-zero, whatever the host's byte order.
            meta: unsafe { NonZeroUsize::new_unchecked(usize::from_ne_bytes(tail)) },
        }
    }

    #[inline]
    fn copy_inline(source: &[u8], destination: &mut [u8]) {
        #[inline]
        fn ends<const N: usize>(source: &[u8], destination: &mut [u8]) {
            let end = source.len();
            destination[..N].copy_from_slice(&source[..N]);
            destination[end - N..end].copy_from_slice(&source[end - N..end]);
        }
        match source.len() {
            0 => {}
            1 => destination[0] = source[0],
            2..=3 => ends::<2>(source, destination),
            4..=7 => ends::<4>(source, destination),
            _ => ends::<8>(source, destination),
        }
    }

    /// Creates a `Str` holding a copy of `s`, inline when it fits.
    #[expect(
        clippy::inline_always,
        reason = "keep the empty borrowed-string branch inside callers instead of an allocation-sized frame"
    )]
    #[inline(always)]
    pub(crate) fn from_borrowed(s: &str) -> Self {
        if s.is_empty() {
            Self::new()
        } else if s.len() <= INLINE_CAPACITY {
            Self::from_inline(s, "")
        } else {
            Self::from_string(s.to_string())
        }
    }

    #[inline(never)]
    fn allocate_owned(string: String) -> NonNull<()> {
        NonNull::from(Box::leak(Box::new(Shared::new(string)))).cast::<()>()
    }

    /// # Panics
    ///
    /// Panics if the string is longer than a quarter of the address space.
    #[expect(
        clippy::inline_always,
        reason = "x86-64 cross-crate codegen otherwise outlines the empty owned-string fast path"
    )]
    #[inline(always)]
    fn from_string(string: String) -> Self {
        let len = string.len();
        if len == 0 {
            // Only empty input takes static storage; the buffer is dropped.
            return Self::new();
        }
        assert!(len <= MAX_LEN, "a `Str` cannot describe a string this long");

        Self {
            payload: Payload {
                ptr: Self::allocate_owned(string),
            },
            // SAFETY: a shared string is nonempty, so `len` is not zero, and
            // `to_le` keeps it that way.
            meta: unsafe { NonZeroUsize::new_unchecked(len.to_le()) },
        }
    }

    /// The tagged word, in the host's own bit order.
    const fn tag_word(&self) -> usize {
        usize::from_le(self.meta.get())
    }

    /// Which representation this `Str` is in.
    const fn repr(&self) -> Repr {
        let tag_word = self.tag_word();
        if tag_word & (INLINE_MARK | STATIC_MARK) == 0 {
            Repr::Shared
        } else if tag_word & INLINE_MARK != 0 {
            Repr::Inline
        } else {
            Repr::Static
        }
    }

    /// The byte count an inline string carries in its tag byte.
    const fn inline_len(&self) -> usize {
        (self.tag_word() >> (usize::BITS - 8)) & INLINE_LEN_MASK
    }

    /// Whether the bytes belong to a reference-counted [`Shared`].
    ///
    /// This is the one question `Clone` and `Drop` ask, and neither mark being
    /// set answers it in a single test.
    const fn is_shared(&self) -> bool {
        self.tag_word() & (INLINE_MARK | STATIC_MARK) == 0
    }

    /// The reference-counted box, when that is what this `Str` holds.
    const fn as_shared(&self) -> Option<&Shared> {
        if self.is_shared() {
            // SAFETY: the shared representation is exactly the one whose `ptr`
            // is the leaked `Shared` this `Str` holds a count on; the borrow is
            // tied to `&self`, which keeps that count alive.
            Some(unsafe { self.payload.ptr.cast::<Shared>().as_ref() })
        } else {
            None
        }
    }

    /// Returns a string slice of this `Str`.
    ///
    /// This method works for all three representations.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s1 = Str::from("hello");
    /// assert_eq!(s1.as_str(), "hello");
    ///
    /// let s2 = Str::from(String::from("world"));
    /// assert_eq!(s2.as_str(), "world");
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_str(&self) -> &str {
        let (ptr, len) = match self.repr() {
            // The inline bytes start at the first byte of the `Str` and run up
            // to the tag byte, which is its last.
            Repr::Inline => (ptr::from_ref(self).cast::<u8>(), self.inline_len()),
            // SAFETY: the static representation keeps the pointer and length of
            // the original `&'static str`, which outlives this borrow.
            Repr::Static => (
                unsafe { self.payload.ptr }
                    .as_ptr()
                    .cast_const()
                    .cast::<u8>(),
                self.tag_word() & LEN_MASK,
            ),
            Repr::Shared => {
                // SAFETY: `as_shared_unchecked` asks for the shared
                // representation, which the match arm establishes, and
                // `Shared::as_str` asks for a count that outlives the returned
                // `&str`. This `Str` owns such a count and `&self` outlives the
                // borrow, so the allocation cannot be reclaimed while it lives.
                return unsafe { self.as_shared_unchecked().as_str() };
            }
        };

        // SAFETY: `ptr` and `len` describe the bytes this `Str` was built from,
        // which were UTF-8 already, and which live at least as long as `&self`.
        unsafe { core::str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) }
    }

    /// # Safety
    ///
    /// This `Str` must be in the shared representation.
    const unsafe fn as_shared_unchecked(&self) -> &Shared {
        // SAFETY: the caller guarantees the shared representation, whose `ptr`
        // is the leaked `Shared` this `Str` holds a count on.
        unsafe { self.payload.ptr.cast::<Shared>().as_ref() }
    }

    /// Returns the length of the string, in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    /// let s = Str::from("hello");
    /// assert_eq!(s.len(), 5);
    /// ```
    #[must_use]
    pub const fn len(&self) -> usize {
        if self.tag_word() & INLINE_MARK != 0 {
            self.inline_len()
        } else {
            self.tag_word() & LEN_MASK
        }
    }

    /// Returns `true` if the string has a length of zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    /// let s = Str::new();
    /// assert!(s.is_empty());
    /// let s2 = Str::from("not empty");
    /// assert!(!s2.is_empty());
    /// ```
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    // Intentionally no public API exposing reference counts.

    /// Converts this `Str` into a `String`.
    ///
    /// For inline and static strings, this will allocate a new string and copy
    /// the contents. For owned strings, this will take ownership of the string
    /// if this is the last reference, and copy it otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s1 = Str::from("static");
    /// let s1_string = s1.into_string();
    /// assert_eq!(s1_string, "static");
    ///
    /// let s2 = Str::from(String::from("an owned, heap-sized string"));
    /// let s2_string = s2.into_string();
    /// assert_eq!(s2_string, "an owned, heap-sized string");
    /// ```
    #[must_use]
    #[inline]
    pub fn into_string(self) -> String {
        let this = ManuallyDrop::new(self);
        match this.as_shared() {
            // SAFETY: `self` is wrapped in `ManuallyDrop`, so the count it owns
            // is released exactly once, here, and `as_shared` returning `Some`
            // proves this `Str` holds a count on a live `Shared` allocation.
            // In the unique branch, `Shared::take` asks for the last count and
            // for the leaked box to have been reclaimed: `is_unique` answered
            // `true` and `Box::from_raw` takes back what `from_string` leaked.
            // In the other branch, `Shared::decrement_count` asks for an
            // unreleased count that is not the last, which `is_unique`
            // answering `false` proves, and `Shared::as_str` asks for a count
            // that outlives the borrow, which the owner that same answer
            // proves still exists holds for as long as the bytes are copied
            // out.
            Some(shared) => unsafe {
                if shared.is_unique() {
                    let shared = Box::from_raw(this.payload.ptr.cast::<Shared>().as_ptr());

                    shared.take()
                } else {
                    shared.decrement_count();
                    shared.as_str().to_string()
                }
            },
            None => this.as_str().to_string(),
        }
    }
}

impl Str {
    /// Creates a new empty `Str`.
    ///
    /// This returns a static empty string reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s = Str::new();
    /// assert_eq!(s, "");
    /// // Reference count is intentionally not exposed
    /// ```
    #[must_use]
    #[inline]
    pub const fn new() -> Self {
        Self::from_static("")
    }

    /// Creates a `Str` from a vector of bytes.
    ///
    /// This function will attempt to convert the vector to a UTF-8 string and
    /// wrap it in a `Str`. If the vector does not contain valid UTF-8, an error
    /// is returned.
    ///
    /// # Errors
    ///
    /// Returns an error if the provided byte vector does not contain valid UTF-8 data.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let bytes = vec![104, 101, 108, 108, 111]; // "hello" in UTF-8
    /// let s = Str::from_utf8(bytes).unwrap();
    /// assert_eq!(s, "hello");
    /// // Reference count is intentionally not exposed
    ///
    /// // Invalid UTF-8 sequence
    /// let invalid = vec![0xFF, 0xFF];
    /// assert!(Str::from_utf8(invalid).is_err());
    /// ```
    #[inline]
    pub fn from_utf8(bytes: Vec<u8>) -> Result<Self, FromUtf8Error> {
        String::from_utf8(bytes).map(Self::from)
    }

    /// # Safety
    ///
    /// This function is unsafe because it does not check that the bytes passed
    /// to it are valid UTF-8. If this constraint is violated, it may cause
    /// memory unsafety issues with future users of the `Str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// // SAFETY: We know these bytes form valid UTF-8
    /// let bytes = vec![104, 101, 108, 108, 111]; // "hello" in UTF-8
    /// let s = unsafe { Str::from_utf8_unchecked(bytes) };
    /// assert_eq!(s, "hello");
    /// ```
    #[must_use]
    pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> Self {
        // SAFETY: this function's own contract requires `bytes` to be valid UTF-8.
        unsafe { Self::from(String::from_utf8_unchecked(bytes)) }
    }

    /// Applies a function to the owned string representation of this `Str`.
    ///
    /// This is an internal utility method used for operations that need to modify
    /// the string contents.
    fn handle(&mut self, f: impl FnOnce(&mut String)) {
        let mut string = take(self).into_string();
        f(&mut string);
        *self = Self::from(string);
    }

    fn extend_parts<S: AsRef<str>>(&mut self, iter: impl IntoIterator<Item = S>) {
        fn extend_string<S: AsRef<str>>(string: &mut String, iter: impl Iterator<Item = S>) {
            for part in iter {
                string.push_str(part.as_ref());
            }
        }
        let mut iter = iter.into_iter().peekable();
        if iter.peek().is_none() {
            return;
        }
        if self.is_shared() || self.len() > INLINE_CAPACITY {
            self.handle(|string| extend_string(string, iter));
            return;
        }
        let mut bytes = [0u8; INLINE_CAPACITY];
        let mut len = self.len();
        bytes[..len].copy_from_slice(self.as_bytes());
        while let Some(part) = iter.next() {
            let part = part.as_ref();
            if part.len() <= INLINE_CAPACITY - len {
                let end = len + part.len();
                Self::copy_inline(part.as_bytes(), &mut bytes[len..end]);
                len = end;
            } else {
                let total = len.checked_add(part.len()).expect("string length overflow");
                let prefix =
                    core::str::from_utf8(&bytes[..len]).expect("concatenated UTF-8 strings");
                let mut string = String::with_capacity(total);
                string.push_str(prefix);
                string.push_str(part);
                extend_string(&mut string, iter);
                *self = Self::from(string);
                return;
            }
        }
        *self = Self::from_borrowed(
            core::str::from_utf8(&bytes[..len]).expect("concatenated UTF-8 strings"),
        );
    }

    /// Appends a string to this `Str`.
    ///
    /// This method will convert the `Str` to an owned string if it's a static reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let mut s = Str::from("hello");
    /// s.append(" world");
    /// assert_eq!(s, "hello world");
    /// ```
    pub fn append(&mut self, s: impl AsRef<str>) {
        let s = s.as_ref();
        if s.is_empty() {
            return;
        }
        if !self.is_shared()
            && self
                .len()
                .checked_add(s.len())
                .is_some_and(|len| len <= INLINE_CAPACITY)
        {
            *self = Self::from_inline(self.as_str(), s);
        } else {
            self.handle(|string| string.push_str(s));
        }
    }
}
impl From<&'static str> for Str {
    /// Creates a `Str` from a static string slice.
    ///
    /// This stores a reference to the original string without any allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s = Str::from("hello");
    /// assert_eq!(s, "hello");
    /// // Reference count is intentionally not exposed
    /// ```
    #[inline]
    fn from(value: &'static str) -> Self {
        Self::from_static(value)
    }
}

impl From<String> for Str {
    /// Creates a `Str` from an owned `String`.
    ///
    /// The string keeps its own buffer inside a reference-counted box, so its
    /// capacity survives; only an empty `String` takes static storage.
    ///
    /// # Examples
    ///
    /// ```
    /// use suiteki::Str;
    ///
    /// let s = Str::from(String::from("hello"));
    /// assert_eq!(s, "hello");
    /// // Reference count is intentionally not exposed
    /// ```
    #[inline]
    fn from(value: String) -> Self {
        Self::from_string(value)
    }
}

impl From<Str> for String {
    fn from(value: Str) -> Self {
        value.into_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    /// A hasher that just records the bytes it is fed, so the tests can compare
    /// what two `Str`s hash *from* without pulling in `std`'s `DefaultHasher`.
    #[derive(Default)]
    struct Recorder(alloc::vec::Vec<u8>);

    impl core::hash::Hasher for Recorder {
        fn write(&mut self, bytes: &[u8]) {
            self.0.extend_from_slice(bytes);
        }

        fn finish(&self) -> u64 {
            self.0.iter().fold(0u64, |acc, &b| {
                acc.wrapping_mul(31).wrapping_add(u64::from(b))
            })
        }
    }

    fn hash_of(value: &Str) -> u64 {
        use core::hash::{Hash, Hasher};
        let mut hasher = Recorder::default();
        value.hash(&mut hasher);
        hasher.finish()
    }

    /// The three representations of the same text, for the tests that require
    /// all of them to be indistinguishable.
    fn every_representation(text: &'static str) -> [Str; 3] {
        [
            Str::from_static(text),
            Str::from(String::from(text)),
            Str::from_borrowed(text),
        ]
    }

    #[test]
    fn a_str_is_two_words_wide() {
        assert_eq!(size_of::<Str>(), 2 * size_of::<usize>());
        assert_eq!(align_of::<Str>(), align_of::<usize>());
        // The tagged word is never zero, so the niche is still there and an
        // `Option<Str>` costs nothing over a `Str`.
        assert_eq!(size_of::<Option<Str>>(), size_of::<Str>());
    }

    #[test]
    fn a_static_string_is_still_a_constant() {
        // The length check `from_static` makes is evaluated at compile time for
        // a literal, which is what keeps `Str::from("...")` free in real code
        // even though the benchmark's opaque length has to pay for it.
        const GREETING: Str = Str::from_static("hello");
        assert_eq!(GREETING.as_str(), "hello");
        assert_eq!(GREETING.len(), 5);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn sixteen_bytes_hold_fifteen() {
        assert_eq!(size_of::<Str>(), 16);
        assert_eq!(INLINE_CAPACITY, 15);
    }

    #[test]
    fn empty_construction_uses_static_storage() {
        for value in [
            Str::new(),
            Str::from_borrowed(""),
            Str::from(String::new()),
            Str::from(String::with_capacity(64)),
            Str::from_utf8(Vec::with_capacity(64)).unwrap(),
        ] {
            assert!(matches!(value.repr(), Repr::Static));
            assert!(value.is_empty());
            assert_eq!(value.as_str(), "");
        }
    }

    #[test]
    fn borrowed_strings_use_static_empty_or_inline_storage() {
        for len in 0..=INLINE_CAPACITY {
            let text: String = "abcdefghijklmno".chars().take(len).collect();
            let inline = Str::from_borrowed(&text);

            if len == 0 {
                assert!(matches!(inline.repr(), Repr::Static));
            } else {
                assert!(matches!(inline.repr(), Repr::Inline), "{len} bytes");
            }
            assert_eq!(inline.as_str(), text, "{len} bytes");
            assert_eq!(inline.len(), len, "{len} bytes");
            assert_eq!(inline.is_empty(), len == 0, "{len} bytes");
        }
    }

    #[test]
    fn one_byte_past_the_capacity_is_shared() {
        let text = "abcdefghijklmnopqrstuvwxyz"
            .chars()
            .take(INLINE_CAPACITY + 1)
            .collect::<String>();
        let shared = Str::from(text.clone());

        assert!(matches!(shared.repr(), Repr::Shared));
        assert_eq!(shared.as_str(), text);
        assert_eq!(shared.len(), INLINE_CAPACITY + 1);
        // Cloning a shared string still shares the bytes.
        assert_eq!(shared.clone().as_str().as_ptr(), shared.as_str().as_ptr());
    }

    #[test]
    fn a_static_string_stays_borrowed_whatever_its_length() {
        let short = Str::from_static("short");
        let long = Str::from_static("a string that is well past the inline capacity");

        assert!(matches!(short.repr(), Repr::Static));
        assert!(matches!(long.repr(), Repr::Static));
        assert_eq!(short.as_str().as_ptr(), "short".as_ptr());
    }

    #[test]
    fn the_representation_does_not_change_what_a_str_is() {
        for text in [
            "",
            "x",
            "fifteen bytes!!",
            "sixteen bytes!!!",
            "a much longer string",
        ] {
            let [borrowed, owned, copied] = every_representation(text);

            assert_eq!(borrowed, owned);
            assert_eq!(owned, copied);
            assert_eq!(borrowed.as_str(), text);
            assert_eq!(copied.as_str(), text);
            assert_eq!(borrowed.len(), text.len());
            assert_eq!(owned.len(), text.len());
            assert_eq!(copied.len(), text.len());
            assert_eq!(hash_of(&borrowed), hash_of(&owned));
            assert_eq!(hash_of(&owned), hash_of(&copied));
            assert_eq!(borrowed.cmp(&owned), core::cmp::Ordering::Equal);
            assert_eq!(borrowed.clone().into_string(), text);
            assert_eq!(owned.clone().into_string(), text);
            assert_eq!(copied.clone().into_string(), text);
        }
    }

    #[test]
    fn an_inline_string_survives_being_moved() {
        // The inline bytes live in the `Str` itself, so anything that moves one
        // has to keep reading the right bytes afterwards.
        let mut moved = vec![Str::from_borrowed("inline!")];
        for i in 0..64 {
            let mut text = String::from("n");
            text.push_str(&i.to_string());
            moved.push(Str::from_borrowed(&text));
        }
        moved.rotate_left(7);
        let boxed = moved.into_boxed_slice();

        assert_eq!(boxed[boxed.len() - 7].as_str(), "inline!");
        assert_eq!(boxed[boxed.len() - 6].as_str(), "n0");
    }

    #[test]
    fn appending_crosses_the_boundary_in_both_directions() {
        let mut s = Str::from_borrowed("inline");
        assert!(matches!(s.repr(), Repr::Inline));

        s.append(" and then some more bytes");
        assert!(matches!(s.repr(), Repr::Shared));
        assert_eq!(s.as_str(), "inline and then some more bytes");

        let mut back = Str::from_borrowed(&s.as_str()[..6]);
        assert!(matches!(back.repr(), Repr::Inline));
        back.append("");
        assert_eq!(back.as_str(), "inline");
    }

    #[test]
    fn a_long_string_is_still_a_string() {
        // Well past every tag bit, so a length that leaked into the tag would
        // show up here.
        let text = "x".repeat(1 << 20);
        let s = Str::from(text.clone());
        assert_eq!(s.len(), text.len());
        assert_eq!(s.as_str(), text);
    }

    #[test]
    fn test_static_string_creation() {
        let s = Str::from_static("hello");
        assert_eq!(s.as_str(), "hello");
        assert_eq!(s.len(), 5);
        assert!(!s.is_empty());
        // no reference count exposed
    }

    #[test]
    fn test_owned_string_creation() {
        let s = Str::from(String::from("hello"));
        assert_eq!(s.as_str(), "hello");
        assert_eq!(s.len(), 5);
        assert!(!s.is_empty());
        // no reference count exposed
    }

    #[test]
    fn test_empty_string() {
        let s = Str::new();
        assert_eq!(s.as_str(), "");
        assert_eq!(s.len(), 0);
        assert!(s.is_empty());
        // no reference count exposed
    }

    #[test]
    fn test_static_string_clone() {
        let s1 = Str::from_static("hello");
        let s2 = s1.clone();

        assert_eq!(s1.as_str(), "hello");
        assert_eq!(s2.as_str(), "hello");
        // no reference count exposed
    }

    #[test]
    fn test_owned_string_clone() {
        let s1 = Str::from(String::from("hello"));
        let s2 = s1.clone();

        assert_eq!(s1.as_str(), "hello");
        assert_eq!(s2.as_str(), "hello");
    }

    #[test]
    fn test_multiple_clones() {
        let s1 = Str::from(String::from("test"));
        let s2 = s1.clone();
        let s3 = s1;
        let s4 = s2.clone();

        // no reference count exposed

        drop(s4);
        // no reference count exposed

        drop(s3);
        drop(s2);
        // no reference count exposed
    }

    #[test]
    fn test_reference_counting_drop() {
        let s1 = Str::from(String::from("hello"));

        {
            let _s2 = s1;
        } // s2 is dropped here

        // no reference count exposed
    }

    #[test]
    fn test_into_string_unique() {
        let s = Str::from(String::from("hello"));
        // no reference count exposed

        let string = s.into_string();
        assert_eq!(string, "hello");
    }

    #[test]
    fn test_into_string_shared() {
        let s1 = Str::from(String::from("hello"));
        let _s2 = s1.clone();

        let string = s1.into_string();
        assert_eq!(string, "hello");
        // no reference count exposed
    }

    #[test]
    fn test_into_string_static() {
        let s = Str::from_static("hello");
        let string = s.into_string();
        assert_eq!(string, "hello");
    }

    #[test]
    fn test_from_utf8_valid() {
        let bytes = vec![104, 101, 108, 108, 111]; // "hello"
        let s = Str::from_utf8(bytes).unwrap();
        assert_eq!(s.as_str(), "hello");
    }

    #[test]
    fn test_from_utf8_invalid() {
        let bytes = vec![0xFF, 0xFF];
        assert!(Str::from_utf8(bytes).is_err());
    }

    #[test]
    fn test_from_utf8_unchecked() {
        let bytes = vec![104, 101, 108, 108, 111]; // "hello"
        // SAFETY: `bytes` is the ASCII literal spelled out just above, so it is
        // valid UTF-8.
        let s = unsafe { Str::from_utf8_unchecked(bytes) };
        assert_eq!(s.as_str(), "hello");
        // no reference count exposed
    }

    #[test]
    fn test_append() {
        let mut s = Str::from("hello");
        s.append(" world");
        assert_eq!(s.as_str(), "hello world");
    }

    #[test]
    fn test_append_static_to_owned() {
        let mut s = Str::from_static("hello");

        s.append(" world");
        assert_eq!(s.as_str(), "hello world");
    }

    #[test]
    fn test_as_bytes() {
        let s = Str::from("hello");
        assert_eq!(s.as_bytes(), b"hello");
    }

    #[test]
    fn test_deref() {
        let s = Str::from("hello");
        assert_eq!(&*s, "hello");
        assert_eq!(s.chars().count(), 5);
    }

    #[test]
    fn test_empty_string_from_string() {
        let s = Str::from(String::new());
        assert_eq!(s.as_str(), "");
        assert!(s.is_empty());
        // no reference count exposed
    }

    // Memory safety tests designed for Miri
    #[test]
    fn test_memory_safety_clone_drop_cycles() {
        // Test multiple clone/drop cycles to ensure no memory leaks or double-frees
        for text in ["test", "a heap string long enough to remain shared"] {
            for _ in 0..100 {
                let s1 = Str::from(String::from(text));
                let s2 = s1.clone();
                let s3 = s2.clone();

                drop(s1);
                drop(s3);
                drop(s2);
            }
        }
    }

    #[test]
    fn every_inline_length_survives_offset_input_and_moves() {
        for len in 0..=INLINE_CAPACITY + 1 {
            for offset in 0..WORD {
                let text = "q".repeat(offset + len + 1).into_boxed_str();
                let input = &text[offset..offset + len];
                let value = Str::from_borrowed(input);
                let mut values = vec![None, Some(value.clone()), Some(value)];
                values.rotate_left(1);
                let boxed = values.into_boxed_slice();
                drop(text);
                for value in boxed.iter().flatten() {
                    assert_eq!(value.as_str(), "q".repeat(len));
                    assert_eq!(value.len(), len);
                    assert_eq!(value.clone().into_string(), "q".repeat(len));
                }
            }
        }
    }

    #[test]
    fn utf8_boundaries_and_nuls_survive_ownership_transitions() {
        for scalar in ["\0", "é", "界", "\u{1f642}"] {
            for padding in 0..=INLINE_CAPACITY + 1 {
                let text = "x".repeat(padding) + scalar;
                for mut value in [
                    Str::from_utf8(text.as_bytes().to_vec()).unwrap(),
                    Str::from_borrowed(&text),
                ] {
                    let alias = value.clone();
                    value.append(scalar);
                    assert_eq!(alias.as_str(), text);
                    assert_eq!(alias.len(), text.len());
                    assert_eq!(value.as_str(), text.clone() + scalar);
                    drop(value);
                    assert_eq!(alias.into_string(), text);
                }
            }
        }
        for bytes in [
            vec![0xc0, 0x80],
            vec![0xed, 0xa0, 0x80],
            vec![0xf4, 0x90, 0x80, 0x80],
            vec![0xe2, 0x82],
        ] {
            let mut input = vec![b'x'; INLINE_CAPACITY];
            input.extend(bytes);
            let error = Str::from_utf8(input.clone()).unwrap_err();
            assert_eq!(error.into_bytes(), input);
        }
    }

    #[test]
    fn heap_aliases_survive_every_three_owner_release_order() {
        let text = "shared".repeat(INLINE_CAPACITY + 1);
        for order in [
            [0, 1, 2],
            [0, 2, 1],
            [1, 0, 2],
            [1, 2, 0],
            [2, 0, 1],
            [2, 1, 0],
        ] {
            for convert in 0..8 {
                let value = Str::from(text.clone());
                let pointer = value.as_str().as_ptr();
                let mut owners = [Some(value.clone()), Some(value.clone()), Some(value)];
                for (step, index) in order.into_iter().enumerate() {
                    let owner = owners[index].take().unwrap();
                    if convert & (1 << step) == 0 {
                        drop(owner);
                    } else {
                        let string = owner.into_string();
                        assert_eq!(string, text);
                        if step == 2 {
                            assert_eq!(string.as_ptr(), pointer);
                        } else {
                            assert_ne!(string.as_ptr(), pointer);
                        }
                    }
                    for survivor in owners.iter().flatten() {
                        assert_eq!(survivor.as_str(), text);
                        assert_eq!(survivor.as_str().as_ptr(), pointer);
                    }
                }
            }
        }
    }

    #[test]
    fn heap_mutation_detaches_and_preserves_reserved_capacity() {
        let text = "a".repeat(INLINE_CAPACITY + 1);
        let mut string = String::with_capacity(text.len() + 128);
        string.push_str(&text);
        let pointer = string.as_ptr();
        let capacity = string.capacity();
        let mut unique = Str::from(string);
        unique.append("tail");
        let string = unique.into_string();
        assert_eq!(string.as_ptr(), pointer);
        assert_eq!(string.capacity(), capacity);
        let mut shared = Str::from(string);
        let original = shared.clone();
        shared += "suffix";
        assert_eq!(original.as_str(), text.clone() + "tail");
        assert_eq!(shared.as_str(), text + "tailsuffix");
        drop(shared);
        let string = original.into_string();
        assert_eq!(string.as_ptr(), pointer);
    }

    #[test]
    fn iterator_unwind_keeps_alias_and_receiver_valid() {
        extern crate std;
        for text in ["short", "a long shared string beyond inline"] {
            for mut value in every_representation(text) {
                let alias = value.clone();
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    value.extend(["first", "second"].into_iter().inspect(|&part| {
                        assert_ne!(part, "second", "iterator panic");
                    }));
                }));
                assert!(result.is_err());
                assert_eq!(alias.as_str(), text);
                assert_eq!(value.len(), value.as_str().len());
                value.append("after unwind");
                assert!(value.as_str().ends_with("after unwind"));
                drop(alias);
            }
        }
    }

    #[test]
    fn empty_extend_preserves_shared_buffer_and_aliases() {
        let mut value = Str::from(String::from("short"));
        let alias = value.clone();
        let pointer = value.as_str().as_ptr();
        value.extend(core::iter::empty::<&str>());
        value.extend(core::iter::empty::<String>());
        value.extend(core::iter::empty::<Str>());
        assert_eq!(value.as_str().as_ptr(), pointer);
        assert_eq!(value, alias);
    }

    #[test]
    fn owned_strings_preserve_buffers_at_every_inline_boundary() {
        for len in 1..=INLINE_CAPACITY + 1 {
            let mut string = String::with_capacity(INLINE_CAPACITY * 4);
            string.push_str(&"x".repeat(len));
            let pointer = string.as_ptr();
            let capacity = string.capacity();
            let mut value = Str::from(string);
            assert!(matches!(value.repr(), Repr::Shared));
            assert_eq!(value.as_str().as_ptr(), pointer);
            let alias = value.clone();
            let copied = alias.into_string();
            assert_eq!(copied, "x".repeat(len));
            assert_ne!(copied.as_ptr(), pointer);
            value.append("y");
            let string = value.into_string();
            assert_eq!(string, "x".repeat(len) + "y");
            assert_eq!(string.as_ptr(), pointer);
            assert_eq!(string.capacity(), capacity);
        }
    }

    #[test]
    fn equal_addresses_do_not_make_different_lengths_equal() {
        let text = "same allocation, different lengths";
        let full = Str::from_static(text);
        let prefix = Str::from_static(&text[..4]);
        assert_eq!(full.as_str().as_ptr(), prefix.as_str().as_ptr());
        assert_ne!(full, prefix);
        assert_eq!(full, full.clone());
        assert_eq!(Str::from_borrowed(""), Str::new());
    }

    #[test]
    fn mutation_traits_match_string_across_representations() {
        for text in [
            "",
            "x",
            "é水",
            "a long heap string past the inline boundary",
        ] {
            for value in every_representation(text) {
                let suffixes = ["", "a", "é", "an appended heap string"];
                let expected = String::from(text) + &suffixes.concat();
                let mut by_append = value.clone();
                let mut by_assign = value.clone();
                let mut by_extend = value.clone();
                let mut by_owned = value.clone();
                let mut by_str = value.clone();
                for suffix in suffixes {
                    by_append.append(suffix);
                    by_assign += suffix;
                }
                by_extend.extend(suffixes);
                by_owned.extend(suffixes.map(String::from));
                by_str.extend(suffixes.map(Str::from_static));
                for result in [by_append, by_assign, by_extend, by_owned, by_str] {
                    assert_eq!(result.as_str(), expected);
                    assert_eq!(result.len(), expected.len());
                }
                assert_eq!((&value + "tail").as_str(), String::from(text) + "tail");
                assert_eq!(value.as_str(), text);
            }
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_owned_and_borrowed_inputs_keep_their_storage_contracts() {
        use serde::{
            Deserialize,
            de::value::{Error, StrDeserializer, StringDeserializer},
        };
        for text in ["", "short", "a long heap string past the inline boundary"] {
            let borrowed = Str::deserialize(StrDeserializer::<Error>::new(text)).unwrap();
            let string = String::from(text);
            let pointer = string.as_ptr();
            let owned = Str::deserialize(StringDeserializer::<Error>::new(string)).unwrap();
            assert_eq!(borrowed.as_str(), text);
            assert_eq!(owned.as_str(), text);
            if !text.is_empty() {
                assert_eq!(owned.as_str().as_ptr(), pointer);
            }
            assert_eq!(owned, borrowed);
        }
    }

    #[test]
    fn test_memory_safety_interleaved_operations() {
        let mut strings = vec![];

        // Create multiple strings with shared references
        for i in 0..10 {
            let mut content = String::from("string_");
            content.push_str(&(i.to_string()));
            let s = Str::from(content);
            strings.push(s.clone());
            strings.push(s);
        }

        // Randomly drop some strings
        for i in (0..strings.len()).step_by(3) {
            if i < strings.len() {
                strings.remove(i);
            }
        }

        // Verify remaining strings are still valid
        for s in &strings {
            assert!(!s.as_str().is_empty());
        }
    }

    #[test]
    fn test_memory_safety_reference_counting() {
        let original = Str::from(String::from("reference test"));
        let mut clones = vec![];

        // Create many clones
        for _ in 0..50 {
            clones.push(original.clone());
        }
        assert_eq!(clones.len(), 50);

        // no reference count exposed

        // Drop half the clones
        clones.truncate(25);
        assert_eq!(clones.len(), 25);
        // no reference count exposed

        // Drop all clones
        clones.clear();
        assert!(clones.is_empty());
        // no reference count exposed
    }

    #[test]
    fn test_memory_safety_into_string_with_clones() {
        let s1 = Str::from(String::from("unique test"));
        let _s2 = s1.clone();
        let _s3 = s1.clone();

        // no reference count exposed

        // Converting to string should not affect other references
        let string = s1.into_string();
        assert_eq!(string, "unique test");
        // no reference count exposed
    }

    #[test]
    fn test_memory_safety_unique_into_string() {
        // Test that unique references properly transfer ownership
        let s = Str::from(String::from("unique"));
        // no reference count exposed

        let string = s.into_string();
        assert_eq!(string, "unique");
        // s is consumed, can't check reference count
    }

    #[test]
    fn test_memory_safety_static_vs_owned() {
        let static_str = Str::from_static("static");
        let owned_str = Str::from(String::from("owned"));

        // Clone both types many times
        let mut static_clones = vec![];
        let mut owned_clones = vec![];

        for _ in 0..100 {
            static_clones.push(static_str.clone());
            owned_clones.push(owned_str.clone());
        }

        // no reference count exposed

        // Verify all clones work correctly
        for clone in &static_clones {
            assert_eq!(clone.as_str(), "static");
            // no reference count exposed
        }

        for clone in &owned_clones {
            assert_eq!(clone.as_str(), "owned");
            // no reference count exposed
        }
    }

    #[test]
    fn test_memory_safety_mixed_operations() {
        let mut s = Str::from_static("hello");
        // no reference count exposed

        // Convert to owned by appending
        s.append(" world");
        // no reference count exposed

        // Clone the owned string
        let _s2 = s.clone();
        // no reference count exposed

        // Convert back to string
        let string = s.into_string();
        assert_eq!(string, "hello world");
        // no reference count exposed
    }

    #[test]
    fn test_memory_safety_zero_length_edge_cases() {
        // Test various ways to create empty strings
        let empty1 = Str::new();
        let empty2 = Str::from("");
        let empty3 = Str::from(String::new());
        let empty4 = Str::from_utf8(vec![]).unwrap();

        assert!(empty1.is_empty());
        assert!(empty2.is_empty());
        assert!(empty3.is_empty());
        assert!(empty4.is_empty());

        // All empty strings should be static references
        // no reference count exposed
    }

    #[test]
    fn test_memory_safety_large_strings() {
        // Test with larger strings to ensure proper memory handling
        let large_content = "x".repeat(10000);
        let s1 = Str::from(large_content.clone());
        // no reference count exposed

        let s2 = s1.clone();
        // no reference count exposed

        assert_eq!(s1.len(), 10000);
        assert_eq!(s2.len(), 10000);
        assert_eq!(s1.as_str(), large_content);
        assert_eq!(s2.as_str(), large_content);
    }

    #[test]
    fn test_memory_safety_concurrent_like_pattern() {
        // Simulate concurrent-like access patterns (single-threaded but similar stress)
        let base = Str::from(String::from("base"));
        let mut handles = vec![];

        // Create many references
        for _ in 0..1000 {
            handles.push(base.clone());
        }

        // no reference count exposed

        // Process in chunks, dropping some while keeping others
        for chunk in handles.chunks_mut(100) {
            for (i, handle) in chunk.iter().enumerate() {
                assert_eq!(handle.as_str(), "base");
                if i.is_multiple_of(2) {
                    // Mark for keeping (we'll drop the others)
                }
            }
        }

        // Keep only every 3rd element
        let mut i = 0;
        handles.retain(|_| {
            i += 1;
            i % 3 == 0
        });

        // Verify reference count updated correctly
        let _expected_count = handles.len() + 1; // +1 for base

        // Verify all remaining handles are valid
        for handle in &handles {
            assert_eq!(handle.as_str(), "base");
        }
    }

    #[test]
    fn test_memory_safety_drop_order_stress() {
        // Test various drop orders to ensure no use-after-free
        let s1 = Str::from(String::from("original"));
        let s2 = s1.clone();
        let s3 = s1.clone();
        let s4 = s2.clone();
        let s5 = s3.clone();

        // no reference count exposed

        // Drop in different orders across multiple test runs
        {
            let temp1 = s1.clone();
            let temp2 = s2.clone();
            drop(temp2);
            drop(temp1);
            // temp1 and temp2 dropped first
        }

        // no reference count exposed

        drop(s5); // Drop s5 first
        // no reference count exposed

        drop(s2); // Drop s2 (middle)
        // no reference count exposed

        drop(s1); // Drop original
        // no reference count exposed

        drop(s4); // Drop s4
        // no reference count exposed

        // s3 is the last one standing
        assert_eq!(s3.as_str(), "original");
    }

    #[test]
    fn test_memory_safety_ptr_stability() {
        // Ensure string content pointer remains stable across clones. Sharing
        // the bytes is what the reference-counted representation is for, and
        // owning a `String` — not the string's length — is what puts one in
        // it: an inline string is copied by a clone, and copies are the point.
        let s1 = Str::from(String::from("a stable, heap-sized allocation"));
        let ptr1 = s1.as_str().as_ptr();

        let s2 = s1.clone();
        let ptr2 = s2.as_str().as_ptr();

        // Clones should point to the same underlying data
        assert_eq!(ptr1, ptr2);

        let s3 = s2.clone();
        let ptr3 = s3.as_str().as_ptr();

        assert_eq!(ptr1, ptr3);
        assert_eq!(ptr2, ptr3);

        // Even after dropping some references, remaining should still be valid
        drop(s1);
        assert_eq!(s2.as_str().as_ptr(), ptr2);
        assert_eq!(s3.as_str().as_ptr(), ptr3);
    }

    #[test]
    fn test_memory_safety_alternating_clone_drop() {
        let original = Str::from(String::from("alternating"));
        let mut refs = vec![original];

        // Alternating pattern: clone, clone, drop, clone, drop, etc.
        for i in 0..100 {
            if i % 4 == 0 || i % 4 == 1 {
                // Clone phase
                let new_ref = refs[0].clone();
                refs.push(new_ref);
            } else if i % 4 == 2 && refs.len() > 1 {
                // Drop phase
                refs.pop();
            }

            // Verify all remaining references are valid
            for r in &refs {
                assert_eq!(r.as_str(), "alternating");
            }
        }
    }
}