]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_target/src/json.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_target / src / json.rs
1 use std::borrow::Cow;
2 use std::collections::BTreeMap;
3
4 pub use serde_json::Value as Json;
5 use serde_json::{Map, Number};
6
7 pub trait ToJson {
8 fn to_json(&self) -> Json;
9 }
10
11 impl ToJson for Json {
12 fn to_json(&self) -> Json {
13 self.clone()
14 }
15 }
16
17 macro_rules! to_json_impl_num {
18 ($($t:ty), +) => (
19 $(impl ToJson for $t {
20 fn to_json(&self) -> Json {
21 Json::Number(Number::from(*self))
22 }
23 })+
24 )
25 }
26
27 to_json_impl_num! { isize, i8, i16, i32, i64, usize, u8, u16, u32, u64 }
28
29 impl ToJson for bool {
30 fn to_json(&self) -> Json {
31 Json::Bool(*self)
32 }
33 }
34
35 impl ToJson for str {
36 fn to_json(&self) -> Json {
37 Json::String(self.to_owned())
38 }
39 }
40
41 impl ToJson for String {
42 fn to_json(&self) -> Json {
43 Json::String(self.to_owned())
44 }
45 }
46
47 impl<'a> ToJson for Cow<'a, str> {
48 fn to_json(&self) -> Json {
49 Json::String(self.to_string())
50 }
51 }
52
53 impl<A: ToJson> ToJson for [A] {
54 fn to_json(&self) -> Json {
55 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
56 }
57 }
58
59 impl<A: ToJson> ToJson for Vec<A> {
60 fn to_json(&self) -> Json {
61 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
62 }
63 }
64
65 impl<'a, A: ToJson> ToJson for Cow<'a, [A]>
66 where
67 [A]: ToOwned,
68 {
69 fn to_json(&self) -> Json {
70 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
71 }
72 }
73
74 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
75 fn to_json(&self) -> Json {
76 let mut d = Map::new();
77 for (key, value) in self {
78 d.insert(key.to_string(), value.to_json());
79 }
80 Json::Object(d)
81 }
82 }
83
84 impl<A: ToJson> ToJson for Option<A> {
85 fn to_json(&self) -> Json {
86 match *self {
87 None => Json::Null,
88 Some(ref value) => value.to_json(),
89 }
90 }
91 }