Skip to main content

paper_client/
value.rs

1/*
2 * Copyright (c) Kia Shakiba
3 *
4 * This source code is licensed under the GNU AGPLv3 license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::{
9	fmt::{self, Formatter},
10	str::{self, Utf8Error},
11	string::FromUtf8Error,
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.to_vec().into_boxed_slice();
25
26		PaperValue(buf)
27	}
28}
29
30impl From<Vec<u8>> for PaperValue {
31	fn from(value: Vec<u8>) -> Self {
32		PaperValue(value.into_boxed_slice())
33	}
34}
35
36impl From<&str> for PaperValue {
37	fn from(value: &str) -> Self {
38		let buf = value.as_bytes().to_vec().into_boxed_slice();
39
40		PaperValue(buf)
41	}
42}
43
44impl From<String> for PaperValue {
45	fn from(value: String) -> Self {
46		value.as_str().into()
47	}
48}
49
50impl From<&String> for PaperValue {
51	fn from(value: &String) -> Self {
52		value.as_str().into()
53	}
54}
55
56impl From<PaperValue> for Box<[u8]> {
57	fn from(value: PaperValue) -> Self {
58		value.0
59	}
60}
61
62impl<'a> From<&'a PaperValue> for &'a [u8] {
63	fn from(value: &'a PaperValue) -> Self {
64		&value.0
65	}
66}
67
68impl From<PaperValue> for Vec<u8> {
69	fn from(value: PaperValue) -> Self {
70		value.0.to_vec()
71	}
72}
73
74impl<'a> TryFrom<&'a PaperValue> for &'a str {
75	type Error = Utf8Error;
76
77	fn try_from(value: &'a PaperValue) -> Result<Self, Self::Error> {
78		str::from_utf8(&value.0)
79	}
80}
81
82impl TryFrom<PaperValue> for String {
83	type Error = FromUtf8Error;
84
85	fn try_from(value: PaperValue) -> Result<Self, Self::Error> {
86		String::from_utf8(value.0.to_vec())
87	}
88}
89
90impl fmt::Debug for PaperValue {
91	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
92		if self.0.len() > 16 {
93			return write!(f, "PaperValue(...)");
94		}
95
96		let value: Result<&str, Utf8Error> = self.try_into();
97
98		match value {
99			Ok(value) => write!(f, "PaperValue(\"{value}\")"),
100			Err(_) => write!(f, "PaperValue(...)"),
101		}
102	}
103}