Skip to content

Commit 9168a02

Browse files
authored
mcf: add PasswordHash::push_displayable (#2115)
Adds a method for pushing a field onto an MCF hash which impls the `fmt::Display` trait. The idea is it can eventually avoid an intermediate allocation as an optimization, although it uses one for now (with a TODO).
1 parent 07fa4bb commit 9168a02

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

mcf/src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ impl<'a> TryFrom<&'a str> for PasswordHashRef<'a> {
102102
#[cfg(feature = "alloc")]
103103
mod allocating {
104104
use crate::{Error, Field, Fields, PasswordHashRef, Result, fields, validate, validate_id};
105-
use alloc::string::String;
105+
use alloc::string::{String, ToString};
106106
use core::{fmt, str};
107107

108108
#[cfg(feature = "base64")]
@@ -181,6 +181,13 @@ mod allocating {
181181
self.0.push_str(&base64_encoding.encode_string(field));
182182
}
183183

184+
/// Push a type which impls [`fmt::Display`], first adding a `$` delimiter and ensuring the
185+
/// added characters comprise a valid field.
186+
pub fn push_displayable<D: fmt::Display>(&mut self, displayable: D) -> Result<()> {
187+
// TODO(tarcieri): avoid intermediate allocation?
188+
self.push_str(&displayable.to_string())
189+
}
190+
184191
/// Push an additional field onto the password hash string, first adding a `$` delimiter.
185192
pub fn push_field(&mut self, field: Field<'_>) {
186193
self.0.push(fields::DELIMITER);

mcf/tests/mcf.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,16 @@ fn parse_sha512_hash() {
7474

7575
#[cfg(feature = "base64")]
7676
#[test]
77-
fn push_fields() {
77+
fn push_base64() {
7878
let mut hash = PasswordHash::new("$6$rounds=100000").unwrap();
7979
hash.push_base64(EXAMPLE_SALT, Base64::ShaCrypt);
8080
hash.push_base64(EXAMPLE_HASH, Base64::ShaCrypt);
8181
assert_eq!(SHA512_HASH, hash.as_str());
8282
}
83+
84+
#[test]
85+
fn push_displayable() {
86+
let mut hash = PasswordHash::from_id("6").unwrap();
87+
hash.push_displayable("rounds=100000").unwrap();
88+
assert_eq!("$6$rounds=100000", hash.as_str());
89+
}

0 commit comments

Comments
 (0)