mysql_common/value/json/
serde_integration.rs

1// Copyright (c) 2017 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use std::convert::TryFrom;
10
11use serde::{de::DeserializeOwned, Serialize};
12use serde_json::{self, Value as Json};
13
14use super::{Deserialized, Serialized};
15use crate::value::{
16    convert::{FromValue, FromValueError, ParseIr},
17    Value,
18};
19
20impl TryFrom<Value> for ParseIr<Json> {
21    type Error = FromValueError;
22
23    fn try_from(v: Value) -> Result<Self, Self::Error> {
24        match v {
25            Value::Bytes(ref bytes) => match serde_json::from_slice(bytes) {
26                Ok(x) => Ok(ParseIr(x, v)),
27                Err(_) => Err(FromValueError(v)),
28            },
29            v => Err(FromValueError(v)),
30        }
31    }
32}
33
34impl From<ParseIr<Json>> for Json {
35    fn from(value: ParseIr<Json>) -> Self {
36        value.commit()
37    }
38}
39
40impl From<ParseIr<Json>> for Value {
41    fn from(value: ParseIr<Json>) -> Self {
42        value.rollback()
43    }
44}
45
46impl FromValue for Json {
47    type Intermediate = ParseIr<Json>;
48}
49
50impl<T: DeserializeOwned> TryFrom<Value> for ParseIr<Deserialized<T>> {
51    type Error = FromValueError;
52
53    fn try_from(v: Value) -> Result<Self, Self::Error> {
54        match v {
55            Value::Bytes(ref bytes) => match serde_json::from_slice(bytes) {
56                Ok(x) => Ok(ParseIr(Deserialized(x), v)),
57                Err(_) => Err(FromValueError(v)),
58            },
59            v => Err(FromValueError(v)),
60        }
61    }
62}
63
64impl<T: DeserializeOwned> From<ParseIr<Deserialized<T>>> for Deserialized<T> {
65    fn from(value: ParseIr<Deserialized<T>>) -> Self {
66        value.commit()
67    }
68}
69
70impl<T: DeserializeOwned> From<ParseIr<Deserialized<T>>> for Value {
71    fn from(value: ParseIr<Deserialized<T>>) -> Self {
72        value.rollback()
73    }
74}
75
76impl<T: DeserializeOwned> FromValue for Deserialized<T> {
77    type Intermediate = ParseIr<Deserialized<T>>;
78}
79
80impl From<Json> for Value {
81    fn from(x: Json) -> Value {
82        Value::Bytes(serde_json::to_string(&x).unwrap().into())
83    }
84}
85
86impl<T: Serialize> From<Serialized<T>> for Value {
87    fn from(x: Serialized<T>) -> Value {
88        Value::Bytes(serde_json::to_string(&x.0).unwrap().into())
89    }
90}