use std::fmt;
use serde::{Deserialize, Serialize};
use crate::error::{BlobError, Result};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct BlobId(String);
impl BlobId {
pub const MAX_LEN: usize = 200;
pub fn new(id: impl Into<String>) -> Result<Self> {
let id = id.into();
if Self::is_valid(&id) {
Ok(BlobId(id))
} else {
Err(BlobError::InvalidManifest(format!(
"id {id:?} is not a valid single key segment"
)))
}
}
#[must_use]
pub fn is_valid(id: &str) -> bool {
!id.is_empty()
&& id.len() <= Self::MAX_LEN
&& id != ".."
&& !id.starts_with('@')
&& !id.contains(['/', '\\', '*', '?', '#', '$'])
&& !id.chars().any(char::is_whitespace)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl std::ops::Deref for BlobId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for BlobId {
fn borrow(&self) -> &str {
&self.0
}
}
impl AsRef<str> for BlobId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for BlobId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for BlobId {
type Error = BlobError;
fn try_from(s: String) -> Result<Self> {
BlobId::new(s)
}
}
impl TryFrom<&str> for BlobId {
type Error = BlobError;
fn try_from(s: &str) -> Result<Self> {
BlobId::new(s)
}
}
impl std::str::FromStr for BlobId {
type Err = BlobError;
fn from_str(s: &str) -> Result<Self> {
BlobId::new(s)
}
}
impl From<BlobId> for String {
fn from(id: BlobId) -> String {
id.0
}
}
impl PartialEq<str> for BlobId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for BlobId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<BlobId> for str {
fn eq(&self, other: &BlobId) -> bool {
self == other.0
}
}
impl PartialEq<BlobId> for &str {
fn eq(&self, other: &BlobId) -> bool {
*self == other.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_ordinary_ids_and_refuses_key_breaking_ones() {
for good in ["a", "report-01", "01J8Z", "a.b_c", &"x".repeat(200)] {
assert!(BlobId::new(good).is_ok(), "{good:?} should be accepted");
}
for bad in [
"",
"..",
"@rpc",
"a/b",
"a\\b",
"a*",
"a?",
"a#b",
"a$b",
"a b",
"a\tb",
"a\nb",
&"x".repeat(201),
] {
assert!(BlobId::new(bad).is_err(), "{bad:?} should be refused");
}
}
#[test]
fn every_conversion_agrees_on_the_same_id() {
use std::str::FromStr;
let id = BlobId::new("report-01").unwrap();
assert_eq!(id.as_str(), "report-01");
assert_eq!(&*id, "report-01"); assert_eq!(id.as_ref() as &str, "report-01"); assert_eq!(id.to_string(), "report-01"); assert_eq!(format!("{id:?}"), "BlobId(\"report-01\")");
assert_eq!(String::from(id.clone()), "report-01");
assert_eq!(id.clone().into_string(), "report-01");
assert_eq!(BlobId::try_from("report-01").unwrap(), id);
assert_eq!(BlobId::try_from(String::from("report-01")).unwrap(), id);
assert_eq!(BlobId::from_str("report-01").unwrap(), id);
assert_eq!("report-01".parse::<BlobId>().unwrap(), id);
assert!(BlobId::try_from("bad/id").is_err());
assert!("bad/id".parse::<BlobId>().is_err());
assert!(id == "report-01");
assert!(id == *"report-01");
assert!("report-01" == id);
assert!(*"report-01" == id);
assert!(id != "other");
let mut map = std::collections::HashMap::new();
map.insert(id.clone(), 7);
assert_eq!(map.get("report-01"), Some(&7));
assert_eq!(map.get("nope"), None);
let mut v = [
BlobId::new("c").unwrap(),
BlobId::new("a").unwrap(),
BlobId::new("b").unwrap(),
];
v.sort();
assert_eq!(
v.iter().map(BlobId::as_str).collect::<Vec<_>>(),
["a", "b", "c"]
);
}
#[test]
fn decoding_refuses_an_id_that_would_break_a_key() {
let hostile = crate::wire::encode(&String::from("blob/../@evil")).unwrap();
assert!(crate::wire::decode::<BlobId>(&hostile).is_err());
let honest = crate::wire::encode(&String::from("blob-1")).unwrap();
assert_eq!(
crate::wire::decode::<BlobId>(&honest).unwrap().as_str(),
"blob-1"
);
}
#[test]
fn encodes_exactly_as_the_string_it_replaced() {
let id = BlobId::new("report-01").unwrap();
assert_eq!(
crate::wire::encode(&id).unwrap(),
crate::wire::encode(&String::from("report-01")).unwrap()
);
}
}