1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! A TinyChain String

use std::cmp::Ordering;
use std::fmt;
use std::mem::size_of;
use std::sync::Arc;

use async_trait::async_trait;
use base64::engine::general_purpose::STANDARD_NO_PAD;
use base64::Engine;
use bytes::Bytes;
use collate::{Collate, Collator};
use destream::{de, en};
use futures::TryFutureExt;
use get_size::GetSize;
use handlebars::Handlebars;
use safecast::TryCastFrom;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::json;

use tc_error::*;
use tcgeneric::Id;

use super::{Link, Number};

/// A TinyChain String
#[derive(Clone, Eq, PartialEq)]
pub struct TCString(Arc<str>);

impl GetSize for TCString {
    fn get_size(&self) -> usize {
        size_of::<Arc<str>>() + self.0.as_bytes().len()
    }
}

impl Default for TCString {
    fn default() -> Self {
        Self::from(String::default())
    }
}

impl TCString {
    /// Render this string as a [`Handlebars`] template with the given `data`.
    ///
    /// Example:
    /// ```
    /// # use std::collections::HashMap;
    /// # use tc_value::TCString;
    /// let data: HashMap<_, _> = std::iter::once(("name", "world")).collect();
    /// assert_eq!(
    ///     TCString::from("Hello, {{name}}!".to_string()).render(data).unwrap().as_str(),
    ///     "Hello, world!");
    /// ```
    ///
    /// See the [`handlebars`] documentation for a complete description of the formatting options.
    pub fn render<T: Serialize>(&self, data: T) -> TCResult<TCString> {
        Handlebars::new()
            .render_template(self.0.as_ref(), &json!(data))
            .map(Self::from)
            .map_err(|cause| bad_request!("template render error").consume(cause))
    }

    /// Borrow this [`TCString`] as a `str`.
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

impl PartialEq<Id> for TCString {
    fn eq(&self, other: &Id) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<String> for TCString {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<str> for TCString {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl From<String> for TCString {
    fn from(s: String) -> Self {
        Self(s.into())
    }
}

impl From<Id> for TCString {
    fn from(id: Id) -> Self {
        Self(id.into_inner())
    }
}

impl From<Link> for TCString {
    fn from(link: Link) -> Self {
        Self::from(link.to_string())
    }
}

impl From<Number> for TCString {
    fn from(n: Number) -> Self {
        Self::from(n.to_string())
    }
}

impl TryCastFrom<TCString> for Bytes {
    fn can_cast_from(value: &TCString) -> bool {
        if value.as_str().ends_with('=') {
            STANDARD_NO_PAD.decode(value.as_str()).is_ok()
        } else {
            hex::decode(value.as_str()).is_ok()
        }
    }

    fn opt_cast_from(value: TCString) -> Option<Self> {
        if value.as_str().ends_with('=') {
            STANDARD_NO_PAD.decode(value.as_str()).ok().map(Self::from)
        } else {
            hex::decode(value.as_str()).ok().map(Self::from)
        }
    }
}

#[async_trait]
impl de::FromStream for TCString {
    type Context = ();

    async fn from_stream<D: de::Decoder>(cxt: (), decoder: &mut D) -> Result<Self, D::Error> {
        String::from_stream(cxt, decoder).map_ok(Self::from).await
    }
}

impl<'en> en::IntoStream<'en> for TCString {
    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
        encoder.encode_str(self.as_str())
    }
}

impl<'en> en::ToStream<'en> for TCString {
    fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
        encoder.encode_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TCString {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer).map(Self::from)
    }
}

impl Serialize for TCString {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(serializer)
    }
}

impl fmt::Debug for TCString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Display for TCString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A [`Collator`] for [`TCString`] values.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct StringCollator {
    collator: Collator<Arc<str>>,
}

impl Collate for StringCollator {
    type Value = TCString;

    fn cmp(&self, left: &Self::Value, right: &Self::Value) -> Ordering {
        self.collator.cmp(&left.0, &right.0)
    }
}