1use std::{
9 string::FromUtf8Error,
10 str::{self, Utf8Error},
11 fmt::{self, Formatter},
12};
13
14pub struct PaperValue(Box<[u8]>);
15
16impl From<Box<[u8]>> for PaperValue {
17 fn from(value: Box<[u8]>) -> Self {
18 PaperValue(value)
19 }
20}
21
22impl From<&[u8]> for PaperValue {
23 fn from(value: &[u8]) -> Self {
24 let buf = value
25 .to_vec()
26 .into_boxed_slice();
27
28 PaperValue(buf)
29 }
30}
31
32impl From<Vec<u8>> for PaperValue {
33 fn from(value: Vec<u8>) -> Self {
34 PaperValue(value.into_boxed_slice())
35 }
36}
37
38impl From<&str> for PaperValue {
39 fn from(value: &str) -> Self {
40 let buf = value
41 .as_bytes()
42 .to_vec()
43 .into_boxed_slice();
44
45 PaperValue(buf)
46 }
47}
48
49impl From<String> for PaperValue {
50 fn from(value: String) -> Self {
51 value.as_str().into()
52 }
53}
54
55impl From<&String> for PaperValue {
56 fn from(value: &String) -> Self {
57 value.as_str().into()
58 }
59}
60
61impl From<PaperValue> for Box<[u8]> {
62 fn from(value: PaperValue) -> Self {
63 value.0
64 }
65}
66
67impl<'a> From<&'a PaperValue> for &'a [u8] {
68 fn from(value: &'a PaperValue) -> Self {
69 &value.0
70 }
71}
72
73impl From<PaperValue> for Vec<u8> {
74 fn from(value: PaperValue) -> Self {
75 value.0.to_vec()
76 }
77}
78
79impl<'a> TryFrom<&'a PaperValue> for &'a str {
80 type Error = Utf8Error;
81
82 fn try_from(value: &'a PaperValue) -> Result<Self, Self::Error> {
83 str::from_utf8(&value.0)
84 }
85}
86
87impl TryFrom<PaperValue> for String {
88 type Error = FromUtf8Error;
89
90 fn try_from(value: PaperValue) -> Result<Self, Self::Error> {
91 String::from_utf8(value.0.to_vec())
92 }
93}
94
95impl fmt::Debug for PaperValue {
96 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
97 if self.0.len() > 16 {
98 return write!(f, "PaperValue(...)");
99 }
100
101 let value: Result<&str, Utf8Error> = self.try_into();
102
103 match value {
104 Ok(value) => write!(f, "PaperValue(\"{value}\")"),
105 Err(_) => write!(f, "PaperValue(...)"),
106 }
107 }
108}