evobench_tools/key_val_fs/as_key.rs
1use std::borrow::Cow;
2
3/// A type that can be used as the key (i.e. converted to a file name)
4/// in a `KeyVal` database.
5pub trait AsKey: Sized {
6 /// Types implementing this trait can't have failing conversions!
7 /// If you want to use a key type with a fallible conversion, it
8 /// must have a conversion to a custom type that implements AsKey,
9 /// and *that* conversion will need to be fallible. The result
10 /// must never start with a `.` (leading dot is used for temporary
11 /// files), or contain the `/` or `\0` characters, must be at
12 /// least 1 and at most 254 bytes long, and *should* never contain
13 /// control characters (this could make it a pain for people to
14 /// use command line tools to work with the databases).
15 fn as_filename_str(&self) -> Cow<'_, str>;
16
17 /// Calls `as_filename_str` and asserts that the result complies
18 /// to the rules mentioned above, panics if it does not.
19 fn verified_as_filename_str(&self) -> Cow<'_, str> {
20 let s = self.as_filename_str();
21 let bytes = s.as_bytes();
22 assert!(bytes.len() <= 254);
23 assert!(bytes.len() >= 1);
24 assert!(bytes[0] != b'.');
25 assert!(!bytes.contains(&b'/'));
26 assert!(!bytes.contains(&b'\0'));
27 s
28 }
29
30 /// Must convert the output of `as_filename_str` back into a Self
31 /// equal to the original self. If not possible (e.g. a human
32 /// placed an invalid file), return None.
33 fn try_from_filename_str(file_name: &str) -> Option<Self>;
34}