strkind 0.0.2

Semantic string newtypes, generic over their storage: one type per kind of string, any string-like backing (String, str, Arc<str>, SmolStr, ...).
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
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", env!("CARGO_PKG_README")))]
#![cfg_attr(docsrs, feature(doc_cfg))]
// The `ExAsRef` declaration below needs the unstable sized-hierarchy traits
// (`AsRef`'s own bounds use them); the Verus driver permits the feature on
// its pinned stable toolchain (vstd itself does the same).
#![cfg_attr(all(feature = "verus", verus_keep_ghost), feature(sized_hierarchy))]
#![no_std]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(test)]
extern crate std;

// Re-exports for macro-generated code. Not a public API.
//
// `::alloc` is not in the extern prelude, so expanded code cannot name it in
// downstream crates that lack their own `extern crate alloc;` - paths through
// `$crate::__private` are the only ones guaranteed to resolve.
#[doc(hidden)]
pub mod __private {
    #[cfg(feature = "alloc")]
    pub use alloc::borrow::ToOwned;
    #[cfg(feature = "alloc")]
    pub use alloc::string::String;
    #[cfg(feature = "serde")]
    pub use serde;
    #[cfg(feature = "verus")]
    pub use vstd;
}

/// The Verus external-trait declaration for `AsRef`, which vstd does not
/// (yet) provide. Declared here, once - Verus allows only one
/// `external_trait_specification` per trait per crate graph, so it cannot be
/// emitted per `strkind!` expansion. The `[package.metadata.verus]` entry in
/// Cargo.toml makes the Verus driver keep (and export) this ghost code when
/// strkind is a dependency of a verified crate.
#[cfg(all(feature = "verus", verus_keep_ghost))]
const _: () = {
    vstd::prelude::verus! {
        #[verifier::external_trait_specification]
        pub trait ExAsRef<T: ::core::marker::PointeeSized>: ::core::marker::PointeeSized {
            type ExternalTraitSpecificationFor: ::core::convert::AsRef<T>;
        }
    }
};

/// Define one or more string kinds.
///
/// Each item is `[visibility] Name;`. For the full generated API, see the
/// [`example::ExampleId`]'s impls.
///
/// ```
/// strkind::strkind! {
///     /// Identifies a conversation thread.
///     pub ThreadId;
///
///     /// A git commit hash.
///     pub CommitId;
/// }
///
/// let id = CommitId::from("abc123");
/// assert_eq!(id.as_str(), "abc123");
/// ```
#[macro_export]
macro_rules! strkind {
    () => {};

    (
        $(#[$meta:meta])*
        $vis:vis $Name:ident ;
        $($rest:tt)*
    ) => {
        $crate::__strkind_struct! { $(#[$meta])* $vis $Name }

        impl<T: AsRef<str>> $Name<T> {
            /// Wrap `storage` as this kind.
            $vis const fn new(storage: T) -> Self {
                Self(storage)
            }

            /// Unwrap into the underlying storage.
            $vis fn into_inner(self) -> T {
                self.0
            }

            /// Convert the storage type (e.g. `String` → `Arc<str>`),
            /// preserving the kind.
            $vis fn convert<U: AsRef<str> + ::core::convert::From<T>>(self) -> $Name<U> {
                $Name(U::from(self.0))
            }
        }

        impl<T: ?Sized + AsRef<str>> $Name<T> {
            /// View as a plain `&str`, for passing to APIs that require one.
            $vis fn as_str(&self) -> &str {
                self.0.as_ref()
            }
        }

        impl $Name<str> {
            /// Cast a borrowed `&str` to a borrowed kind, without allocating.
            $vis const fn from_ref(s: &str) -> &Self {
                // SAFETY: `$Name` is `#[repr(transparent)]` over its single
                // field, so `$Name<str>` has the same layout as `str`. This
                // is the same cast `std` uses for `Path::new`.
                unsafe { &*(::core::ptr::from_ref::<str>(s) as *const Self) }
            }
        }

        impl<T: ?Sized + AsRef<str>> ::core::convert::AsRef<str> for $Name<T> {
            fn as_ref(&self) -> &str {
                self.0.as_ref()
            }
        }

        // The `PathBuf: AsRef<Path>` analog: lets APIs take
        // `impl AsRef<Name<str>>` and accept any storage. With `T = str` this
        // is also the reflexive `Name<str>: AsRef<Name<str>>` such bounds
        // need (which `std` writes by hand for `Path`). Unlike `Deref`, this
        // requires only `T: AsRef<str>`, not `T: Deref<Target = str>`.
        impl<T: ?Sized + AsRef<str>> ::core::convert::AsRef<$Name<str>> for $Name<T> {
            fn as_ref(&self) -> &$Name<str> {
                $Name::from_ref(self.0.as_ref())
            }
        }

        impl<T: ?Sized + AsRef<str>> ::core::fmt::Display for $Name<T> {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                ::core::fmt::Display::fmt(self.0.as_ref(), f)
            }
        }

        // ── Comparisons: uniform across storages ──
        //
        // Any two storages of the same kind compare by string content, so a
        // `$Name<Arc<str>>` equals the `$Name<String>` it was converted from.
        // `Hash` matches, which also upholds the `Borrow` contract below.

        impl<A: ?Sized + AsRef<str>, B: ?Sized + AsRef<str>>
            ::core::cmp::PartialEq<$Name<B>> for $Name<A>
        {
            fn eq(&self, other: &$Name<B>) -> bool {
                self.0.as_ref() == other.0.as_ref()
            }
        }

        impl<T: ?Sized + AsRef<str>> ::core::cmp::Eq for $Name<T> {}

        impl<A: ?Sized + AsRef<str>, B: ?Sized + AsRef<str>>
            ::core::cmp::PartialOrd<$Name<B>> for $Name<A>
        {
            fn partial_cmp(&self, other: &$Name<B>) -> ::core::option::Option<::core::cmp::Ordering> {
                self.0.as_ref().partial_cmp(other.0.as_ref())
            }
        }

        impl<T: ?Sized + AsRef<str>> ::core::cmp::Ord for $Name<T> {
            fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
                self.0.as_ref().cmp(other.0.as_ref())
            }
        }

        impl<T: ?Sized + AsRef<str>> ::core::hash::Hash for $Name<T> {
            fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
                self.0.as_ref().hash(state)
            }
        }

        impl<T: AsRef<str> + for<'a> ::core::convert::From<&'a str>> ::core::str::FromStr
            for $Name<T>
        {
            type Err = ::core::convert::Infallible;
            fn from_str(s: &str) -> ::core::result::Result<Self, Self::Err> {
                ::core::result::Result::Ok(Self(T::from(s)))
            }
        }

        // ── The `String`/`str` pattern ──

        impl<T: ?Sized + AsRef<str> + ::core::ops::Deref<Target = str>> ::core::ops::Deref
            for $Name<T>
        {
            type Target = $Name<str>;
            fn deref(&self) -> &$Name<str> {
                $Name::from_ref(self.0.as_ref())
            }
        }

        impl<T: AsRef<str> + ::core::ops::Deref<Target = str>>
            ::core::borrow::Borrow<$Name<str>> for $Name<T>
        {
            fn borrow(&self) -> &$Name<str> {
                self
            }
        }

        // `alloc`-backed impls (`ToOwned`, `From<&str>`), if feature is enabled.
        $crate::__strkind_alloc! { $Name }

        // Serde impls, if feature is enabled.
        $crate::__strkind_serde! { $Name }

        // Verus verification boundary, if feature is enabled.
        $crate::__strkind_verus! { $vis $Name }

        $crate::strkind! { $($rest)* }
    };
}

/// The struct definition for a kind. With strkind's `alloc` feature the
/// storage parameter defaults to `String`; without it there is no default
/// (macros cannot expand in default-type-parameter position, hence the
/// duplicated definition). Not a public API.
///
/// The feature is resolved when _strkind_ is compiled (the two definitions
/// below are `cfg`-gated), so downstream expansions of [`strkind!`] follow
/// strkind's feature rather than the downstream crate's.
#[cfg(feature = "alloc")]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_struct {
    ( $(#[$meta:meta])* $vis:vis $Name:ident ) => {
        $(#[$meta])*
        #[derive(Debug, Clone)]
        #[repr(transparent)]
        $vis struct $Name<T: ?Sized + AsRef<str> = $crate::__private::String>(T);
    };
}

#[cfg(not(feature = "alloc"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_struct {
    ( $(#[$meta:meta])* $vis:vis $Name:ident ) => {
        $(#[$meta])*
        #[derive(Debug, Clone)]
        #[repr(transparent)]
        $vis struct $Name<T: ?Sized + AsRef<str>>(T);
    };
}

/// `alloc`-backed impls for a generated kind - expands to empty without the
/// `alloc` feature. Not a public API.
///
/// Paths go through `$crate::__private` because `::alloc` is not in the
/// extern prelude of downstream crates, and calls are fully qualified because
/// the `no_std` prelude does not include `ToOwned`.
///
/// The feature is resolved when _strkind_ is compiled (the two definitions
/// below are `cfg`-gated), so downstream expansions of [`strkind!`] follow
/// strkind's feature rather than the downstream crate's.
#[cfg(feature = "alloc")]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_alloc {
    ( $Name:ident ) => {
        impl $crate::__private::ToOwned for $Name<str> {
            type Owned = $Name<$crate::__private::String>;
            fn to_owned(&self) -> Self::Owned {
                $Name($crate::__private::ToOwned::to_owned(&self.0))
            }
        }

        // The `From` impls are pinned to the `String` storage, NOT generic
        // over `T: From<&str>` storages, deliberately: a generic impl would
        // break every unannotated `Name::from("..")` call site, because `T`
        // becomes an unconstrained inference variable - type-parameter
        // defaults do not participate in expression inference (the
        // never-stabilized `default_type_parameter_fallback`). Construction
        // with other storages goes through `new` or the (storage-generic)
        // `FromStr`.
        impl ::core::convert::From<&str> for $Name<$crate::__private::String> {
            fn from(s: &str) -> Self {
                Self($crate::__private::ToOwned::to_owned(s))
            }
        }

        impl ::core::convert::From<$crate::__private::String> for $Name<$crate::__private::String> {
            fn from(s: $crate::__private::String) -> Self {
                Self(s)
            }
        }
    };
}

#[cfg(not(feature = "alloc"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_alloc {
    ( $Name:ident ) => {};
}

/// Serde impls for a generated kind - expands to empty without the `serde`
/// feature. Not a public API.
///
/// Impl is equivalent to `#[serde(transparent)]` but without requiring `serde`'s
/// `derive` feature.
///
/// The feature is resolved when _strkind_ is compiled (the two definitions
/// below are `cfg`-gated), so downstream expansions of [`strkind!`] follow
/// strkind's feature rather than the downstream crate's.
#[cfg(feature = "serde")]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_serde {
    ( $Name:ident ) => {
        impl<T: ?Sized + AsRef<str> + $crate::__private::serde::Serialize>
            $crate::__private::serde::Serialize for $Name<T>
        {
            fn serialize<S: $crate::__private::serde::Serializer>(
                &self,
                serializer: S,
            ) -> ::core::result::Result<S::Ok, S::Error> {
                self.0.serialize(serializer)
            }
        }

        impl<'de, T: AsRef<str> + $crate::__private::serde::Deserialize<'de>>
            $crate::__private::serde::Deserialize<'de> for $Name<T>
        {
            fn deserialize<D: $crate::__private::serde::Deserializer<'de>>(
                deserializer: D,
            ) -> ::core::result::Result<Self, D::Error> {
                T::deserialize(deserializer).map(Self)
            }
        }
    };
}
/// Empty without `serde` feature.
#[cfg(not(feature = "serde"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_serde {
    ( $Name:ident ) => {};
}

/// Verus verification boundary for a generated kind - expands to empty
/// without the `verus` feature. Not a public API.
///
/// Emits, inside `#[cfg(verus_keep_ghost)]` (set only by the Verus driver, so
/// plain-cargo consumers compile none of this; the referenced vstd is
/// strkind's own feature-gated dependency, via `$crate::__private`):
///
/// 1. an opaque external-type proxy (`external_type_specification`), so Verus
///    accepts specifications for the kind;
/// 2. an uninterpreted `View` (`Seq<char>`, vstd's `str`/`String` view type)
///    for every storage;
/// 3. an uninterpreted "storage obeys the str model" predicate - true when
///    the storage's `AsRef<str>` impl is *pure* (deterministic, no observable
///    interior mutability) - granted by trusted axiom for `str` (and `String`,
///    via [`__strkind_verus_alloc!`]);
/// 4. one `assume_specification` for `as_str`, conditioned on that predicate:
///    `Name::<T>::storage_obeys_str_model() ==> s@ == id@`.
///
/// This mirrors vstd's own pattern for user-implementable traits (e.g.
/// `obeys_key_model` in `vstd::std_specs::hash`): the axiom gives no
/// postcondition for storages whose `AsRef<str>` could be impure, so a wrong
/// or stateful impl cannot prove `false`. Consumers using other known-pure
/// storages (`Arc<str>`, `SmolStr`, ...) can grant the predicate for them
/// with their own one-line axiom.
///
/// Deliberately **no view-injectivity axiom** (`a@ == b@ ==> a == b`): vstd
/// has none for `String` either. Write specs over views, not values.
///
/// The proxy lives inside an anonymous `const _` block, so its fixed name
/// (`Ex`) and the lint `allow`s stay scoped while the specification still
/// applies crate-wide. The `impl`s, axioms, and `assume_specification` must
/// instead be emitted at the expansion site: Verus's impl paths ignore the
/// anonymous `const` scopes, so same-shaped impls from different kinds would
/// collide ("duplicate specification for this trait implementation").
///
/// The feature is resolved when _strkind_ is compiled (the two definitions
/// below are `cfg`-gated), so downstream expansions of [`strkind!`] follow
/// strkind's feature rather than the downstream crate's.
///
/// `verus_keep_ghost`, by contrast, must be resolved in the *invoking* crate
/// (hence the emitted `#[cfg]`s): in a verified build, crates without
/// `[package.metadata.verus]` are compiled without it, as plain Rust, even
/// though strkind and vstd are compiled with it, and `verus!` erases ghost
/// code according to the invoking crate's cfg. A consequence: a `cfg` emitted
/// by a macro is checked against the invoking crate's declared cfgs, and the
/// module-scope blocks below cannot carry an `allow(unexpected_cfgs)` (an
/// `allow` on the `cfg`'d item itself does not suppress the lint, and a
/// `const` wrapper would break Verus impl paths). So every crate expanding
/// [`strkind!`] with the `verus` feature must declare
/// `check-cfg = ["cfg(verus_keep_ghost)"]` (documented in the README). The
/// `const`-scoped blocks still `allow` it, which is harmless.
#[cfg(feature = "verus")]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_verus {
    ( $vis:vis $Name:ident ) => {
        // `allow` rather than `expect`: the lints fire only in some
        // configurations (`expect` would be unfulfilled in the others), and
        // `clippy::allow_attributes` must therefore be allowed alongside.
        #[allow(
            clippy::allow_attributes,
            unexpected_cfgs,
            reason = "`verus_keep_ghost` is set by the Verus driver"
        )]
        const _: () = {
            #[cfg(verus_keep_ghost)]
            $crate::__private::vstd::prelude::verus! {
                #[verifier::external_type_specification]
                #[verifier::external_body]
                #[verifier::reject_recursive_types(T)]
                pub struct Ex<T: ?Sized + AsRef<str>>($Name<T>);
            }
        };

        #[cfg(verus_keep_ghost)]
        $crate::__private::vstd::prelude::verus! {
            impl<T: ?Sized + AsRef<str>> $crate::__private::vstd::view::View for $Name<T> {
                type V = $crate::__private::vstd::seq::Seq<char>;

                uninterp spec fn view(&self) -> $crate::__private::vstd::seq::Seq<char>;
            }

            impl<T: ?Sized + AsRef<str>> $Name<T> {
                /// Trusted marker: the storage's `AsRef<str>` impl is
                /// *pure* (deterministic, no observable interior
                /// mutability). Uninterpreted; granted by axiom for
                /// `str` and `String`. Grant it for other known-pure
                /// storages with your own axiom.
                $vis uninterp spec fn storage_obeys_str_model() -> bool;
            }

            impl $Name<str> {
                /// Axiom (trusted): `str`'s identity `AsRef` is pure.
                $vis broadcast axiom fn axiom_str_storage_obeys_str_model()
                    ensures #[trigger] Self::storage_obeys_str_model();
            }
        }

        // In its own anonymous `const` block so the scoped `allow` covers the
        // unsafe-marked items the axiom expands to (module scope would trip
        // consumers' `unsafe_code` lint: under the Verus driver the items are
        // not attributed to an external macro).
        #[allow(
            clippy::allow_attributes,
            unexpected_cfgs,
            unsafe_code,
            reason = "`verus_keep_ghost` is set by the Verus driver, and the trusted `assume_specification` axiom expands to unsafe-marked items"
        )]
        const _: () = {
            #[cfg(verus_keep_ghost)]
            $crate::__private::vstd::prelude::verus! {
                $vis assume_specification<T: ?Sized + AsRef<str>>[ $Name::<T>::as_str ](id: &$Name<T>) -> (s: &str)
                    ensures $Name::<T>::storage_obeys_str_model() ==> s@ == id@;
            }
        };

        $crate::__strkind_verus_alloc! { $vis $Name }
    };
}

#[cfg(not(feature = "verus"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_verus {
    ( $vis:vis $Name:ident ) => {};
}

/// The `String`-storage axiom of the Verus boundary - expands to empty unless
/// both the `verus` and `alloc` features are enabled (the `String` default
/// storage only exists with `alloc`). See [`__strkind_verus!`]. Not a public
/// API.
#[cfg(all(feature = "verus", feature = "alloc"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_verus_alloc {
    ( $vis:vis $Name:ident ) => {
        #[cfg(verus_keep_ghost)]
        $crate::__private::vstd::prelude::verus! {
            impl $Name<$crate::__private::String> {
                /// Axiom (trusted): `String`'s `AsRef<str>` is pure.
                $vis broadcast axiom fn axiom_string_storage_obeys_str_model()
                    ensures #[trigger] Self::storage_obeys_str_model();
            }
        }
    };
}

#[cfg(not(all(feature = "verus", feature = "alloc")))]
#[doc(hidden)]
#[macro_export]
macro_rules! __strkind_verus_alloc {
    ( $vis:vis $Name:ident ) => {};
}

/// Example expansion of the [`strkind!`] macro, as rendered documentation.
///
/// Gated behind the internal `_example` feature (enabled when building the
/// docs); it is **not** part of the crate's API - do not use it.
#[cfg(feature = "_example")]
#[cfg_attr(docsrs, doc(cfg(feature = "_example")))]
pub mod example {
    strkind! {
        /// An example kind, showing everything [`strkind!`](crate::strkind)
        /// generates for the declaration `pub ExampleId;`.
        pub ExampleId;
    }
}

/// Tests that require no strkind features: the core-only surface.
#[cfg(test)]
mod core_tests {
    strkind! {
        /// Usable without `alloc`: no `String` default, but explicit storages
        /// and the borrowed `&CoreId<str>` form work.
        pub(crate) CoreId;
    }

    #[test]
    fn core_only_surface() {
        const A: &CoreId<str> = CoreId::from_ref("a");
        assert_eq!(A.as_str(), "a");

        let b: CoreId<&str> = CoreId::new("a");
        assert_eq!(A, &b); // cross-storage comparison
        assert!(A <= &b);

        let c: CoreId<&str> = b.clone().convert();
        assert_eq!(c.into_inner(), "a");

        // `AsRef<CoreId<str>>` works without `alloc`, for any storage and
        // reflexively for the borrowed form.
        fn takes_kinded(id: &(impl ?Sized + AsRef<CoreId<str>>)) -> &str {
            id.as_ref().as_str()
        }
        assert_eq!(takes_kinded(&b), "a");
        assert_eq!(takes_kinded(A), "a");
    }

    /// Compile-time regression test: `new` and `from_ref` must
    /// stay callable in const context. `clippy::missing_const_for_fn` cannot
    /// enforce this (clippy skips macro-expanded code, and every method here
    /// is generated by `strkind!`), so this `const` block stands in for it.
    const _CONST_METHODS: () = {
        let _id: CoreId<&str> = CoreId::new("a");
        let _borrowed: &CoreId<str> = CoreId::from_ref("a");
    };
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
    use std::collections::{BTreeMap, HashMap};
    use std::format;
    use std::prelude::rust_2024::*;
    use std::sync::Arc;

    use smol_str::SmolStr;

    strkind! {
        /// A kind for tests.
        pub(crate) ThreadId;

        /// Another kind for tests.
        pub(crate) RawTag;
    }

    // A second macro invocation must still produce distinct types.
    strkind! {
        pub(crate) OtherId;
    }

    #[test]
    fn new_wraps_and_unwraps() {
        let id = ThreadId::new("thread-7".to_owned());
        assert_eq!(id.as_str(), "thread-7");
        assert_eq!(id.to_string(), "thread-7");
        assert_eq!(id.into_inner(), "thread-7");
    }

    #[test]
    fn from_and_from_str() {
        let id = ThreadId::from("thread-7");
        assert_eq!(id.as_str(), "thread-7");

        // `From<String>`, so an owned string doesn't force `new` (and
        // `.map(ThreadId::from)` etc. work).
        let from_owned = ThreadId::from("thread-7".to_owned());
        assert_eq!(from_owned, id);

        let parsed: ThreadId = "thread-7".parse().expect("infallible");
        assert_eq!(parsed, id);

        // `FromStr` is generic over any storage constructible `From<&str>`.
        let small: ThreadId<SmolStr> = "thread-7".parse().expect("infallible");
        let shared: ThreadId<Arc<str>> = "thread-7".parse().expect("infallible");
        assert_eq!(small, id);
        assert_eq!(shared, id);
    }

    #[test]
    fn from_ref_is_const_and_zero_copy() {
        const ID: &ThreadId<str> = ThreadId::from_ref("thread-7");
        assert_eq!(ID.as_str(), "thread-7");
        assert_eq!(ID, &ThreadId::from("thread-7"));
    }

    #[test]
    fn deref_gives_borrowed_form() {
        fn takes_borrowed(id: &ThreadId<str>) -> &str {
            id.as_str()
        }
        let owned = ThreadId::from("thread-7");
        assert_eq!(takes_borrowed(&owned), "thread-7");
    }

    #[test]
    fn as_ref_kinded_bound() {
        fn takes_any_storage(id: impl AsRef<ThreadId<str>>) -> String {
            id.as_ref().as_str().to_owned()
        }

        let owned = ThreadId::from("thread-7");
        let shared: ThreadId<Arc<str>> = owned.clone().convert();
        let borrowed: &ThreadId<str> = ThreadId::from_ref("thread-7");

        assert_eq!(takes_any_storage(&owned), "thread-7");
        assert_eq!(takes_any_storage(owned), "thread-7");
        assert_eq!(takes_any_storage(shared), "thread-7");
        assert_eq!(takes_any_storage(borrowed), "thread-7"); // reflexive, via `&T` forwarding
    }

    #[test]
    fn as_ref_str_still_available() {
        fn takes_stringish(s: impl AsRef<str>) -> String {
            s.as_ref().to_owned()
        }
        assert_eq!(takes_stringish(ThreadId::from("thread-7")), "thread-7");
        let id = ThreadId::from("thread-7");
        let s: &str = id.as_ref(); // annotated target disambiguates
        assert_eq!(s, "thread-7");
    }

    #[test]
    fn to_owned_round_trips() {
        let borrowed: &ThreadId<str> = ThreadId::from_ref("thread-7");
        let owned: ThreadId = borrowed.to_owned();
        assert_eq!(owned, *borrowed);
    }

    #[test]
    fn map_lookup_by_borrowed_form() {
        let mut hash_map: HashMap<ThreadId, u32> = HashMap::new();
        hash_map.insert(ThreadId::from("a"), 1);
        assert_eq!(hash_map.get(ThreadId::from_ref("a")), Some(&1));
        assert_eq!(hash_map.get(ThreadId::from_ref("b")), None);

        let mut btree_map: BTreeMap<ThreadId, u32> = BTreeMap::new();
        btree_map.insert(ThreadId::from("a"), 1);
        assert_eq!(btree_map.get(ThreadId::from_ref("a")), Some(&1));
    }

    #[test]
    fn alternate_storages_interoperate() {
        let owned = ThreadId::from("thread-7");
        let shared: ThreadId<Arc<str>> = owned.clone().convert();
        let small: ThreadId<SmolStr> = ThreadId::new(SmolStr::new("thread-7"));

        // Cross-storage comparisons.
        assert_eq!(shared, owned);
        assert_eq!(small, owned);
        assert_eq!(shared, small);

        // Cross-storage map lookup via the borrowed form (`Borrow` + `Hash`
        // are uniform across storages).
        let mut map: HashMap<ThreadId<Arc<str>>, u32> = HashMap::new();
        map.insert(shared, 1);
        assert_eq!(map.get(ThreadId::from_ref("thread-7")), Some(&1));
    }

    #[test]
    fn kinds_are_distinct_types() {
        // `ThreadId` and `OtherId` must not unify.
        // (Compile-time property; this test documents it.)
        fn takes_thread_id(id: &ThreadId<str>) -> &str {
            id.as_str()
        }
        let other = OtherId::new("x".to_owned());
        // takes_thread_id(&other); // must not compile
        let thread = ThreadId::from("x");
        assert_eq!(takes_thread_id(&thread), other.as_str());
        assert_eq!(other.convert::<Box<str>>().into_inner().as_ref(), "x");

        // Second kind in the same macro invocation works identically.
        let tag = RawTag::new("x".to_owned());
        assert_eq!(tag.as_str(), "x");
        assert_eq!(tag.convert::<Arc<str>>().into_inner().as_ref(), "x");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trip_is_transparent() {
        let id = ThreadId::from("thread-7");
        let json = serde_json::to_string(&id).expect("serialize");
        assert_eq!(json, r#""thread-7""#, "serializes as a plain string");
        let back: ThreadId = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, id);

        // Borrowed form serializes identically.
        let borrowed_json =
            serde_json::to_string(ThreadId::from_ref("thread-7")).expect("serialize");
        assert_eq!(borrowed_json, json);

        // Alternate storage deserializes too.
        let small: ThreadId<SmolStr> = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(small, id);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_map_keys() {
        let mut map: HashMap<ThreadId, u32> = HashMap::new();
        map.insert(ThreadId::from("a"), 1);
        let json = serde_json::to_string(&map).expect("serialize");
        assert_eq!(json, r#"{"a":1}"#);
        let back: HashMap<ThreadId, u32> = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, map);
    }

    #[test]
    fn debug_names_the_kind() {
        assert_eq!(format!("{:?}", ThreadId::from("a")), r#"ThreadId("a")"#);
    }

    #[test]
    fn ordering_is_by_content() {
        let mut ids = [
            ThreadId::from("b"),
            ThreadId::from("a"),
            ThreadId::from("c"),
        ];
        ids.sort();
        let sorted: Vec<&str> = ids.iter().map(|i| i.as_str()).collect();
        assert_eq!(sorted, ["a", "b", "c"]);
        assert!(ThreadId::from("a") < ThreadId::from("b"));
    }
}