use core::str;
use thiserror::Error;
use crate::error::RetryableStorageError;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Key {
pub dir: Vec<Vec<u8>>,
pub key: Vec<u8>,
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum KeyError {
#[error("directory segment {segment} is not valid UTF-8")]
DirSegmentNotUtf8 {
segment: usize,
},
#[error("the root directory cannot be removed")]
RootNotRemovable,
}
impl RetryableStorageError for KeyError {
fn is_retryable(&self) -> bool {
false
}
}
pub fn validate_dir(dir: &[&[u8]]) -> Result<(), KeyError> {
for (i, seg) in dir.iter().enumerate() {
if str::from_utf8(seg).is_err() {
return Err(KeyError::DirSegmentNotUtf8 { segment: i });
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use proptest::prelude::*;
#[test]
fn validate_dir_accepts_utf8_and_empty() {
assert!(validate_dir(&[]).is_ok());
assert!(validate_dir(&[b"", b"asset", b"btc"]).is_ok());
assert!(validate_dir(&["€".as_bytes()]).is_ok());
}
#[test]
fn validate_dir_rejects_non_utf8_with_index() {
assert_eq!(
validate_dir(&[b"ok", b"\xFF\xFE"]),
Err(KeyError::DirSegmentNotUtf8 { segment: 1 })
);
assert_eq!(
validate_dir(&[b"\x00\xFF"]),
Err(KeyError::DirSegmentNotUtf8 { segment: 0 })
);
}
#[test]
fn key_error_is_not_retryable() {
assert!(!KeyError::RootNotRemovable.is_retryable());
assert!(!KeyError::DirSegmentNotUtf8 { segment: 0 }.is_retryable());
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
proptest! {
#[test]
fn prop_validate_dir_matches_str_from_utf8(
dir in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..8), 0..4),
) {
let slices: Vec<&[u8]> = dir.iter().map(|v| v.as_slice()).collect();
let expected: Option<usize> =
dir.iter().position(|seg| str::from_utf8(seg).is_err());
match (validate_dir(&slices), expected) {
(Ok(()), None) => {}
(Err(KeyError::DirSegmentNotUtf8 { segment }), Some(i)) => {
prop_assert_eq!(segment, i);
}
(other, _) => prop_assert!(false, "unexpected answer: {other:?}"),
}
}
}
}