1use std::ffi::{OsStr, OsString};
7use std::os::unix::ffi::OsStrExt;
8use std::path::PathBuf;
9
10pub trait ByteSize {
11 fn byte_size(&self) -> usize;
12}
13
14impl ByteSize for OsString {
15 fn byte_size(&self) -> usize {
16 self.as_bytes().len()
17 }
18}
19
20impl ByteSize for OsStr {
21 fn byte_size(&self) -> usize {
22 self.as_bytes().len()
23 }
24}
25
26impl ByteSize for PathBuf {
27 fn byte_size(&self) -> usize {
28 self.as_os_str().byte_size()
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 #[test]
37 fn test_os_string_empty() {
38 let os_str = OsStr::new("");
39 let os_string = OsString::from("");
40
41 assert_eq!(os_str.len(), 0);
42 assert_eq!(os_str.byte_size(), 0);
43 assert_eq!(os_string.len(), 0);
44 assert_eq!(os_string.byte_size(), 0);
45 }
46
47 #[test]
48 fn test_os_string_size() {
49 let os_str = OsStr::new("foo");
50 let os_string = OsString::from("foo");
51
52 assert_eq!(os_str.len(), 3);
53 assert_eq!(os_str.byte_size(), 3);
54 assert_eq!(os_string.len(), 3);
55 assert_eq!(os_string.byte_size(), 3);
56 }
57
58 #[test]
59 fn test_pathbuf_size() {
60 let mut path = PathBuf::new();
61
62 assert_eq!(path.byte_size(), 0);
63
64 path.push("/");
65 assert_eq!(path.byte_size(), 1);
66
67 path.push("test");
68 assert_eq!(path.byte_size(), 5);
69
70 path.push("a");
72 assert_eq!(path.byte_size(), 7);
73 }
74}