numbered 0.4.0

Derive stable integer numbers for enum variants.
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
//! Compile-time integer numbers for enum variants.
//!
//! This crate gives each variant a stable integer: a `u8` (or another chosen
//! repr) assigned at compile time. Runtime conversion is a `match` on a
//! literal. [`Number::number`] and [`FromNumber::from_number`] are not
//! `const` (trait methods cannot be). In const context, use
//! [`Variants::NUMBERS`].
//!
//! Downstream crates use this to drop handwritten `from_u8` / `as_u8` matches
//! on status codes, wire tags, and similar closed integer sets.
//!
//! Numbers are **trait items** in this crate, not inherent methods on `E`.
//! Import [`Number`] / [`FromNumber`] to call them, or use UFCS
//! (`<E as Number>::number(&e)`). A user `fn number()` still compiles.
//!
//! # Quick start
//!
//! ```
//! use numbered::{FromNumber, Number, Numbered, Variants};
//!
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
//! #[numbered(u8)]
//! enum Kind {
//!     Process,                 // 0
//!     File,                    // 1
//!     #[numbered(n = 10)]
//!     Network,                 // 10
//!     Socket,                  // 11  (continues after last explicit)
//! }
//!
//! assert_eq!(Kind::Process.number(), 0u8);
//! assert_eq!(Kind::File.as_u8(), 1);
//! assert_eq!(Kind::from_number(10).unwrap(), Kind::Network);
//! assert_eq!(Kind::try_from(11u8), Ok(Kind::Socket));
//! assert!(Kind::Process == 0u8);
//! assert_eq!(Kind::VARIANTS.len(), 4);
//! assert_eq!(Kind::NUMBERS, &[0, 1, 10, 11]);
//! ```
//!
//! Native Rust discriminants (`Process = 1`) are treated as
//! `#[numbered(n = 1)]`. If both are present they must agree.
//! A variant named `Error` is fine: generated `TryFrom` names
//! [`FromNumberError`] instead of `Self::Error`.
//!
//! # Attributes
//!
//! **Container** (required): `#[numbered(<repr>, ...)]`
//!
//! - A repr type: `u8`, `u16`, `u32`, `u64`, `usize`, `i8`, `i16`, `i32`,
//!   `i64`, or `isize`. First positional, or `repr = u8`.
//! - `start = 1`: first auto-assigned number when no discriminant / `n` is
//!   set (default `0`).
//! - `crate = ::other::numbered`: path used in generated code when this crate
//!   is re-exported under another name.
//!
//! **Variant** (optional): `#[numbered(n = 5)]`
//!
//! Pins that variant to an explicit integer. A native `= 5` discriminant
//! does the same. Gaps are allowed. After an explicit number, the next auto
//! variant is `last + 1`.
//!
//! ```
//! use numbered::{FromNumber, Number, Numbered};
//!
//! #[derive(Debug, PartialEq, Numbered)]
//! #[numbered(u8, start = 1)]
//! enum Wire {
//!     Open,                    // 1
//!     #[numbered(n = 10)]
//!     IoFailed,                // 10
//!     Closed = 20,             // 20
//!     Draining,                // 21
//! }
//!
//! assert_eq!(Wire::Open.number(), 1);
//! assert_eq!(Wire::IoFailed.as_u8(), 10);
//! assert_eq!(Wire::from_number(21).unwrap(), Wire::Draining);
//! ```
//!
//! Fielded variants keep [`Number`] and the [`Variants`] tables. Pair with
//! cognomen `reason = "... {field}"` on the same enum; a number cannot
//! rebuild the payload, so [`FromNumber`] is omitted.
//!
//! ```
//! use numbered::{Number, Numbered, Variants};
//!
//! #[derive(Debug, Clone, PartialEq, Numbered)]
//! #[numbered(u8, start = 1)]
//! enum HostError {
//!     Unsupported { capability: &'static str },
//!     OpenFailed { cause: &'static str },
//! }
//!
//! let e = HostError::OpenFailed { cause: "busy" };
//! assert_eq!(e.number(), 2);
//! assert_eq!(HostError::NUMBERS, &[1, 2]);
//! assert_eq!(HostError::VARIANTS.len(), 2);
//! assert_eq!(HostError::COUNT, 2);
//! ```
//!
//! Violations (non-enum, empty enum, missing repr, duplicate keys, unknown
//! keys, collisions, overflow, disagreeing discriminant) are compile errors.
//!
//! # Generated API
//!
//! For `#[numbered(u8)]` on `E`. Nothing is inherent on `E`.
//!
//! - [`Number`]: `number()` / `as_u8()` (`as_*` follows the repr). Takes
//!   `&self` so fielded variants do not need `Copy`. Not `const`
//! - [`FromNumber`]: `from_number` / `from_u8` ->
//!   `Result<Self, FromNumberError<u8>>` (fieldless enums; a number cannot
//!   rebuild a payload). Not `const`
//! - [`Variants`] (non-generic enums): `E::VARIANTS`, `E::NUMBERS`, and
//!   `E::COUNT` after `use numbered::Variants`. Trait items, so they cannot
//!   clash with cognomen or a user `const VARIANTS`. Fielded enums keep
//!   `NUMBERS` / `COUNT`; `VARIANTS` is `&[()]` of that length. Const use
//!   goes through `NUMBERS`
//! - No `Display` impl. Print the number with `e.number()`.
//! - `From<E> for u8`, `TryFrom<u8> for E` (`TryFrom` is fieldless only)
//! - `PartialEq<u8>` / `PartialEq<E>` both ways
//! - `Serialize` / `Deserialize` (feature `serde`): the number, not a string.
//!   `Deserialize` is fieldless only. Do not enable serde on both Numbered
//!   and Cognomen for the same type (two `Serialize` impls)
//!
//! # Features
//!
//! | Feature | Default | Unlocks |
//! |---------|---------|---------|
//! | `std` | yes | `alloc` + [`std::error::Error`] for [`FromNumberError`] |
//! | `alloc` | via `std` | kept for feature parity; the unmatched number is always stored |
//! | `serde` | no | `Serialize` / `Deserialize` |
//!
//! # `no_std`
//!
//! ```toml
//! numbered = { version = "0.2", default-features = false }
//! ```
//!
//! [`Number`], [`FromNumber`], `From` / `TryFrom`, and [`Variants`] use only
//! `core`. Add `features = ["serde"]` for wire formats.
//!
//! # MSRV
//!
//! Rust 1.71.1.

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate self as numbered;

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

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

mod number;

pub use number::{FromNumber, Number};
#[doc(inline)]
pub use numbered_macros::Numbered;

/// Declaration-order tables for a non-generic numbered enum.
///
/// `VARIANTS`, `NUMBERS`, and `COUNT` live on this trait, not as inherent
/// items on `E`. Cognomen's `Variants` is a different trait; import one
/// or spell the path: `<E as numbered::Variants>::NUMBERS`.
///
/// Fieldless enums store `Self` in [`VARIANTS`]. Fielded enums cannot
/// build a `'static [Self]`, so [`Variant`](Self::Variant) is `()` and
/// `VARIANTS.len()` / [`COUNT`](Self::COUNT) still match the declaration.
///
/// [`NUMBERS`](Self::NUMBERS) is the const-context path:
/// [`Number::number`] cannot be `const`.
///
/// ```
/// use numbered::{Numbered, Variants};
///
/// #[derive(Debug, Clone, Copy, PartialEq, Numbered)]
/// #[numbered(u8)]
/// enum Kind {
///     A,
///     B,
/// }
///
/// assert_eq!(Kind::VARIANTS, &[Kind::A, Kind::B]);
/// assert_eq!(Kind::NUMBERS, &[0, 1]);
/// assert_eq!(Kind::COUNT, 2);
/// ```
pub trait Variants: Sized + 'static {
    /// Integer type chosen in `#[numbered(<repr>)]`.
    type Repr: Copy;

    /// Element type of [`VARIANTS`].
    ///
    /// `Self` when every variant is fieldless; `()` when any variant has
    /// a payload (`VARIANTS` is then a length-only table).
    type Variant: 'static;

    /// All variants in declaration order, or `()` placeholders if fielded.
    const VARIANTS: &'static [Self::Variant];

    /// Assigned number for each variant in declaration order.
    const NUMBERS: &'static [Self::Repr];

    /// How many variants were declared (`NUMBERS.len()`).
    const COUNT: usize = Self::NUMBERS.len();
}

/// Error returned when a number matches no declared variant.
///
/// Produced by [`TryFrom`](core::convert::TryFrom) and
/// [`FromNumber::from_number`]. The unmatched number is stored in
/// [`Self::number`]. With `std`, this implements [`std::error::Error`].
///
/// ```
/// use numbered::{FromNumber, FromNumberError, Numbered};
///
/// #[derive(Debug, Numbered)]
/// #[numbered(u8)]
/// enum Mode {
///     SingleProcess,
/// }
///
/// let err = Mode::from_number(9).unwrap_err();
/// assert_eq!(err.number, 9);
/// assert!(err.to_string().contains("9"));
/// let _: FromNumberError<u8> = err;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FromNumberError<T> {
    /// The number that did not match.
    pub number: T,
}

impl<T> FromNumberError<T> {
    /// Build an error for the unmatched `number`.
    #[must_use]
    pub const fn new(number: T) -> Self {
        Self { number }
    }
}

impl<T: core::fmt::Display> core::fmt::Display for FromNumberError<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "no numbered variant has number {}", self.number)
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<T: core::fmt::Debug + core::fmt::Display> std::error::Error for FromNumberError<T> {}

#[cfg(feature = "serde")]
#[doc(hidden)]
pub use serde as __serde;

#[cfg(test)]
mod tests {
    extern crate std;

    use std::string::ToString;

    use super::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u8)]
    enum Kind {
        Process,
        File,
        #[numbered(n = 10)]
        Network,
        Socket,
    }

    #[test]
    fn numbers_and_tables() {
        assert_eq!(Kind::Process.number(), 0u8);
        assert_eq!(Kind::File.as_u8(), 1);
        assert_eq!(Kind::from_number(10).unwrap(), Kind::Network);
        assert_eq!(Kind::try_from(11u8), Ok(Kind::Socket));
        assert!(Kind::Process == 0u8);
        assert!(0u8 == Kind::Process);
        assert_eq!(
            Kind::VARIANTS,
            &[Kind::Process, Kind::File, Kind::Network, Kind::Socket]
        );
        assert_eq!(Kind::NUMBERS, &[0, 1, 10, 11]);
        assert_eq!(Kind::COUNT, 4);
        assert_eq!(Kind::Process.number().to_string(), "0");
        assert_eq!(u8::from(Kind::File), 1);
        assert_eq!(Kind::from_u8(11).unwrap(), Kind::Socket);
    }

    #[derive(Debug, Clone, PartialEq, Eq, Numbered)]
    #[numbered(u8, start = 1)]
    enum HostError {
        Unsupported { capability: &'static str },
        OpenFailed { cause: &'static str },
        BadRequest { why: &'static str },
        Io { status: &'static str },
    }

    #[test]
    fn fielded_numbers_and_tables() {
        let e = HostError::OpenFailed { cause: "busy" };
        assert_eq!(e.number(), 2);
        assert_eq!(e.as_u8(), 2);
        assert_eq!(u8::from(e.clone()), 2);
        assert!(e == 2u8);
        assert!(2u8 == e);
        assert_eq!(<HostError as Variants>::NUMBERS, &[1, 2, 3, 4]);
        assert_eq!(<HostError as Variants>::VARIANTS.len(), 4);
        assert_eq!(HostError::COUNT, 4);
        assert_eq!(HostError::COUNT, HostError::VARIANTS.len());
        assert_eq!(HostError::Unsupported { capability: "x" }.number(), 1);
        assert_eq!(
            HostError::BadRequest {
                why: "device name has interior NUL"
            }
            .number(),
            3
        );
        assert_eq!(HostError::Io { status: "e" }.number(), 4);
    }

    #[test]
    fn parse() {
        assert_eq!(Kind::from_u8(10).unwrap(), Kind::Network);
        assert!(Kind::from_number(99).is_err());
        let err = Kind::from_number(99).unwrap_err();
        assert_eq!(err.number, 99);
        assert!(err.to_string().contains("99"));
        #[cfg(feature = "std")]
        {
            let _: &dyn std::error::Error = &err;
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(i8, start = -1)]
    enum Signed {
        Neg,
        Zero,
        Pos = 5,
        Next,
    }

    #[test]
    fn signed_start_and_discriminant() {
        assert_eq!(Signed::Neg.number(), -1);
        assert_eq!(Signed::Zero.as_i8(), 0);
        assert_eq!(Signed::Pos.number(), 5);
        assert_eq!(Signed::Next.number(), 6);
        assert_eq!(Signed::from_number(-1).unwrap(), Signed::Neg);
        assert_eq!(Signed::NUMBERS, &[-1, 0, 5, 6]);
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u8)]
    enum Shared {
        A,
        B,
    }

    impl core::fmt::Display for Shared {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str("user")
        }
    }

    impl Shared {
        pub const VARIANTS: &'static [&'static str] = &["a", "b"];

        fn number(&self) -> u8 {
            9
        }

        fn as_u8(&self) -> u8 {
            8
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u8, start = 1)]
    enum Level {
        Error,
        Warn,
        Info,
        Debug,
    }

    #[test]
    fn error_variant_try_from() {
        assert_eq!(Level::Error.number(), 1);
        assert_eq!(Level::try_from(1u8), Ok(Level::Error));
        assert_eq!(Level::from_number(4).unwrap(), Level::Debug);
        assert!(Level::from_number(0).is_err());
        assert_eq!(Level::Error.number(), 1);
    }

    #[test]
    fn tables_do_not_clash_with_user_items() {
        assert_eq!(Shared::VARIANTS, &["a", "b"]);
        assert_eq!(<Shared as Variants>::VARIANTS, &[Shared::A, Shared::B]);
        assert_eq!(<Shared as Variants>::NUMBERS, &[0, 1]);
        assert_eq!(Shared::A.to_string(), "user");
        assert_eq!(Shared::A.number(), 9);
        assert_eq!(Shared::A.as_u8(), 8);
        assert_eq!(<Shared as Number>::number(&Shared::A), 0);
        assert_eq!(<Shared as Number>::as_u8(&Shared::A), 0);
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(repr = u16, start = 1)]
    enum Port {
        Http,
        Https = 443,
        Alt,
    }

    #[test]
    fn repr_key_and_start() {
        assert_eq!(Port::Http.as_u16(), 1);
        assert_eq!(Port::Https.number(), 443);
        assert_eq!(Port::Alt.number(), 444);
        assert_eq!(u16::from(Port::Http), 1);
        assert_eq!(Port::try_from(443u16), Ok(Port::Https));
    }

    // Trait methods cannot be const. Const use goes through Variants::NUMBERS.
    const fn kind_number_in_const() -> u8 {
        Kind::NUMBERS[0]
    }

    #[test]
    fn works_in_const() {
        assert_eq!(kind_number_in_const(), 0);
        const TABLES: &[u8] = Kind::NUMBERS;
        assert_eq!(TABLES, &[0, 1, 10, 11]);
    }

    #[test]
    fn from_number_error_new() {
        let err = FromNumberError::new(7u8);
        assert_eq!(err.number, 7);
        assert_eq!(err, Kind::from_number(7).unwrap_err());
        assert_eq!(err.to_string(), "no numbered variant has number 7");
    }

    #[test]
    fn partial_eq_mismatch() {
        assert!(Kind::Process != 1u8);
        assert!(1u8 != Kind::Process);
        assert!(Kind::File != 99u8);
        assert!(Kind::Network == 10u8);
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u8)]
    enum Literals {
        Hex = 0x10,
        #[numbered(n = 0x20)]
        AlsoHex,
        Next,
        #[numbered(n = 5)]
        Agree = 5,
        Paren = (7),
    }

    #[test]
    fn hex_paren_and_agreeing_discriminant() {
        assert_eq!(Literals::Hex.number(), 16);
        assert_eq!(Literals::AlsoHex.number(), 32);
        assert_eq!(Literals::Next.number(), 33);
        assert_eq!(Literals::Agree.number(), 5);
        assert_eq!(Literals::Paren.number(), 7);
        assert_eq!(Literals::from_number(16).unwrap(), Literals::Hex);
        assert_eq!(Literals::NUMBERS, &[16, 32, 33, 5, 7]);
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(i8, start = -128)]
    enum I8Min {
        Lo,
        Next,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u32)]
    enum Wide {
        A,
        B = 1_000,
        C,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(usize)]
    enum UsizeKind {
        A,
        B,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(isize)]
    enum IsizeKind {
        A = -1,
        B,
    }

    #[test]
    fn other_reprs() {
        assert_eq!(I8Min::Lo.as_i8(), -128);
        assert_eq!(I8Min::Next.number(), -127);
        assert_eq!(Wide::B.as_u32(), 1_000);
        assert_eq!(Wide::C.number(), 1_001);
        assert_eq!(UsizeKind::B.as_usize(), 1);
        assert_eq!(IsizeKind::A.as_isize(), -1);
        assert_eq!(IsizeKind::B.number(), 0);
        assert_eq!(u32::from(Wide::A), 0);
        assert_eq!(Wide::try_from(1_000u32), Ok(Wide::B));
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
    #[numbered(u8)]
    enum Generic<const N: usize> {
        A,
        B,
    }

    #[test]
    fn generic_has_numbers_not_tables() {
        assert_eq!(Generic::<3>::A.number(), 0);
        assert_eq!(Generic::<3>::from_number(1).unwrap(), Generic::<3>::B);
        assert_eq!(u8::from(Generic::<1>::A), 0);
    }

    impl Shared {
        pub const NUMBERS: &'static [&'static str] = &["zero", "one"];
    }

    #[test]
    fn user_numbers_do_not_hide_trait_numbers() {
        assert_eq!(Shared::NUMBERS, &["zero", "one"]);
        assert_eq!(<Shared as Variants>::NUMBERS, &[0, 1]);
    }

    #[test]
    fn signed_from_and_eq() {
        assert_eq!(i8::from(Signed::Neg), -1);
        assert_eq!(Signed::from_i8(5).unwrap(), Signed::Pos);
        assert!(Signed::Neg == -1i8);
        assert!(-1i8 == Signed::Neg);
        assert!(Signed::Pos != 0i8);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip() {
        let v = Kind::Network;
        let s = serde_json::to_string(&v).unwrap();
        assert_eq!(s, "10");
        let back: Kind = serde_json::from_str(&s).unwrap();
        assert_eq!(back, v);
        assert!(serde_json::from_str::<Kind>("99").is_err());
        let process: Kind = serde_json::from_str("0").unwrap();
        assert_eq!(process, Kind::Process);
        let generic = Generic::<3>::B;
        let gs = serde_json::to_string(&generic).unwrap();
        assert_eq!(gs, "1");
        let gback: Generic<3> = serde_json::from_str(&gs).unwrap();
        assert_eq!(gback, generic);
    }
}