1use core::str;
4
5use thiserror::Error;
6
7use crate::error::RetryableStorageError;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Key {
15 pub dir: Vec<Vec<u8>>,
17 pub key: Vec<u8>,
19}
20
21#[derive(Debug, Error, PartialEq, Eq)]
26pub enum KeyError {
27 #[error("directory segment {segment} is not valid UTF-8")]
33 DirSegmentNotUtf8 {
34 segment: usize,
36 },
37 #[error("the root directory cannot be removed")]
39 RootNotRemovable,
40}
41
42impl RetryableStorageError for KeyError {
43 fn is_retryable(&self) -> bool {
44 false
45 }
46}
47
48pub fn validate_dir(dir: &[&[u8]]) -> Result<(), KeyError> {
54 for (i, seg) in dir.iter().enumerate() {
55 if str::from_utf8(seg).is_err() {
56 return Err(KeyError::DirSegmentNotUtf8 { segment: i });
57 }
58 }
59 Ok(())
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
68 use proptest::prelude::*;
69
70 #[test]
71 fn validate_dir_accepts_utf8_and_empty() {
72 assert!(validate_dir(&[]).is_ok());
73 assert!(validate_dir(&[b"", b"asset", b"btc"]).is_ok());
74 assert!(validate_dir(&["€".as_bytes()]).is_ok());
76 }
77
78 #[test]
79 fn validate_dir_rejects_non_utf8_with_index() {
80 assert_eq!(
81 validate_dir(&[b"ok", b"\xFF\xFE"]),
82 Err(KeyError::DirSegmentNotUtf8 { segment: 1 })
83 );
84 assert_eq!(
85 validate_dir(&[b"\x00\xFF"]),
86 Err(KeyError::DirSegmentNotUtf8 { segment: 0 })
87 );
88 }
89
90 #[test]
91 fn key_error_is_not_retryable() {
92 assert!(!KeyError::RootNotRemovable.is_retryable());
93 assert!(!KeyError::DirSegmentNotUtf8 { segment: 0 }.is_retryable());
94 }
95
96 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
97 proptest! {
98 #[test]
99 fn prop_validate_dir_matches_str_from_utf8(
100 dir in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..8), 0..4),
101 ) {
102 let slices: Vec<&[u8]> = dir.iter().map(|v| v.as_slice()).collect();
103 let expected: Option<usize> =
104 dir.iter().position(|seg| str::from_utf8(seg).is_err());
105 match (validate_dir(&slices), expected) {
106 (Ok(()), None) => {}
107 (Err(KeyError::DirSegmentNotUtf8 { segment }), Some(i)) => {
108 prop_assert_eq!(segment, i);
109 }
110 (other, _) => prop_assert!(false, "unexpected answer: {other:?}"),
111 }
112 }
113 }
114}