1use std::collections::HashMap;
2
3use crate::cbor;
4
5#[derive(Debug, Clone)]
12pub enum LocalizedString {
13 Plain(String),
15 Localized(HashMap<String, String>),
17}
18
19impl Default for LocalizedString {
20 fn default() -> Self {
21 Self::Plain(String::new())
22 }
23}
24
25impl LocalizedString {
26 pub fn plain(text: impl Into<String>) -> Self {
28 Self::Plain(text.into())
29 }
30
31 pub fn new(lang: impl Into<String>, text: impl Into<String>) -> Self {
33 let mut map = HashMap::new();
34 map.insert(lang.into(), text.into());
35 Self::Localized(map)
36 }
37
38 pub fn get(&self, lang: &str) -> Option<&str> {
43 match self {
44 Self::Plain(text) => Some(text.as_str()),
45 Self::Localized(map) => map.get(lang).map(|s| s.as_str()),
46 }
47 }
48
49 pub fn resolve(&self, lang: &str) -> &str {
54 match self {
55 Self::Plain(text) => text.as_str(),
56 Self::Localized(map) => {
57 if let Some(text) = map.get(lang) {
59 return text.as_str();
60 }
61 if let Some(text) = map
63 .iter()
64 .find(|(tag, _)| tag.starts_with(lang) || lang.starts_with(tag.as_str()))
65 .map(|(_, text)| text.as_str())
66 {
67 return text;
68 }
69 map.values().next().map(|s| s.as_str()).unwrap_or("")
71 }
72 }
73 }
74
75 pub fn any_text(&self) -> &str {
78 match self {
79 Self::Plain(text) => text.as_str(),
80 Self::Localized(map) => map.values().next().map(|s| s.as_str()).unwrap_or(""),
81 }
82 }
83}
84
85impl From<String> for LocalizedString {
86 fn from(s: String) -> Self {
87 Self::Plain(s)
88 }
89}
90
91impl From<&str> for LocalizedString {
92 fn from(s: &str) -> Self {
93 Self::Plain(s.to_string())
94 }
95}
96
97impl From<Vec<(String, String)>> for LocalizedString {
98 fn from(v: Vec<(String, String)>) -> Self {
99 Self::Localized(v.into_iter().collect())
100 }
101}
102
103impl From<HashMap<String, String>> for LocalizedString {
104 fn from(map: HashMap<String, String>) -> Self {
105 Self::Localized(map)
106 }
107}
108
109#[derive(Debug, Clone, Default)]
115pub struct Metadata(HashMap<String, serde_json::Value>);
116
117impl Metadata {
118 pub fn new() -> Self {
119 Self(HashMap::new())
120 }
121
122 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
124 self.0.insert(key.into(), value.into());
125 }
126
127 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
129 self.0.get(key)
130 }
131
132 pub fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
134 self.0
135 .get(key)
136 .and_then(|v| serde_json::from_value(v.clone()).ok())
137 }
138
139 pub fn contains_key(&self, key: &str) -> bool {
141 self.0.contains_key(key)
142 }
143
144 pub fn is_empty(&self) -> bool {
146 self.0.is_empty()
147 }
148
149 pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
151 self.0.iter()
152 }
153
154 pub fn to_json(&self) -> Option<serde_json::Value> {
156 if self.0.is_empty() {
157 return None;
158 }
159 let map: serde_json::Map<String, serde_json::Value> =
160 self.0.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
161 Some(serde_json::Value::Object(map))
162 }
163}
164
165impl From<Vec<(String, Vec<u8>)>> for Metadata {
167 fn from(v: Vec<(String, Vec<u8>)>) -> Self {
168 Self(
169 v.into_iter()
170 .filter_map(|(k, cbor_bytes)| {
171 let val = cbor::cbor_to_json(&cbor_bytes).ok()?;
172 Some((k, val))
173 })
174 .collect(),
175 )
176 }
177}
178
179impl From<Metadata> for Vec<(String, Vec<u8>)> {
181 fn from(m: Metadata) -> Self {
182 m.0.into_iter()
183 .map(|(k, v)| (k, cbor::to_cbor(&v)))
184 .collect()
185 }
186}
187
188macro_rules! cbor_wrapper {
192 ($(#[$meta:meta])* $name:ident) => {
193 $(#[$meta])*
194 #[derive(Debug, Clone)]
195 pub struct $name(Vec<u8>);
196
197 impl $name {
198 pub fn from_json(value: &serde_json::Value) -> Result<Self, cbor::CborError> {
200 cbor::json_to_cbor(value).map(Self)
201 }
202
203 pub fn from_json_opt(value: &Option<serde_json::Value>) -> Result<Option<Self>, cbor::CborError> {
205 match value {
206 Some(val) => Self::from_json(val).map(Some),
207 None => Ok(None),
208 }
209 }
210
211 pub fn as_bytes(&self) -> &[u8] {
213 &self.0
214 }
215
216 pub fn to_json(&self) -> Result<serde_json::Value, cbor::CborError> {
218 cbor::cbor_to_json(&self.0)
219 }
220
221 pub fn deserialize<T: serde::de::DeserializeOwned>(&self) -> Result<T, cbor::CborError> {
223 cbor::from_cbor(&self.0)
224 }
225 }
226
227 impl From<Vec<u8>> for $name {
228 fn from(v: Vec<u8>) -> Self {
229 Self(v)
230 }
231 }
232
233 impl From<$name> for Vec<u8> {
234 fn from(w: $name) -> Self {
235 w.0
236 }
237 }
238 };
239}
240
241cbor_wrapper!(
242 Args
244);
245
246use crate::constants::*;
247
248#[derive(Debug, Clone)]
252pub struct ActError {
253 pub kind: String,
254 pub message: String,
255}
256
257impl ActError {
258 pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
259 Self {
260 kind: kind.into(),
261 message: message.into(),
262 }
263 }
264
265 pub fn not_found(message: impl Into<String>) -> Self {
266 Self::new(ERR_NOT_FOUND, message)
267 }
268
269 pub fn invalid_args(message: impl Into<String>) -> Self {
270 Self::new(ERR_INVALID_ARGS, message)
271 }
272
273 pub fn internal(message: impl Into<String>) -> Self {
274 Self::new(ERR_INTERNAL, message)
275 }
276
277 pub fn timeout(message: impl Into<String>) -> Self {
278 Self::new(ERR_TIMEOUT, message)
279 }
280
281 pub fn capability_denied(message: impl Into<String>) -> Self {
282 Self::new(ERR_CAPABILITY_DENIED, message)
283 }
284}
285
286impl std::fmt::Display for ActError {
287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288 write!(f, "{}: {}", self.kind, self.message)
289 }
290}
291
292impl std::error::Error for ActError {}
293
294pub type ActResult<T> = Result<T, ActError>;
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300 use serde_json::json;
301
302 #[test]
303 fn localized_string_plain() {
304 let ls = LocalizedString::plain("hello");
305 assert_eq!(ls.resolve("en"), "hello");
306 assert_eq!(ls.any_text(), "hello");
307 }
308
309 #[test]
310 fn localized_string_from_str() {
311 let ls = LocalizedString::from("hello");
312 assert_eq!(ls.any_text(), "hello");
313 }
314
315 #[test]
316 fn localized_string_default() {
317 let ls = LocalizedString::default();
318 assert_eq!(ls.any_text(), "");
319 }
320
321 #[test]
322 fn localized_string_resolve_by_lang() {
323 let mut map = std::collections::HashMap::new();
324 map.insert("en".to_string(), "hello".to_string());
325 map.insert("ru".to_string(), "привет".to_string());
326 let ls = LocalizedString::Localized(map);
327 assert_eq!(ls.resolve("ru"), "привет");
328 assert_eq!(ls.resolve("en"), "hello");
329 assert!(!ls.resolve("fr").is_empty());
331 }
332
333 #[test]
334 fn localized_string_resolve_prefix() {
335 let mut map = HashMap::new();
336 map.insert("zh-Hans".to_string(), "你好".to_string());
337 map.insert("en".to_string(), "hello".to_string());
338 let ls = LocalizedString::Localized(map);
339 assert_eq!(ls.resolve("zh"), "你好");
340 }
341
342 #[test]
343 fn localized_string_get() {
344 let ls = LocalizedString::new("en", "hello");
345 assert_eq!(ls.get("en"), Some("hello"));
346 assert_eq!(ls.get("ru"), None);
347 }
348
349 #[test]
350 fn localized_string_from_vec() {
351 let v = vec![("en".to_string(), "hi".to_string())];
352 let ls = LocalizedString::from(v);
353 assert_eq!(ls.resolve("en"), "hi");
354 }
355
356 #[test]
357 fn metadata_insert_and_get() {
358 let mut m = Metadata::new();
359 m.insert("std:read-only", true);
360 assert_eq!(m.get("std:read-only"), Some(&json!(true)));
361 assert_eq!(m.get_as::<bool>("std:read-only"), Some(true));
362 }
363
364 #[test]
365 fn metadata_to_json_empty() {
366 assert!(Metadata::new().to_json().is_none());
367 }
368
369 #[test]
370 fn metadata_to_json_with_values() {
371 let mut m = Metadata::new();
372 m.insert("std:read-only", true);
373 let json = m.to_json().unwrap();
374 assert_eq!(json["std:read-only"], json!(true));
375 }
376
377 #[test]
378 fn metadata_from_vec() {
379 let v = vec![("key".to_string(), cbor::to_cbor(&42u32))];
380 let m = Metadata::from(v);
381 assert_eq!(m.get("key"), Some(&json!(42)));
382 assert_eq!(m.get_as::<u32>("key"), Some(42));
383 }
384
385 #[test]
386 fn args_from_json_roundtrip() {
387 let val = json!({"code": "2+2"});
388 let args = Args::from_json(&val).unwrap();
389 let decoded = args.to_json().unwrap();
390 assert_eq!(val, decoded);
391 }
392
393 #[test]
394 fn args_deserialize_typed() {
395 #[derive(serde::Deserialize, PartialEq, Debug)]
396 struct Params {
397 code: String,
398 }
399 let val = json!({"code": "hello"});
400 let args = Args::from_json(&val).unwrap();
401 let params: Params = args.deserialize().unwrap();
402 assert_eq!(params.code, "hello");
403 }
404}