cyfs_base/codec/
json_codec.rs

1use crate::*;
2use serde_json::{Map, Value};
3
4use serde::{Deserialize, Serialize};
5use std::convert::TryFrom;
6use std::str::FromStr;
7
8pub trait JsonCodec<T> {
9    fn encode_json(&self) -> Map<String, Value> {
10        unimplemented!();
11    }
12    fn decode_json(_obj: &Map<String, Value>) -> BuckyResult<T> {
13        unimplemented!();
14    }
15
16    fn encode_string(&self) -> String {
17        self.encode_value().to_string()
18    }
19
20    fn decode_string(value: &str) -> BuckyResult<T> {
21        let value: Value = serde_json::from_str(value).map_err(|e| {
22            error!("invalid json buf str: {} {}", value, e);
23            BuckyError::from(BuckyErrorCode::InvalidFormat)
24        })?;
25
26        Self::decode_value(&value)
27    }
28
29    fn decode_value(value: &Value) -> BuckyResult<T> {
30        let obj = value.as_object().ok_or_else(|| {
31            let msg = format!("invalid json object format: {}", value);
32            error!("{}", msg);
33            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
34        })?;
35
36        Self::decode_json(obj)
37    }
38
39    fn encode_value(&self) -> Value {
40        JsonCodecHelper::encode_value(self.encode_json())
41    }
42}
43
44pub trait JsonCodecAutoWithSerde {}
45
46impl<T> JsonCodec<T> for T
47where
48    T: Serialize + for<'d> Deserialize<'d> + JsonCodecAutoWithSerde,
49{
50    fn encode_json(&self) -> Map<String, Value> {
51        unimplemented!();
52    }
53
54    fn decode_json(_obj: &Map<String, Value>) -> BuckyResult<T> {
55        unimplemented!();
56    }
57
58    fn encode_value(&self) -> Value {
59        serde_json::to_value(self).unwrap()
60    }
61
62    fn decode_value(obj: &Value) -> BuckyResult<T> {
63        T::deserialize(obj).map_err(|e| {
64            let msg = format!("decode from json error! {:?}, {}", obj, e);
65            error!("{}", msg);
66            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
67        })
68    }
69}
70
71pub struct JsonCodecHelper;
72
73impl JsonCodecHelper {
74    // None在js里面会编码成{},如果不是使用serde_json的解码,而是手工操作,这里需要对这种情况加以判断
75    pub fn is_none_node(node: &Value) -> bool {
76        match node.is_object() {
77            true => node.as_object().unwrap().is_empty(),
78            false => false,
79        }
80    }
81
82    pub fn encode_string(obj: Map<String, Value>) -> String {
83        Self::encode_value(obj).to_string()
84    }
85
86    pub fn encode_value(obj: Map<String, Value>) -> Value {
87        Value::Object(obj)
88    }
89
90    pub fn encode_string_field<T: ?Sized>(
91        obj: &mut Map<String, Value>,
92        key: impl ToString,
93        value: &T,
94    ) where
95        T: ToString,
96    {
97        obj.insert(key.to_string(), Value::String(value.to_string()));
98    }
99
100    pub fn encode_string_field_2(
101        obj: &mut Map<String, Value>,
102        key: impl ToString,
103        value: impl ToString,
104    ) {
105        obj.insert(key.to_string(), Value::String(value.to_string()));
106    }
107
108    pub fn encode_option_string_field<T: ?Sized>(
109        obj: &mut Map<String, Value>,
110        key: impl ToString,
111        value: Option<&T>,
112    ) where
113        T: ToString,
114    {
115        if let Some(value) = value {
116            obj.insert(key.to_string(), Value::String(value.to_string()));
117        }
118    }
119
120    pub fn encode_number_field<T>(obj: &mut Map<String, Value>, key: impl ToString, value: T)
121    where
122        T: Into<serde_json::Number>,
123    {
124        obj.insert(key.to_string(), Value::Number(value.into()));
125    }
126
127    pub fn encode_bool_field(obj: &mut Map<String, Value>, key: impl ToString, value: bool) {
128        obj.insert(key.to_string(), Value::Bool(value));
129    }
130
131    pub fn encode_option_number_field<T>(
132        obj: &mut Map<String, Value>,
133        key: impl ToString,
134        value: Option<T>,
135    ) where
136        T: Into<serde_json::Number>,
137    {
138        if let Some(value) = value {
139            obj.insert(key.to_string(), Value::Number(value.into()));
140        }
141    }
142
143    pub fn decode_string_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<T>
144    where
145        T: FromStr,
146        <T as FromStr>::Err: std::fmt::Display,
147    {
148        let v = obj.get(key).ok_or_else(|| {
149            let msg = format!("field not found: {}", key);
150            warn!("{}", msg);
151
152            BuckyError::new(BuckyErrorCode::NotFound, msg)
153        })?;
154
155        Self::decode_from_string(v)
156    }
157
158    pub fn decode_option_string_field<T>(
159        obj: &Map<String, Value>,
160        key: &str,
161    ) -> BuckyResult<Option<T>>
162    where
163        T: FromStr,
164        <T as FromStr>::Err: std::fmt::Display,
165    {
166        match obj.get(key) {
167            Some(v) => {
168                let obj = Self::decode_from_string(v)?;
169                Ok(Some(obj))
170            }
171            None => Ok(None),
172        }
173    }
174
175    pub fn decode_serde_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<T>
176    where
177    T: for<'a> serde::de::Deserialize<'a>,
178    {
179        let v = obj.get(key).ok_or_else(|| {
180            let msg = format!("field not found: {}", key);
181            warn!("{}", msg);
182
183            BuckyError::new(BuckyErrorCode::NotFound, msg)
184        })?;
185
186        <T as Deserialize>::deserialize(v).map_err(|e| {
187            let msg = format!("decode field with serde failed!: key={}, value={:?}, {}", key, v, e);
188            warn!("{}", msg);
189
190            BuckyError::new(BuckyErrorCode::InvalidData, msg)
191        })
192    }
193
194    pub fn decode_option_serde_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Option<T>>
195    where
196    T: for<'a> serde::de::Deserialize<'a>,
197    {
198        match obj.get(key) {
199            Some(v) => {
200                let ret = <T as Deserialize>::deserialize(v).map_err(|e| {
201                    let msg = format!("decode field with serde failed!: key={}, value={:?}, {}", key, v, e);
202                    warn!("{}", msg);
203        
204                    BuckyError::new(BuckyErrorCode::InvalidData, msg)
205                })?;
206                Ok(Some(ret))
207            }
208            None => Ok(None)
209        }
210    }
211
212    pub fn decode_int_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<T>
213    where
214        T: FromStr + TryFrom<u64> + TryFrom<i64>,
215        <T as FromStr>::Err: std::fmt::Display,
216        <T as TryFrom<u64>>::Error: std::fmt::Display,
217        <T as TryFrom<i64>>::Error: std::fmt::Display,
218    {
219        let v = obj.get(key).ok_or_else(|| {
220            let msg = format!("field not found: {}", key);
221            warn!("{}", msg);
222
223            BuckyError::new(BuckyErrorCode::NotFound, msg)
224        })?;
225
226        Self::decode_to_int(v)
227    }
228
229    pub fn decode_option_int_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Option<T>>
230    where
231        T: FromStr + TryFrom<u64> + TryFrom<i64>,
232        <T as FromStr>::Err: std::fmt::Display,
233        <T as TryFrom<u64>>::Error: std::fmt::Display,
234        <T as TryFrom<i64>>::Error: std::fmt::Display,
235    {
236        match obj.get(key) {
237            Some(v) => {
238                let obj = Self::decode_to_int(v)?;
239                Ok(Some(obj))
240            }
241            None => Ok(None),
242        }
243    }
244
245    pub fn decode_to_int<T>(v: &Value) -> BuckyResult<T>
246    where
247        T: FromStr + TryFrom<u64> + TryFrom<i64>,
248        <T as FromStr>::Err: std::fmt::Display,
249        <T as TryFrom<u64>>::Error: std::fmt::Display,
250        <T as TryFrom<i64>>::Error: std::fmt::Display,
251    {
252        if v.is_string() {
253            let v = T::from_str(v.as_str().unwrap()).map_err(|e| {
254                let msg = format!(
255                    "parse json string to int error: value={}, {}",
256                    v.as_str().unwrap(),
257                    e
258                );
259                warn!("{}", msg);
260                BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
261            })?;
262
263            Ok(v)
264        } else if v.is_number() {
265            if v.is_i64() {
266                let v = T::try_from(v.as_i64().unwrap()).map_err(|e| {
267                    let msg = format!(
268                        "parse json number to int error: value={}, {}",
269                        v.as_i64().unwrap(),
270                        e
271                    );
272                    warn!("{}", msg);
273                    BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
274                })?;
275                Ok(v)
276            } else if v.is_u64() {
277                let v = T::try_from(v.as_u64().unwrap()).map_err(|e| {
278                    let msg = format!(
279                        "parse json number to int error: value={}, {}",
280                        v.as_u64().unwrap(),
281                        e
282                    );
283                    warn!("{}", msg);
284                    BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
285                })?;
286                Ok(v)
287            } else {
288                let msg = format!(
289                    "parse json float number to int error: value={}",
290                    v.as_u64().unwrap(),
291                );
292                warn!("{}", msg);
293                Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg))
294            }
295        } else {
296            let msg = format!("invalid json field, except string or number: {}", v);
297            warn!("{}", msg);
298
299            Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg))
300        }
301    }
302
303    pub fn decode_from_serde_string<T>(v: &Value) -> BuckyResult<T>
304    where
305        T: for<'a> serde::de::Deserialize<'a>,
306    {
307        if !v.is_string() {
308            let msg = format!("invalid json field, except string: {}", v);
309            warn!("{}", msg);
310
311            return Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg));
312        }
313
314        let v = serde_json::from_str(v.as_str().unwrap()).map_err(|e| {
315            let msg = format!(
316                "parse json string error: value={}, {}",
317                v.as_str().unwrap(),
318                e
319            );
320            warn!("{}", msg);
321
322            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
323        })?;
324
325        Ok(v)
326    }
327
328    pub fn decode_from_string<T>(v: &Value) -> BuckyResult<T>
329    where
330        T: FromStr,
331        <T as FromStr>::Err: std::fmt::Display,
332    {
333        if !v.is_string() {
334            let msg = format!("invalid json field, except string: {}", v);
335            warn!("{}", msg);
336
337            return Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg));
338        }
339
340        let v = T::from_str(v.as_str().unwrap()).map_err(|e| {
341            let msg = format!(
342                "parse json string error: value={}, {}",
343                v.as_str().unwrap(),
344                e
345            );
346            warn!("{}", msg);
347
348            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
349        })?;
350
351        Ok(v)
352    }
353
354    pub fn decode_bool_field(obj: &Map<String, Value>, key: &str) -> BuckyResult<bool> {
355        let v = obj.get(key).ok_or_else(|| {
356            let msg = format!("field not found: {}", key);
357            warn!("{}", msg);
358
359            BuckyError::new(BuckyErrorCode::NotFound, msg)
360        })?;
361
362        Self::decode_from_boolean(v)
363    }
364
365    pub fn decode_object_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<T>
366    where
367        T: for<'de> RawFrom<'de, T>,
368    {
369        let v = obj.get(key).ok_or_else(|| {
370            let msg = format!("field not found: {}", key);
371            warn!("{}", msg);
372
373            BuckyError::new(BuckyErrorCode::NotFound, msg)
374        })?;
375
376        Self::decode_object_from_string(v)
377    }
378
379    pub fn decode_object_from_string<T>(v: &Value) -> BuckyResult<T>
380    where
381        T: for<'de> RawFrom<'de, T>,
382        //<T as FromStr>::Err: std::fmt::Display,
383    {
384        if !v.is_string() {
385            let msg = format!("invalid json field, except string: {}", v);
386            warn!("{}", msg);
387
388            return Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg));
389        }
390
391        let buf = hex::decode(v.as_str().unwrap()).map_err(|e| {
392            let msg = format!(
393                "parse object hex string error: value={}, {}",
394                v.as_str().unwrap(),
395                e
396            );
397            warn!("{}", msg);
398
399            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
400        })?;
401
402        let v = T::clone_from_slice(&buf).map_err(|e| {
403            let msg = format!(
404                "decode object from hex buf error: value={}, {}",
405                v.as_str().unwrap(),
406                e
407            );
408            warn!("{}", msg);
409
410            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
411        })?;
412
413        Ok(v)
414    }
415
416    pub fn decode_from_boolean(v: &Value) -> BuckyResult<bool> {
417        let v = v.as_bool().ok_or_else(|| {
418            let msg = format!("invalid json field, except bool: {}", v);
419            warn!("{}", msg);
420
421            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
422        })?;
423
424        Ok(v)
425    }
426
427    /// number array
428    pub fn encode_number_array_field<T>(obj: &mut Map<String, Value>, key: &str, value: &Vec<T>)
429    where
430        T: Into<serde_json::Number> + Copy,
431    {
432        obj.insert(key.to_owned(), Self::encode_to_number_array(value));
433    }
434
435    pub fn encode_to_number_array<T>(list: &Vec<T>) -> Value
436    where
437        T: Into<serde_json::Number> + Copy,
438    {
439        let mut result = Vec::new();
440        for item in list {
441            result.push(Value::Number((*item).into()));
442        }
443
444        Value::Array(result)
445    }
446
447    pub fn decode_int_array_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Vec<T>>
448    where
449        T: FromStr + TryFrom<u64> + TryFrom<i64>,
450        <T as FromStr>::Err: std::fmt::Display,
451        <T as TryFrom<u64>>::Error: std::fmt::Display,
452        <T as TryFrom<i64>>::Error: std::fmt::Display,
453    {
454        match obj.get(key) {
455            Some(v) => Self::decode_from_int_array(v),
456            None => Ok(vec![]),
457        }
458    }
459
460    pub fn decode_option_int_array_field<T>(
461        obj: &Map<String, Value>,
462        key: &str,
463    ) -> BuckyResult<Option<Vec<T>>>
464    where
465        T: FromStr + TryFrom<u64> + TryFrom<i64>,
466        <T as FromStr>::Err: std::fmt::Display,
467        <T as TryFrom<u64>>::Error: std::fmt::Display,
468        <T as TryFrom<i64>>::Error: std::fmt::Display,
469    {
470        let ret = match obj.get(key) {
471            Some(v) => Some(Self::decode_from_int_array(v)?),
472            None => None,
473        };
474
475        Ok(ret)
476    }
477
478    pub fn decode_from_int_array<T>(v: &Value) -> BuckyResult<Vec<T>>
479    where
480        T: FromStr + TryFrom<u64> + TryFrom<i64>,
481        <T as FromStr>::Err: std::fmt::Display,
482        <T as TryFrom<u64>>::Error: std::fmt::Display,
483        <T as TryFrom<i64>>::Error: std::fmt::Display,
484    {
485        let list = v.as_array().ok_or_else(|| {
486            let msg = format!("invalid json field, except array: {}", v);
487            error!("{}", msg);
488
489            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
490        })?;
491
492        let mut result = Vec::new();
493        for item in list {
494            let item = Self::decode_to_int(item)?;
495            result.push(item);
496        }
497
498        Ok(result)
499    }
500
501    /// string array
502    pub fn encode_str_array_field<T>(obj: &mut Map<String, Value>, key: &str, value: &Vec<T>)
503    where
504        T: ToString,
505    {
506        obj.insert(key.to_owned(), Self::encode_to_str_array(value));
507    }
508
509    pub fn encode_option_str_array_field<T>(
510        obj: &mut Map<String, Value>,
511        key: &str,
512        value: Option<&Vec<T>>,
513    ) where
514        T: ToString,
515    {
516        if let Some(value) = value {
517            obj.insert(key.to_owned(), Self::encode_to_str_array(value));
518        }
519    }
520
521    pub fn encode_to_str_array<T>(list: &Vec<T>) -> Value
522    where
523        T: ToString,
524    {
525        let mut result = Vec::new();
526        for item in list {
527            let item = item.to_string();
528            result.push(Value::String(item));
529        }
530
531        Value::Array(result)
532    }
533
534    pub fn decode_str_array_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Vec<T>>
535    where
536        T: FromStr,
537        <T as FromStr>::Err: std::fmt::Display,
538    {
539        match obj.get(key) {
540            Some(v) => Self::decode_from_str_array(v),
541            None => Ok(vec![]),
542        }
543    }
544
545    pub fn decode_option_str_array_field<T>(
546        obj: &Map<String, Value>,
547        key: &str,
548    ) -> BuckyResult<Option<Vec<T>>>
549    where
550        T: FromStr,
551        <T as FromStr>::Err: std::fmt::Display,
552    {
553        match obj.get(key) {
554            Some(v) => Self::decode_from_str_array(v).map(|v| Some(v)),
555            None => Ok(None),
556        }
557    }
558
559    pub fn decode_from_str_array<T>(v: &Value) -> BuckyResult<Vec<T>>
560    where
561        T: FromStr,
562        <T as FromStr>::Err: std::fmt::Display,
563    {
564        let list = v.as_array().ok_or_else(|| {
565            let msg = format!("invalid json field, except array: {}", v);
566            error!("{}", msg);
567
568            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
569        })?;
570
571        let mut result = Vec::new();
572        for item in list {
573            let item = Self::decode_from_string(item)?;
574            result.push(item);
575        }
576
577        Ok(result)
578    }
579
580    pub fn encode_as_list<T>(obj: &mut Map<String, Value>, key: &str, value: &Vec<T>)
581    where
582        T: JsonCodec<T>,
583    {
584        obj.insert(key.to_owned(), Self::encode_to_array(value));
585    }
586
587    pub fn encode_as_option_list<T>(obj: &mut Map<String, Value>, key: &str, value: Option<&Vec<T>>)
588    where
589        T: JsonCodec<T>,
590    {
591        if let Some(list) = value {
592            obj.insert(key.to_owned(), Self::encode_to_array(list));
593        }
594    }
595
596    pub fn encode_to_array<T>(list: &Vec<T>) -> Value
597    where
598        T: JsonCodec<T>,
599    {
600        let mut result = Vec::new();
601        for item in list {
602            let item = T::encode_value(item);
603            result.push(item);
604        }
605
606        Value::Array(result)
607    }
608
609    pub fn decode_array_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Vec<T>>
610    where
611        T: JsonCodec<T>,
612    {
613        let v = obj.get(key).ok_or_else(|| {
614            let msg = format!("field not found: {}", key);
615            warn!("{}", msg);
616
617            BuckyError::new(BuckyErrorCode::NotFound, msg)
618        })?;
619
620        Self::decode_from_array(v)
621    }
622
623    pub fn decode_option_array_field<T>(
624        obj: &Map<String, Value>,
625        key: &str,
626    ) -> BuckyResult<Option<Vec<T>>>
627    where
628        T: JsonCodec<T>,
629    {
630        let ret = match obj.get(key) {
631            Some(v) => Some(Self::decode_from_array(v)?),
632            None => None,
633        };
634
635        Ok(ret)
636    }
637
638    pub fn decode_from_array<T>(v: &Value) -> BuckyResult<Vec<T>>
639    where
640        T: JsonCodec<T>,
641    {
642        let list = v.as_array().ok_or_else(|| {
643            let msg = format!("invalid json field, except array: {}", v);
644            error!("{}", msg);
645
646            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
647        })?;
648
649        let mut result = Vec::new();
650        for item in list {
651            let item = T::decode_value(item)?;
652            result.push(item);
653        }
654
655        Ok(result)
656    }
657
658    pub fn encode_field<T>(obj: &mut Map<String, Value>, key: impl ToString, value: &T)
659    where
660        T: JsonCodec<T>,
661    {
662        obj.insert(key.to_string(), value.encode_value());
663    }
664
665    pub fn encode_option_field<T>(
666        obj: &mut Map<String, Value>,
667        key: impl ToString,
668        value: Option<&T>,
669    ) where
670        T: JsonCodec<T>,
671    {
672        if let Some(value) = value {
673            obj.insert(key.to_string(), value.encode_value());
674        }
675    }
676
677    pub fn decode_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<T>
678    where
679        T: JsonCodec<T>,
680    {
681        let v = obj.get(key).ok_or_else(|| {
682            let msg = format!("field not found: {}", key);
683            warn!("{}", msg);
684
685            BuckyError::new(BuckyErrorCode::NotFound, msg)
686        })?;
687
688        Self::decode_from_object(v)
689    }
690
691    pub fn decode_option_field<T>(obj: &Map<String, Value>, key: &str) -> BuckyResult<Option<T>>
692    where
693        T: JsonCodec<T>,
694    {
695        match obj.get(key) {
696            Some(v) => {
697                let obj = Self::decode_from_object(v)?;
698                Ok(Some(obj))
699            }
700            None => Ok(None),
701        }
702    }
703
704    pub fn decode_from_object<T>(v: &Value) -> BuckyResult<T>
705    where
706        T: JsonCodec<T>,
707    {
708        if !v.is_object() {
709            let msg = format!("invalid object field: {:?}", v);
710            warn!("{}", msg);
711
712            return Err(BuckyError::new(BuckyErrorCode::InvalidParam, msg));
713        }
714
715        T::decode_json(v.as_object().unwrap())
716    }
717}
718
719impl JsonCodec<BuckyError> for BuckyError {
720    fn encode_json(&self) -> Map<String, Value> {
721        let mut obj = Map::new();
722
723        let code: u16 = self.code().into();
724        obj.insert("code".to_owned(), Value::String(code.to_string()));
725
726        obj.insert("msg".to_owned(), Value::String(self.msg().to_owned()));
727
728        obj
729    }
730
731    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
732        let mut code = BuckyErrorCode::Unknown;
733        let mut msg: String = "".to_owned();
734
735        for (k, v) in obj {
736            match k.as_str() {
737                "code" => {
738                    // 支持number和string两种模式
739                    let v: u16 = JsonCodecHelper::decode_to_int(v)?;
740                    code = BuckyErrorCode::from(v);
741                }
742
743                "msg" => {
744                    msg = v.as_str().unwrap_or("").to_owned();
745                }
746
747                u @ _ => {
748                    warn!("unknown bucky error field: {}", u);
749                }
750            }
751        }
752
753        Ok(Self::new(code, msg))
754    }
755}
756
757impl JsonCodec<NameLink> for NameLink {
758    fn encode_json(&self) -> Map<String, Value> {
759        let mut obj = Map::new();
760
761        match self {
762            Self::ObjectLink(id) => {
763                obj.insert("t".to_owned(), Value::String("object".to_owned()));
764                obj.insert("v".to_owned(), Value::String(id.to_string()));
765            }
766            Self::OtherNameLink(other) => {
767                obj.insert("t".to_owned(), Value::String("name".to_owned()));
768                obj.insert("v".to_owned(), Value::String(other.clone()));
769            }
770            Self::IPLink(addr) => {
771                obj.insert("t".to_owned(), Value::String("ip".to_owned()));
772                obj.insert("v".to_owned(), Value::String(addr.to_string()));
773            }
774        }
775
776        obj
777    }
778
779    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
780        let t: String = JsonCodecHelper::decode_string_field(obj, "t")?;
781        match t.as_ref() {
782            "object" => Ok(NameLink::ObjectLink(JsonCodecHelper::decode_string_field(
783                obj, "v",
784            )?)),
785            "name" => Ok(NameLink::OtherNameLink(
786                JsonCodecHelper::decode_string_field(obj, "v")?,
787            )),
788            "ip" => Ok(NameLink::IPLink(JsonCodecHelper::decode_string_field(
789                obj, "v",
790            )?)),
791            v @ _ => {
792                let msg = format!("invalid name link type: {}", v);
793                warn!("{}", msg);
794
795                Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg))
796            }
797        }
798    }
799}
800
801impl<T> JsonCodec<BuckyResult<T>> for BuckyResult<T>
802where
803    T: JsonCodec<T>,
804{
805    fn encode_json(&self) -> Map<String, Value> {
806        let mut obj = Map::new();
807
808        match self {
809            Ok(v) => JsonCodecHelper::encode_field(&mut obj, "value", v),
810            Err(e) => JsonCodecHelper::encode_field(&mut obj, "error", e),
811        }
812
813        obj
814    }
815
816    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
817        match JsonCodecHelper::decode_option_field(obj, "value")? {
818            Some(v) => Ok(Ok(v)),
819            None => match JsonCodecHelper::decode_option_field(obj, "error")? {
820                Some(e) => Ok(Err(e)),
821                None => {
822                    let msg = format!("invalid BuckyResult format: {:?}", obj);
823                    error!("{}", msg);
824
825                    Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg))
826                }
827            },
828        }
829    }
830}
831
832impl JsonCodec<Self> for ObjectMapContentItem {
833    fn encode_json(&self) -> Map<String, Value> {
834        let mut obj = Map::new();
835
836        JsonCodecHelper::encode_string_field(&mut obj, "content_type", &self.content_type());
837        match &self {
838            Self::Map((key, value)) => {
839                JsonCodecHelper::encode_string_field(&mut obj, "key", key);
840                JsonCodecHelper::encode_string_field(&mut obj, "value", value);
841            }
842            Self::DiffMap((key, value)) => {
843                JsonCodecHelper::encode_string_field(&mut obj, "key", key);
844                if let Some(value) = &value.prev {
845                    JsonCodecHelper::encode_string_field(&mut obj, "prev", value);
846                }
847                if let Some(value) = &value.altered {
848                    JsonCodecHelper::encode_string_field(&mut obj, "altered", value);
849                }
850                if let Some(value) = &value.diff {
851                    JsonCodecHelper::encode_string_field(&mut obj, "diff", value);
852                }
853            }
854            Self::Set(value) => {
855                JsonCodecHelper::encode_string_field(&mut obj, "value", value);
856            }
857            Self::DiffSet(value) => {
858                if let Some(value) = &value.prev {
859                    JsonCodecHelper::encode_string_field(&mut obj, "prev", value);
860                }
861                if let Some(value) = &value.altered {
862                    JsonCodecHelper::encode_string_field(&mut obj, "altered", value);
863                }
864            }
865        }
866
867        obj
868    }
869
870    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
871        let content_type: ObjectMapSimpleContentType =
872            JsonCodecHelper::decode_string_field(obj, "content_type")?;
873        let ret = match content_type {
874            ObjectMapSimpleContentType::Map => {
875                let key = JsonCodecHelper::decode_string_field(obj, "key")?;
876                let value = JsonCodecHelper::decode_string_field(obj, "value")?;
877                Self::Map((key, value))
878            }
879            ObjectMapSimpleContentType::DiffMap => {
880                let key = JsonCodecHelper::decode_string_field(obj, "key")?;
881                let prev = JsonCodecHelper::decode_option_string_field(obj, "prev")?;
882                let altered = JsonCodecHelper::decode_option_string_field(obj, "altered")?;
883                let diff = JsonCodecHelper::decode_option_string_field(obj, "diff")?;
884                let item = ObjectMapDiffMapItem {
885                    prev,
886                    altered,
887                    diff,
888                };
889                Self::DiffMap((key, item))
890            }
891            ObjectMapSimpleContentType::Set => {
892                let value = JsonCodecHelper::decode_string_field(obj, "value")?;
893                Self::Set(value)
894            }
895            ObjectMapSimpleContentType::DiffSet => {
896                let prev = JsonCodecHelper::decode_option_string_field(obj, "prev")?;
897                let altered = JsonCodecHelper::decode_option_string_field(obj, "altered")?;
898                let item = ObjectMapDiffSetItem { prev, altered };
899                Self::DiffSet(item)
900            }
901        };
902
903        Ok(ret)
904    }
905}
906
907impl JsonCodec<Self> for Vec<ObjectMapContentItem> {
908    fn decode_value(value: &Value) -> BuckyResult<Self> {
909        JsonCodecHelper::decode_from_array(value)
910    }
911
912    fn encode_value(&self) -> Value {
913        JsonCodecHelper::encode_to_array(self)
914    }
915}