1
0
Fork 0
forked from wry/wry

util: optimize opaque string formatting

This commit is contained in:
Julian Orth 2024-10-10 17:01:27 +02:00
parent e6c3c9c1ed
commit 8d6aaf79a7
3 changed files with 30 additions and 6 deletions

View file

@ -1,5 +1,6 @@
use {
crate::utils::opaque::{opaque, Opaque, OpaqueError},
crate::utils::opaque::{opaque, Opaque, OpaqueError, OPAQUE_LEN},
arrayvec::ArrayString,
std::{
fmt::{Display, Formatter},
str::FromStr,
@ -13,6 +14,12 @@ pub fn activation_token() -> ActivationToken {
ActivationToken(opaque())
}
impl ActivationToken {
pub fn to_string(self) -> ArrayString<OPAQUE_LEN> {
self.0.to_string()
}
}
impl Display for ActivationToken {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)

View file

@ -1,4 +1,5 @@
use {
arrayvec::ArrayString,
rand::{thread_rng, Rng},
std::{
fmt::{Debug, Display, Formatter},
@ -22,6 +23,15 @@ pub fn opaque() -> Opaque {
}
}
impl Opaque {
pub fn to_string(self) -> ArrayString<OPAQUE_LEN> {
use std::fmt::Write;
let mut s = ArrayString::new();
write!(s, "{}", self).unwrap();
s
}
}
impl Display for Opaque {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:016x}", self.hi)?;
@ -40,20 +50,20 @@ impl FromStr for Opaque {
type Err = OpaqueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != LEN {
if s.len() != OPAQUE_LEN {
return Err(OpaqueError::InvalidLength);
}
if !s.is_char_boundary(LEN / 2) {
if !s.is_char_boundary(OPAQUE_LEN / 2) {
return Err(OpaqueError::NotAscii);
}
let (hi, lo) = s.split_at(LEN / 2);
let (hi, lo) = s.split_at(OPAQUE_LEN / 2);
let hi = u64::from_str_radix(hi, 16).map_err(OpaqueError::Parse)?;
let lo = u64::from_str_radix(lo, 16).map_err(OpaqueError::Parse)?;
Ok(Self { lo, hi })
}
}
const LEN: usize = 32;
pub const OPAQUE_LEN: usize = 32;
#[derive(Debug, Error)]
pub enum OpaqueError {

View file

@ -1,5 +1,6 @@
use {
crate::utils::opaque::{opaque, Opaque, OpaqueError},
crate::utils::opaque::{opaque, Opaque, OpaqueError, OPAQUE_LEN},
arrayvec::ArrayString,
std::{
fmt::{Display, Formatter},
str::FromStr,
@ -13,6 +14,12 @@ pub fn toplevel_identifier() -> ToplevelIdentifier {
ToplevelIdentifier(opaque())
}
impl ToplevelIdentifier {
pub fn to_string(self) -> ArrayString<OPAQUE_LEN> {
self.0.to_string()
}
}
impl Display for ToplevelIdentifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)