Skip to main content

dfx_base/fields/converters/
string.rs

1use crate::field_map::FieldValue;
2use crate::fields::converters::TryFrom;
3use crate::fields::ConversionError;
4
5use super::IntoBytes;
6
7impl<'a> TryFrom<&'a FieldValue> for String {
8    type Error = ConversionError;
9
10    fn try_from(value: &'a FieldValue) -> Result<Self, Self::Error> {
11        Ok(value.iter().map(|b| *b as char).collect())
12    }
13}
14
15impl IntoBytes<FieldValue> for String {
16    fn as_bytes(&self) -> FieldValue {
17        self.clone().into_bytes().into()
18    }
19}
20
21impl<'a> TryFrom<&'a FieldValue> for &'a str {
22    type Error = ConversionError;
23
24    fn try_from(value: &'a FieldValue) -> Result<Self, Self::Error> {
25        // TODO encoding latin1
26        std::str::from_utf8(value).map_err(|_| ConversionError::EncodingError)
27    }
28}
29
30impl IntoBytes<FieldValue> for &&str {
31    fn as_bytes(&self) -> FieldValue {
32        let s: String = (**self).into();
33        s.into_bytes().into()
34    }
35}
36
37impl IntoBytes<FieldValue> for &str {
38    fn as_bytes(&self) -> FieldValue {
39        let s: String = (*self).into();
40        s.into_bytes().into()
41    }
42}
43
44impl IntoBytes<FieldValue> for &&String {
45    fn as_bytes(&self) -> FieldValue {
46        let s: String = (**self).into();
47        s.into_bytes().into()
48    }
49}
50
51impl IntoBytes<FieldValue> for &String {
52    fn as_bytes(&self) -> FieldValue {
53        let s: String = (*self).into();
54        s.into_bytes().into()
55    }
56}
57
58
59impl<'a> TryFrom<&'a FieldValue> for char {
60    type Error = ConversionError;
61
62    fn try_from(value: &'a FieldValue) -> Result<Self, Self::Error> {
63        if value.len() != 1 {
64            Err(ConversionError::EncodingError)
65        } else {
66            Ok(value[0] as char)
67        }
68    }
69}
70
71
72impl IntoBytes<FieldValue> for char {
73    fn as_bytes(&self) -> FieldValue {
74        vec!(*self as u8).into()
75    }
76}