pub struct CheckedUnigramId<const N: usize>(/* private fields */);Expand description
An identifier of N bytes carrying a trailing check word, rendered as N + 1
alphabet words.
One extra word is 8 bits of CRC over the payload, so every single-word substitution and transposition is caught outright, and an arbitrary accidental mutation with probability about 255/256. Use it where a value has to prove it is the one that was issued without the original in hand.
It detects accidents, not tampering: anyone who can change the payload can recompute
the check word. A hostile party calls for a keyed MAC over
CheckedUnigramId::as_bytes, which this crate does not provide.
use unigram::{CheckedUnigramId, ParseError};
let id = CheckedUnigramId::from_bytes([1u8, 2, 3, 4]);
let text = id.to_string();
assert_eq!(text.split(' ').count(), 5); // four payload words, one check
assert_eq!(CheckedUnigramId::<4>::parse(&text).unwrap(), id);
// Swap one word for another valid word: caught, where UnigramId could not.
let mangled = text.replacen("account", "action", 1);
assert!(matches!(
CheckedUnigramId::<4>::parse(&mangled),
Err(ParseError::ChecksumMismatch { .. })
));Implementations§
Source§impl<const N: usize> CheckedUnigramId<N>
impl<const N: usize> CheckedUnigramId<N>
Sourcepub const fn from_bytes(bytes: [u8; N]) -> Self
pub const fn from_bytes(bytes: [u8; N]) -> Self
Wrap bytes that are already in hand. The check word is derived, never stored.
Sourcepub fn try_random() -> Result<Self, Error>
pub fn try_random() -> Result<Self, Error>
Mint N bytes of fresh entropy from the OS CSPRNG.
Sourcepub fn parse(text: &str) -> Result<Self, ParseError>
pub fn parse(text: &str) -> Result<Self, ParseError>
Parse the canonical form and verify the check word.
Sourcepub fn recover(text: &str) -> Result<Self, ParseError>
pub fn recover(text: &str) -> Result<Self, ParseError>
Parse tolerantly and verify the check word.
The pairing worth noting: tolerant parsing is what lets a value survive a round trip, and the check word is what keeps that tolerance from quietly accepting a value the trip changed.
Sourcepub const fn as_bytes(&self) -> &[u8; N]
pub const fn as_bytes(&self) -> &[u8; N]
The bytes this identifier carries, without the check word.
Sourcepub const fn into_bytes(self) -> [u8; N]
pub const fn into_bytes(self) -> [u8; N]
Consume the identifier, yielding its bytes.
Sourcepub const fn check_byte(&self) -> u8
pub const fn check_byte(&self) -> u8
The check byte this payload computes.
Trait Implementations§
Source§impl<const N: usize> Clone for CheckedUnigramId<N>
impl<const N: usize> Clone for CheckedUnigramId<N>
Source§fn clone(&self) -> CheckedUnigramId<N>
fn clone(&self) -> CheckedUnigramId<N>
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more