const_bcd/lib.rs
1//! Binary-Coded Decimal (BCD) representation and conversion utilities.
2//!
3//! This crate provides [`Bcd<BYTES>`], a fixed-size, const-generic type for storing
4//! unsigned integers in packed BCD format. Each byte holds two decimal digits, one
5//! per nibble. The `BYTES` const parameter controls the storage size and therefore
6//! the maximum representable value.
7//!
8//! # BCD Format
9//!
10//! In packed BCD, the value `1234` is stored as `[0x12, 0x34]`. The high nibble of
11//! each byte holds the more-significant digit. Leading zero bytes are permitted and
12//! are transparent to formatting and arithmetic conversions.
13//!
14//! # Constructing a `Bcd`
15//!
16//! There are three ways to build a [`Bcd`]:
17//!
18//! - [`Bcd::from_bcd_bytes`] — from a raw byte array already in BCD format.
19//! - [`Bcd::try_from_u8`] and its `try_from_u16` / `try_from_u32` / `try_from_u64`
20//! / `try_from_u128` / `try_from_usize` counterparts — from a primitive integer
21//! via the double-dabble algorithm, returning [`BcdOverflowError`] on overflow.
22//! - The [`bcd!`] macro — a convenience wrapper that dispatches to the smallest
23//! primitive conversion capable of holding the value and panics on overflow.
24//!
25//! Conversion back to primitives uses the matching `try_into_*` methods. For the
26//! `Bcd<BYTES>` sizes that are guaranteed to fit in a target primitive, infallible
27//! `into_*` methods are also provided.
28//!
29//! # `const` support
30//!
31//! All construction and conversion methods are `const fn`, and the [`bcd!`] macro
32//! works in `const` context:
33//!
34//! ```rust
35//! use const_bcd::{Bcd, bcd};
36//!
37//! const N: Bcd<2> = bcd!(1234u16);
38//! ```
39//!
40//! # `no_std`
41//!
42//! This crate is `no_std` compatible. The `std` feature is enabled by default but
43//! has no functional effect — the crate uses only `core` internally. Disable it
44//! for `no_std` targets:
45//!
46//! ```toml
47//! [dependencies]
48//! const-bcd = { version = "0.1", default-features = false }
49//! ```
50//!
51//! The crate never allocates, regardless of feature flags.
52//!
53//! # Examples
54//!
55//! ```rust
56//! use const_bcd::{Bcd, bcd};
57//!
58//! // Construct from a primitive integer
59//! let n: Bcd<2> = Bcd::try_from_u16(1234).unwrap();
60//! assert_eq!(n.to_string(), "1234");
61//!
62//! // Construct directly from raw BCD bytes
63//! let n: Bcd<2> = Bcd::from_bcd_bytes([0x12, 0x34]).unwrap();
64//! assert_eq!(n.to_string(), "1234");
65//!
66//! // Convenience macro
67//! let n: Bcd<2> = bcd!(1234u16);
68//! assert_eq!(n.to_string(), "1234");
69//!
70//! // Convert back to a primitive
71//! let value: u16 = n.try_into_u16().unwrap();
72//! assert_eq!(value, 1234);
73//! ```
74
75#![cfg_attr(not(feature = "std"), no_std)]
76
77use core::{error::Error, fmt, str};
78
79const DIGIT_MAX: u8 = 9;
80
81/// A packed Binary-Coded Decimal (BCD) value backed by `BYTES` bytes.
82///
83/// Each byte encodes two decimal digits: the high nibble holds the more-significant
84/// digit and the low nibble holds the less-significant digit. For example, the decimal
85/// value `42` is stored as `0x42`.
86///
87/// # Zero-byte `Bcd<0>`
88///
89/// `Bcd<0>` is a valid, zero-sized type that stores no digits. `try_into_*` always
90/// yields `0`, and `try_from_*` accepts only `0` (any other value overflows). It
91/// exists so the const-generic bound stays uniform; in most use cases `BYTES >= 1`
92/// is expected.
93///
94/// # Examples
95///
96/// ```rust
97/// use const_bcd::Bcd;
98///
99/// let a: Bcd<2> = Bcd::try_from_u16(100).unwrap();
100/// let b: Bcd<2> = Bcd::try_from_u16(200).unwrap();
101/// assert!(a < b);
102/// ```
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
104pub struct Bcd<const BYTES: usize>([u8; BYTES]);
105
106/// Error returned when a byte contains a nibble with a value greater than 9.
107///
108/// BCD digits must be in the range `0..=9`. Any nibble value in `10..=15` (`0xA`–`0xF`)
109/// is invalid and will produce this error.
110///
111/// # Examples
112///
113/// ```rust
114/// use const_bcd::Bcd;
115///
116/// // 0xAB contains nibbles 0xA and 0xB, both invalid BCD digits
117/// let err = Bcd::<1>::from_bcd_bytes([0xAB]).unwrap_err();
118/// assert_eq!(err.to_string(), "Invalid BCD digit 10. Must be <= 9");
119/// ```
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct InvalidBcdDigit(u8);
122
123impl fmt::Display for InvalidBcdDigit {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 write!(f, "Invalid BCD digit {}. Must be <= {}", self.0, DIGIT_MAX)
126 }
127}
128
129impl Error for InvalidBcdDigit {}
130
131/// Error returned when a conversion between an integer and a BCD overflows.
132///
133/// # Examples
134///
135/// ```rust
136/// use const_bcd::{Bcd, bcd};
137///
138/// // A Bcd<1> can only hold two decimal digits (a value <= 99)
139/// let err = Bcd::<1>::try_from_u8(240).unwrap_err();
140/// assert_eq!(err.to_string(), "Overflow during BCD conversion");
141///
142/// let bcd: Bcd<2> = bcd!(1234u16);
143/// let err = bcd.try_into_u8().unwrap_err();
144/// assert_eq!(err.to_string(), "Overflow during BCD conversion");
145/// ```
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct BcdOverflowError;
148
149impl fmt::Display for BcdOverflowError {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 write!(f, "Overflow during BCD conversion")
152 }
153}
154
155impl Error for BcdOverflowError {}
156
157macro_rules! impl_bcd_try_from {
158 ($(#[$attr:meta])* $name:ident, $ty:ty) => {
159 $(#[$attr])*
160 pub const fn $name(value: $ty) -> Result<Self, BcdOverflowError> {
161 const BITS: u32 = <$ty>::BITS;
162
163 let mut bcd = [0u8; BYTES];
164 let mut overflow = false;
165
166 let mut bit = BITS;
167 while bit > 0 {
168 bit -= 1;
169
170 let mut byte = 0;
171 while byte < BYTES {
172 let lo = bcd[byte] & 0x0f;
173 let hi = (bcd[byte] >> 4) & 0x0f;
174
175 if lo >= 5 {
176 bcd[byte] += 0x03;
177 }
178
179 if hi >= 5 {
180 bcd[byte] += 0x30;
181 }
182
183 byte += 1;
184 }
185
186 let mut carry = ((value >> bit) & 1) as u8;
187
188 let mut i = BYTES;
189 while i > 0 {
190 i -= 1;
191
192 let next_carry = (bcd[i] >> 7) & 1;
193 bcd[i] = (bcd[i] << 1) | carry;
194 carry = next_carry;
195 }
196
197 if carry != 0 {
198 overflow = true;
199 }
200 }
201
202 if overflow {
203 Err(BcdOverflowError)
204 } else {
205 Ok(Bcd(bcd))
206 }
207 }
208 };
209}
210
211macro_rules! impl_bcd_try_into {
212 ($(#[$attr:meta])* $name:ident, $ty:ty) => {
213 $(#[$attr])*
214 pub const fn $name(self) -> Result<$ty, BcdOverflowError> {
215 let mut result: $ty = 0;
216
217 let mut i = 0;
218 while i < BYTES {
219 let hi = (self.0[i] >> 4) & 0x0f;
220 let lo = self.0[i] & 0x0f;
221
222 result = match result.checked_mul(10) {
223 Some(v) => v,
224 None => return Err(BcdOverflowError),
225 };
226
227 result = match result.checked_add(hi as $ty) {
228 Some(v) => v,
229 None => return Err(BcdOverflowError),
230 };
231
232 result = match result.checked_mul(10) {
233 Some(v) => v,
234 None => return Err(BcdOverflowError),
235 };
236
237 result = match result.checked_add(lo as $ty) {
238 Some(v) => v,
239 None => return Err(BcdOverflowError),
240 };
241
242 i += 1;
243 }
244
245 Ok(result)
246 }
247 };
248}
249
250impl<const BYTES: usize> Bcd<BYTES> {
251 /// Constructs a `Bcd` from a raw byte array already in packed BCD format.
252 ///
253 /// Each nibble in `bytes` must be a valid decimal digit (`0..=9`). If any nibble
254 /// is in the range `10..=15`, an [`InvalidBcdDigit`] error is returned containing
255 /// the offending nibble value.
256 ///
257 /// # Errors
258 ///
259 /// Returns [`Err(InvalidBcdDigit)`](InvalidBcdDigit) if any nibble exceeds `9`.
260 ///
261 /// # Examples
262 ///
263 /// ```rust
264 /// use const_bcd::Bcd;
265 ///
266 /// // Valid BCD bytes
267 /// let n = Bcd::<2>::from_bcd_bytes([0x12, 0x34]).unwrap();
268 /// assert_eq!(n.to_string(), "1234");
269 ///
270 /// // Invalid: high nibble of first byte is 0xA
271 /// assert!(Bcd::<2>::from_bcd_bytes([0xA0, 0x00]).is_err());
272 ///
273 /// // Invalid: low nibble of second byte is 0xF
274 /// assert!(Bcd::<2>::from_bcd_bytes([0x00, 0x0F]).is_err());
275 /// ```
276 pub const fn from_bcd_bytes(bytes: [u8; BYTES]) -> Result<Self, InvalidBcdDigit> {
277 let mut i = 0;
278
279 while i < BYTES {
280 let high = bytes[i] >> 4;
281 let low = bytes[i] & 0x0F;
282 if high > DIGIT_MAX {
283 return Err(InvalidBcdDigit(high));
284 }
285 if low > DIGIT_MAX {
286 return Err(InvalidBcdDigit(low));
287 }
288 i += 1;
289 }
290
291 Ok(Self(bytes))
292 }
293
294 impl_bcd_try_from!(
295 /// Converts a [`u8`] to BCD using the double-dabble algorithm.
296 ///
297 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
298 ///
299 /// # Examples
300 ///
301 /// ```rust
302 /// use const_bcd::Bcd;
303 ///
304 /// let n = Bcd::<1>::try_from_u8(99).unwrap();
305 /// assert_eq!(n.to_string(), "99");
306 ///
307 /// // 100 requires 3 digits but Bcd<1> holds at most 2
308 /// assert!(Bcd::<1>::try_from_u8(100).is_err());
309 /// ```
310 try_from_u8, u8
311 );
312
313 impl_bcd_try_from!(
314 /// Converts a [`u16`] to BCD using the double-dabble algorithm.
315 ///
316 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
317 ///
318 /// # Examples
319 ///
320 /// ```rust
321 /// use const_bcd::Bcd;
322 ///
323 /// let n = Bcd::<2>::try_from_u16(9999).unwrap();
324 /// assert_eq!(n.to_string(), "9999");
325 ///
326 /// // Bcd<1> can hold at most 99
327 /// assert!(Bcd::<1>::try_from_u16(100).is_err());
328 /// ```
329 try_from_u16, u16
330 );
331
332 impl_bcd_try_from!(
333 /// Converts a [`u32`] to BCD using the double-dabble algorithm.
334 ///
335 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
336 ///
337 /// # Examples
338 ///
339 /// ```rust
340 /// use const_bcd::Bcd;
341 ///
342 /// let n = Bcd::<4>::try_from_u32(12_345_678).unwrap();
343 /// assert_eq!(n.to_string(), "12345678");
344 /// ```
345 try_from_u32, u32
346 );
347
348 impl_bcd_try_from!(
349 /// Converts a [`u64`] to BCD using the double-dabble algorithm.
350 ///
351 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
352 ///
353 /// # Examples
354 ///
355 /// ```rust
356 /// use const_bcd::Bcd;
357 ///
358 /// let n = Bcd::<8>::try_from_u64(1_000_000_000_000u64).unwrap();
359 /// assert_eq!(n.to_string(), "1000000000000");
360 /// ```
361 try_from_u64, u64
362 );
363
364 impl_bcd_try_from!(
365 /// Converts a [`u128`] to BCD using the double-dabble algorithm.
366 ///
367 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
368 ///
369 /// # Examples
370 ///
371 /// ```rust
372 /// use const_bcd::Bcd;
373 ///
374 /// let n = Bcd::<20>::try_from_u128(u128::MAX).unwrap();
375 /// assert_eq!(n.to_string(), u128::MAX.to_string());
376 /// ```
377 try_from_u128, u128
378 );
379
380 impl_bcd_try_from!(
381 /// Converts a [`usize`] to BCD using the double-dabble algorithm.
382 ///
383 /// Returns `Err(BcdOverflowError)` if `value` has more decimal digits than `BYTES * 2` can hold.
384 ///
385 /// # Examples
386 ///
387 /// ```rust
388 /// use const_bcd::Bcd;
389 ///
390 /// let n = Bcd::<4>::try_from_usize(12345usize).unwrap();
391 /// assert_eq!(n.to_string(), "12345");
392 /// ```
393 try_from_usize, usize
394 );
395
396 impl_bcd_try_into!(
397 /// Converts this BCD value to a [`u8`].
398 ///
399 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`u8::MAX`].
400 ///
401 /// # Examples
402 ///
403 /// ```rust
404 /// use const_bcd::Bcd;
405 ///
406 /// let n = Bcd::<1>::try_from_u8(42).unwrap();
407 /// assert_eq!(n.try_into_u8(), Ok(42u8));
408 ///
409 /// // A large Bcd<2> value won't fit in a u8
410 /// let big = Bcd::<2>::try_from_u16(1000).unwrap();
411 /// assert!(big.try_into_u8().is_err());
412 /// ```
413 try_into_u8, u8
414 );
415
416 impl_bcd_try_into!(
417 /// Converts this BCD value to a [`u16`].
418 ///
419 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`u16::MAX`].
420 ///
421 /// # Examples
422 ///
423 /// ```rust
424 /// use const_bcd::Bcd;
425 ///
426 /// let n = Bcd::<2>::try_from_u16(1234).unwrap();
427 /// assert_eq!(n.try_into_u16(), Ok(1234u16));
428 /// ```
429 try_into_u16, u16
430 );
431
432 impl_bcd_try_into!(
433 /// Converts this BCD value to a [`u32`].
434 ///
435 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`u32::MAX`].
436 ///
437 /// # Examples
438 ///
439 /// ```rust
440 /// use const_bcd::Bcd;
441 ///
442 /// let n = Bcd::<4>::try_from_u32(100_000).unwrap();
443 /// assert_eq!(n.try_into_u32(), Ok(100_000u32));
444 /// ```
445 try_into_u32, u32
446 );
447
448 impl_bcd_try_into!(
449 /// Converts this BCD value to a [`u64`].
450 ///
451 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`u64::MAX`].
452 ///
453 /// # Examples
454 ///
455 /// ```rust
456 /// use const_bcd::Bcd;
457 ///
458 /// let n = Bcd::<10>::try_from_u64(u64::MAX).unwrap();
459 /// assert_eq!(n.try_into_u64(), Ok(u64::MAX));
460 /// ```
461 try_into_u64, u64
462 );
463
464 impl_bcd_try_into!(
465 /// Converts this BCD value to a [`u128`].
466 ///
467 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`u128::MAX`].
468 ///
469 /// # Examples
470 ///
471 /// ```rust
472 /// use const_bcd::Bcd;
473 ///
474 /// // A value larger than u64::MAX that still fits in Bcd<10> (max 10^20 - 1).
475 /// let v = 20_000_000_000_000_000_000u128;
476 /// let n = Bcd::<10>::try_from_u128(v).unwrap();
477 /// assert_eq!(n.try_into_u128(), Ok(v));
478 /// ```
479 try_into_u128, u128
480 );
481
482 impl_bcd_try_into!(
483 /// Converts this BCD value to a [`usize`].
484 ///
485 /// Returns `Err(BcdOverflowError)` if the decoded value exceeds [`usize::MAX`].
486 ///
487 /// # Examples
488 ///
489 /// ```rust
490 /// use const_bcd::Bcd;
491 ///
492 /// let n = Bcd::<4>::try_from_usize(99999usize).unwrap();
493 /// assert_eq!(n.try_into_usize(), Ok(99999usize));
494 /// ```
495 try_into_usize, usize
496 );
497}
498
499/// Formats the BCD value as a decimal string.
500///
501/// Behaves like a native unsigned integer: width, alignment, sign (`+`), and
502/// numeric zero-padding are honored via [`core::fmt::Formatter::pad_integral`].
503///
504/// # Examples
505///
506/// ```rust
507/// use const_bcd::Bcd;
508///
509/// let n = Bcd::<4>::try_from_u32(42).unwrap();
510/// assert_eq!(format!("{n}"), "42");
511/// assert_eq!(format!("{n:8}"), " 42");
512/// assert_eq!(format!("{n:08}"), "00000042");
513/// assert_eq!(format!("{n:<8}"), "42 ");
514/// assert_eq!(format!("{n:+}"), "+42");
515///
516/// // Zero displays as "0", not ""
517/// let zero = Bcd::<2>::try_from_u16(0).unwrap();
518/// assert_eq!(format!("{zero}"), "0");
519/// ```
520impl<const BYTES: usize> fmt::Display for Bcd<BYTES> {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 let mut buf = [[0u8; 2]; BYTES];
523 let mut len = 0;
524 for nibble in self
525 .0
526 .iter()
527 .flat_map(|b| [b >> 4, b & 0x0F])
528 .skip_while(|n| *n == 0)
529 {
530 // Division and modulo will get compiled away to len >> 1 and len & 1, so don't worry about performance.
531 buf[len / 2][len % 2] = b'0' + nibble;
532 len += 1;
533 }
534 let s = if len == 0 {
535 // No non-zero nibbles (or `BYTES == 0`): emit a single "0".
536 "0"
537 } else {
538 str::from_utf8(&buf.as_flattened()[..len]).unwrap()
539 };
540 f.pad_integral(true, "", s)
541 }
542}
543
544macro_rules! impl_bcd_into {
545 ($prim:ty, $fn_name:ident, $try_into_fn:ident, $($bytes:literal),+) => {
546 $(
547 impl Bcd<$bytes> {
548 /// Infallibly converts this BCD value to a primitive integer.
549 ///
550 /// Available only for `BYTES` values whose maximum representable BCD
551 /// value is statically guaranteed to fit in the target primitive, so
552 /// this method cannot overflow.
553 pub const fn $fn_name(self) -> $prim {
554 match self.$try_into_fn() {
555 Ok(val) => val,
556 // Unreachable: `BYTES` is bounded so that overflow is impossible.
557 // A panic branch is required to keep this function total for `const fn`.
558 Err(_) => panic!("BUG: infallible BCD conversion overflowed")
559 }
560 }
561 }
562 )+
563 };
564}
565
566// An infallible `into_*` exists for every BYTES value whose maximum representable
567// BCD value (10.pow(2 * BYTES) - 1) is guaranteed to fit in the target primitive.
568// The largest safe BYTES is `ilog10(PRIM::MAX) / 2`:
569//
570// u8: ilog10(u8::MAX) = 2 -> BYTES <= 1
571// u16: ilog10(u16::MAX) = 4 -> BYTES <= 2
572// u32: ilog10(u32::MAX) = 9 -> BYTES <= 4
573// u64: ilog10(u64::MAX) = 19 -> BYTES <= 9
574// u128: ilog10(u128::MAX) = 38 -> BYTES <= 19
575//
576// `usize` is treated as if it were `u16` so the impls remain sound on 16-bit targets.
577impl_bcd_into!(u8, into_u8, try_into_u8, 0, 1);
578impl_bcd_into!(u16, into_u16, try_into_u16, 0, 1, 2);
579impl_bcd_into!(u32, into_u32, try_into_u32, 0, 1, 2, 3, 4);
580impl_bcd_into!(u64, into_u64, try_into_u64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
581impl_bcd_into!(
582 u128,
583 into_u128,
584 try_into_u128,
585 0,
586 1,
587 2,
588 3,
589 4,
590 5,
591 6,
592 7,
593 8,
594 9,
595 10,
596 11,
597 12,
598 13,
599 14,
600 15,
601 16,
602 17,
603 18,
604 19
605);
606impl_bcd_into!(usize, into_usize, try_into_usize, 0, 1, 2);
607
608/// Constructs a [`Bcd`] from an unsigned integer expression, panicking on overflow.
609///
610/// The value is cast to `u128` and then dispatched at runtime to the smallest
611/// `try_from_*` method capable of holding it. This keeps the double-dabble loop
612/// short for small values without requiring the caller to pick the right method.
613///
614/// This macro is `const`-usable, so it can construct `Bcd` values in `const`
615/// items and other `const` contexts.
616///
617/// # Signed values
618///
619/// This macro accepts any expression that can be cast to `u128`. Passing a
620/// negative value is a logic error: the value is reinterpreted as an unsigned
621/// integer via the `as` cast, which will almost always overflow the target
622/// `Bcd<BYTES>` and panic. Use one of the `try_from_*` methods directly if you
623/// need explicit control over the source type.
624///
625/// # Panics
626///
627/// Panics if the value overflows the `Bcd<BYTES>` that type inference selects.
628///
629/// # Examples
630///
631/// ```rust
632/// use const_bcd::{Bcd, bcd};
633///
634/// let n: Bcd<2> = bcd!(1234u16);
635/// assert_eq!(n.to_string(), "1234");
636///
637/// // Works with expressions, not just literals
638/// let x = 56u8;
639/// let n: Bcd<1> = bcd!(x);
640/// assert_eq!(n.to_string(), "56");
641///
642/// // Works in const context
643/// const M: Bcd<4> = bcd!(12345678u32);
644/// assert_eq!(M.to_string(), "12345678");
645///
646/// // Works with u128-range values
647/// let n: Bcd<20> = bcd!(u128::MAX);
648/// assert_eq!(n.to_string(), u128::MAX.to_string());
649/// ```
650#[macro_export]
651macro_rules! bcd {
652 ($v:expr) => {{
653 let v: u128 = $v as u128;
654 match if v <= u8::MAX as u128 {
655 $crate::Bcd::try_from_u8(v as u8)
656 } else if v <= u16::MAX as u128 {
657 $crate::Bcd::try_from_u16(v as u16)
658 } else if v <= u32::MAX as u128 {
659 $crate::Bcd::try_from_u32(v as u32)
660 } else if v <= u64::MAX as u128 {
661 $crate::Bcd::try_from_u64(v as u64)
662 } else {
663 $crate::Bcd::try_from_u128(v)
664 } {
665 Ok(bcd) => bcd,
666 Err(_) => panic!("Overflow during BCD conversion"),
667 }
668 }};
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674 use test_format::assert_display_fmt;
675
676 // --- Construction: from_bcd_bytes ---
677
678 #[test]
679 fn from_bcd_bytes_valid() {
680 let n = Bcd::<2>::from_bcd_bytes([0x12, 0x34]).unwrap();
681 assert_display_fmt!(n, "1234");
682 }
683
684 #[test]
685 fn from_bcd_bytes_all_zeros() {
686 let n = Bcd::<4>::from_bcd_bytes([0; 4]).unwrap();
687 assert_eq!(n.try_into_u32(), Ok(0));
688 }
689
690 #[test]
691 fn from_bcd_bytes_rejects_invalid_high_nibble() {
692 let err = Bcd::<1>::from_bcd_bytes([0xA0]).unwrap_err();
693 assert_eq!(err, InvalidBcdDigit(0xA));
694 }
695
696 #[test]
697 fn from_bcd_bytes_rejects_invalid_low_nibble() {
698 let err = Bcd::<1>::from_bcd_bytes([0x0B]).unwrap_err();
699 assert_eq!(err, InvalidBcdDigit(0xB));
700 }
701
702 #[test]
703 fn from_bcd_bytes_reports_first_invalid_nibble() {
704 // The high nibble of the second byte (0xC) is the first bad nibble.
705 let err = Bcd::<2>::from_bcd_bytes([0x12, 0xC3]).unwrap_err();
706 assert_eq!(err, InvalidBcdDigit(0xC));
707 }
708
709 // --- Construction: try_from_* roundtrips and overflow ---
710
711 #[test]
712 fn try_from_u8_exhaustive() {
713 for v in 0..=99u8 {
714 let bcd = Bcd::<1>::try_from_u8(v).unwrap();
715 assert_eq!(bcd.try_into_u8(), Ok(v));
716 }
717 for v in 100..=255u8 {
718 assert!(Bcd::<1>::try_from_u8(v).is_err());
719 }
720 }
721
722 #[test]
723 fn try_from_u8_wider_bcd_never_overflows() {
724 for v in 0..=255u8 {
725 let bcd = Bcd::<2>::try_from_u8(v).unwrap();
726 assert_eq!(bcd.try_into_u16(), Ok(v as u16));
727 }
728 }
729
730 #[test]
731 fn try_from_u16_roundtrip() {
732 for v in [0u16, 1, 999, 9999, u16::MAX] {
733 let bcd = Bcd::<3>::try_from_u16(v).unwrap();
734 assert_eq!(bcd.try_into_u16(), Ok(v));
735 }
736 }
737
738 #[test]
739 fn try_from_u16_overflow() {
740 // Bcd<2> holds at most 9999.
741 assert!(Bcd::<2>::try_from_u16(10_000).is_err());
742 assert!(Bcd::<2>::try_from_u16(u16::MAX).is_err());
743 }
744
745 #[test]
746 fn try_from_u32_roundtrip() {
747 for v in [0u32, 1, 9_999, 99_999_999, u32::MAX] {
748 let bcd = Bcd::<5>::try_from_u32(v).unwrap();
749 assert_eq!(bcd.try_into_u32(), Ok(v));
750 }
751 }
752
753 #[test]
754 fn try_from_u32_overflow() {
755 // Bcd<4> holds at most 99_999_999.
756 assert!(Bcd::<4>::try_from_u32(100_000_000).is_err());
757 assert!(Bcd::<4>::try_from_u32(u32::MAX).is_err());
758 }
759
760 #[test]
761 fn try_from_u64_roundtrip() {
762 for v in [0u64, 1, u16::MAX as u64, u32::MAX as u64, u64::MAX] {
763 let bcd = Bcd::<10>::try_from_u64(v).unwrap();
764 assert_eq!(bcd.try_into_u64(), Ok(v));
765 }
766 }
767
768 #[test]
769 fn try_from_u64_overflow() {
770 // Bcd<9> holds at most 10^18 - 1, which is less than u64::MAX.
771 assert!(Bcd::<9>::try_from_u64(u64::MAX).is_err());
772 }
773
774 #[test]
775 fn try_from_u128_roundtrip() {
776 for v in [0u128, 1, u32::MAX as u128, u64::MAX as u128, u128::MAX] {
777 let bcd = Bcd::<20>::try_from_u128(v).unwrap();
778 assert_eq!(bcd.try_into_u128(), Ok(v));
779 }
780 }
781
782 #[test]
783 fn try_from_u128_overflow() {
784 // Bcd<19> holds at most 10^38 - 1, which is less than u128::MAX.
785 assert!(Bcd::<19>::try_from_u128(u128::MAX).is_err());
786 }
787
788 #[test]
789 fn try_from_usize_roundtrip() {
790 for v in [0usize, 1, 99, 99_999] {
791 let bcd = Bcd::<3>::try_from_usize(v).unwrap();
792 assert_eq!(bcd.try_into_usize(), Ok(v));
793 }
794 }
795
796 #[test]
797 fn try_from_usize_overflow() {
798 assert!(Bcd::<2>::try_from_usize(10_000).is_err());
799 }
800
801 // --- try_into_* overflow ---
802
803 #[test]
804 fn try_into_u8_overflow() {
805 let bcd = Bcd::<2>::try_from_u16(1000).unwrap();
806 assert!(bcd.try_into_u8().is_err());
807 }
808
809 #[test]
810 fn try_into_u16_overflow() {
811 let bcd = Bcd::<3>::try_from_u32(100_000).unwrap();
812 assert!(bcd.try_into_u16().is_err());
813 }
814
815 #[test]
816 fn try_into_u32_overflow() {
817 // Bcd<5> filled with 9s = 9_999_999_999 > u32::MAX.
818 let bcd = Bcd::<5>::from_bcd_bytes([0x99; 5]).unwrap();
819 assert!(bcd.try_into_u32().is_err());
820 }
821
822 #[test]
823 fn try_into_u64_overflow() {
824 // Bcd<10> filled with 9s = 10^20 - 1 > u64::MAX.
825 let bcd = Bcd::<10>::from_bcd_bytes([0x99; 10]).unwrap();
826 assert!(bcd.try_into_u64().is_err());
827 }
828
829 #[test]
830 fn try_into_u128_overflow() {
831 // Bcd<20> filled with 9s represents 10^40 - 1, which overflows u128.
832 let bcd = Bcd::<20>::from_bcd_bytes([0x99; 20]).unwrap();
833 assert!(bcd.try_into_u128().is_err());
834 }
835
836 #[test]
837 fn try_into_usize_overflow_on_any_target() {
838 // Overflows usize on every currently supported target (max 64-bit).
839 let bcd = Bcd::<20>::from_bcd_bytes([0x99; 20]).unwrap();
840 assert!(bcd.try_into_usize().is_err());
841 }
842
843 // --- Infallible into_* ---
844
845 #[test]
846 fn infallible_into_u8() {
847 let bcd = Bcd::<1>::try_from_u8(42).unwrap();
848 assert_eq!(bcd.into_u8(), 42u8);
849 }
850
851 #[test]
852 fn infallible_into_u16() {
853 let bcd = Bcd::<2>::try_from_u16(9999).unwrap();
854 assert_eq!(bcd.into_u16(), 9999u16);
855 }
856
857 #[test]
858 fn infallible_into_u32() {
859 let bcd = Bcd::<4>::try_from_u32(12_345_678).unwrap();
860 assert_eq!(bcd.into_u32(), 12_345_678u32);
861 }
862
863 #[test]
864 fn infallible_into_u64() {
865 let v = 999_999_999_999_999_999u64;
866 let bcd = Bcd::<9>::try_from_u64(v).unwrap();
867 assert_eq!(bcd.into_u64(), v);
868 }
869
870 #[test]
871 fn infallible_into_u128() {
872 let v = 10u128.pow(38) - 1;
873 let bcd = Bcd::<19>::try_from_u128(v).unwrap();
874 assert_eq!(bcd.into_u128(), v);
875 }
876
877 #[test]
878 fn infallible_into_usize() {
879 let bcd = Bcd::<2>::try_from_usize(9999).unwrap();
880 assert_eq!(bcd.into_usize(), 9999usize);
881 }
882
883 // --- Display ---
884
885 #[test]
886 fn display_zero() {
887 let n = Bcd::<2>::try_from_u16(0).unwrap();
888 assert_display_fmt!(n, "0");
889 }
890
891 #[test]
892 fn display_no_leading_zeros() {
893 let n = Bcd::<4>::try_from_u32(42).unwrap();
894 assert_display_fmt!(n, "42");
895 }
896
897 #[test]
898 fn display_single_digit() {
899 let n = Bcd::<4>::try_from_u32(7).unwrap();
900 assert_display_fmt!(n, "7");
901 }
902
903 #[test]
904 fn display_padding_right_aligned() {
905 let n = Bcd::<2>::try_from_u16(42).unwrap();
906 assert_display_fmt!(format_args!("{:0>6}", n), "000042");
907 }
908
909 #[test]
910 fn display_padding_left_aligned() {
911 let n = Bcd::<2>::try_from_u16(42).unwrap();
912 assert_display_fmt!(format_args!("{:<6}", n), "42 ");
913 }
914
915 #[test]
916 fn display_default_right_aligned_like_integer() {
917 // Native uints default to right-align with space fill.
918 let n = Bcd::<2>::try_from_u16(42).unwrap();
919 assert_display_fmt!(format_args!("{:8}", n), " 42");
920 }
921
922 #[test]
923 fn display_numeric_zero_padding() {
924 // `{:08}` should zero-pad like an integer, not space-pad like a string.
925 let n = Bcd::<2>::try_from_u16(42).unwrap();
926 assert_display_fmt!(format_args!("{:08}", n), "00000042");
927 }
928
929 #[test]
930 fn display_positive_sign_flag() {
931 // `{:+}` should emit `+` since BCD values are always non-negative.
932 let n = Bcd::<2>::try_from_u16(42).unwrap();
933 assert_display_fmt!(format_args!("{:+}", n), "+42");
934 }
935
936 #[test]
937 fn display_positive_sign_with_zero_pad() {
938 // Sign counts against width when combined with zero-padding.
939 let n = Bcd::<2>::try_from_u16(42).unwrap();
940 assert_display_fmt!(format_args!("{:+08}", n), "+0000042");
941 }
942
943 #[test]
944 fn display_zero_pad_zero_value() {
945 let n = Bcd::<2>::try_from_u16(0).unwrap();
946 assert_display_fmt!(format_args!("{:04}", n), "0000");
947 }
948
949 #[test]
950 fn display_u128_max() {
951 let bcd = Bcd::<20>::try_from_u128(u128::MAX).unwrap();
952 assert_eq!(bcd.to_string(), u128::MAX.to_string());
953 }
954
955 #[test]
956 fn display_internal_zeros() {
957 // Guards the `skip_while(|n| *n == 0)` logic: only leading zeros should
958 // be trimmed, not zeros between non-zero digits.
959 let n = Bcd::<2>::try_from_u16(1002).unwrap();
960 assert_display_fmt!(n, "1002");
961
962 let n = Bcd::<4>::try_from_u32(1_000_000).unwrap();
963 assert_display_fmt!(n, "1000000");
964 }
965
966 // --- Debug ---
967
968 #[test]
969 fn debug_shows_internal_bytes() {
970 // Derived Debug: prints the byte array in decimal.
971 let bcd = Bcd::<2>::from_bcd_bytes([0x12, 0x34]).unwrap();
972 assert_eq!(format!("{bcd:?}"), "Bcd([18, 52])");
973 }
974
975 // --- Ordering / Eq / Copy / Hash ---
976
977 #[test]
978 fn ordering() {
979 let a = Bcd::<2>::try_from_u16(100).unwrap();
980 let b = Bcd::<2>::try_from_u16(200).unwrap();
981 let c = Bcd::<2>::try_from_u16(200).unwrap();
982 assert!(a < b);
983 assert!(b > a);
984 assert_eq!(b, c);
985 }
986
987 #[test]
988 fn copy_and_clone() {
989 let a = Bcd::<2>::try_from_u16(42).unwrap();
990 let b = a;
991 #[allow(clippy::clone_on_copy)]
992 let c = a.clone();
993 assert_eq!(a, b);
994 assert_eq!(a, c);
995 }
996
997 #[test]
998 fn hash_consistent_with_eq() {
999 use std::collections::HashMap;
1000 let mut map = HashMap::new();
1001 map.insert(Bcd::<2>::try_from_u16(1234).unwrap(), "hi");
1002 assert_eq!(
1003 map.get(&Bcd::<2>::try_from_u16(1234).unwrap()),
1004 Some(&"hi"),
1005 );
1006 }
1007
1008 // --- Error types ---
1009
1010 #[test]
1011 fn invalid_bcd_digit_display() {
1012 let e = InvalidBcdDigit(10);
1013 assert_display_fmt!(e, "Invalid BCD digit 10. Must be <= 9");
1014 }
1015
1016 #[test]
1017 fn bcd_overflow_error_display() {
1018 let e = BcdOverflowError;
1019 assert_display_fmt!(e, "Overflow during BCD conversion");
1020 }
1021
1022 // --- Bcd<0> edge case ---
1023
1024 #[test]
1025 fn zero_byte_bcd_accepts_zero_and_overflows_on_one() {
1026 assert!(Bcd::<0>::try_from_u8(0).is_ok());
1027 assert!(Bcd::<0>::try_from_u8(1).is_err());
1028
1029 let z = Bcd::<0>::try_from_u8(0).unwrap();
1030 assert_eq!(z.try_into_u8(), Ok(0));
1031 assert_eq!(z.into_u8(), 0);
1032 assert_display_fmt!(z, "0");
1033 }
1034
1035 // --- bcd! macro ---
1036
1037 #[test]
1038 fn bcd_macro_u8_range() {
1039 let n: Bcd<1> = bcd!(99u8);
1040 assert_display_fmt!(n, "99");
1041 }
1042
1043 #[test]
1044 fn bcd_macro_u16_range() {
1045 let n: Bcd<2> = bcd!(1234u16);
1046 assert_display_fmt!(n, "1234");
1047 }
1048
1049 #[test]
1050 fn bcd_macro_u32_range() {
1051 let n: Bcd<5> = bcd!(100_000u32);
1052 assert_display_fmt!(n, "100000");
1053 }
1054
1055 #[test]
1056 fn bcd_macro_u64_range() {
1057 let n: Bcd<10> = bcd!(u64::MAX);
1058 assert_eq!(n.to_string(), u64::MAX.to_string());
1059 }
1060
1061 #[test]
1062 fn bcd_macro_u128_range() {
1063 let n: Bcd<20> = bcd!(u128::MAX);
1064 assert_eq!(n.to_string(), u128::MAX.to_string());
1065 }
1066
1067 #[test]
1068 fn bcd_macro_expression() {
1069 let x = 56u8;
1070 let n: Bcd<1> = bcd!(x);
1071 assert_display_fmt!(n, "56");
1072 }
1073
1074 #[test]
1075 fn bcd_macro_zero() {
1076 let n: Bcd<1> = bcd!(0u8);
1077 assert_display_fmt!(n, "0");
1078 }
1079
1080 #[test]
1081 #[should_panic(expected = "Overflow during BCD conversion")]
1082 fn bcd_macro_panics_on_overflow() {
1083 // 100 won't fit in Bcd<1> which holds at most 2 digits.
1084 let _: Bcd<1> = bcd!(100u8);
1085 }
1086
1087 // --- const context ---
1088
1089 #[test]
1090 fn const_construction_and_conversion() {
1091 const RAW: Bcd<2> = match Bcd::<2>::from_bcd_bytes([0x12, 0x34]) {
1092 Ok(v) => v,
1093 Err(_) => panic!(),
1094 };
1095 const FROM_INT: Bcd<2> = match Bcd::<2>::try_from_u16(1234) {
1096 Ok(v) => v,
1097 Err(_) => panic!(),
1098 };
1099 const FROM_MACRO: Bcd<2> = bcd!(1234u16);
1100 const AS_INT: u16 = match FROM_MACRO.try_into_u16() {
1101 Ok(v) => v,
1102 Err(_) => 0,
1103 };
1104 const AS_INFALLIBLE: u16 = FROM_MACRO.into_u16();
1105
1106 assert_eq!(RAW, FROM_INT);
1107 assert_eq!(RAW, FROM_MACRO);
1108 assert_eq!(AS_INT, 1234);
1109 assert_eq!(AS_INFALLIBLE, 1234);
1110 }
1111}