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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! Subgraph JSON values.

use crate::{
    ffi::{
        boxed::AscRef,
        buf::AscTypedArray,
        str::AscString,
        sys,
        value::{AscJsonValue, AscJsonValueData},
    },
    num::BigInt,
};
use indexmap::IndexMap;
use std::{
    borrow::Cow,
    error::Error,
    fmt::{self, Debug, Display, Formatter},
    str::FromStr,
};

/// A Subgraph JSON value.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum Value {
    #[default]
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(IndexMap<String, Value>),
}

impl Value {
    /// Creates a new instance from a raw JSON value.
    fn from_raw(raw: &AscRef<AscJsonValue>) -> Self {
        match raw.data() {
            AscJsonValueData::Null(()) => Self::Null,
            AscJsonValueData::Bool(value) => Self::Bool(value),
            AscJsonValueData::Number(value) => {
                Self::Number(Number(Cow::Owned(value.to_string_lossy())))
            }
            AscJsonValueData::String(value) => Self::String(value.to_string_lossy()),
            AscJsonValueData::Array(value) => Self::Array(
                value
                    .as_slice()
                    .iter()
                    .map(|value| Self::from_raw(value.as_asc_ref()))
                    .collect(),
            ),
            AscJsonValueData::Object(value) => Self::Object(
                value
                    .entries()
                    .iter()
                    .map(|entry| {
                        let entry = entry.as_asc_ref();
                        (
                            entry.key().to_string_lossy(),
                            Self::from_raw(entry.value().as_asc_ref()),
                        )
                    })
                    .collect(),
            ),
        }
    }

    /// Parses a new JSON from from some bytes.
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Self {
        let bytes = bytes.as_ref();
        let array = AscTypedArray::from_bytes(bytes);
        let raw = unsafe { &*sys::json__from_bytes(array.as_ptr()) };

        Self::from_raw(raw)
    }

    /// Parses a new JSON value from bytes, returning and error on failure.
    pub fn try_from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, ParseError> {
        let bytes = bytes.as_ref();
        let array = AscTypedArray::from_bytes(bytes);
        let result = unsafe { &*sys::json__try_from_bytes(array.as_ptr()) };
        let raw = result.as_std_result().map_err(|_| ParseError)?.as_asc_ref();

        Ok(Self::from_raw(raw))
    }

    /// Returns the JSON value as a unit value, or `None` if the value is not
    /// `null`.
    pub fn as_null(&self) -> Option<()> {
        match self {
            Self::Null => Some(()),
            _ => None,
        }
    }

    /// Returns the JSON value as a boolean value, or `None` if the value is not
    /// `true` or `false`.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    /// Returns the JSON value as a numeric value, or `None` if the value is not
    /// a number.
    pub fn as_number(&self) -> Option<&Number> {
        match self {
            Self::Number(value) => Some(value),
            _ => None,
        }
    }

    /// Returns the JSON value as a string value, or `None` if the value is not
    /// a string.
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    /// Returns the JSON value as a slice of values, or `None` if the value is
    /// not an array.
    pub fn as_array(&self) -> Option<&[Self]> {
        match self {
            Self::Array(value) => Some(value),
            _ => None,
        }
    }

    /// Returns the JSON value as a map of values, or `None` if the value is not
    /// an object.
    pub fn as_object(&self) -> Option<&IndexMap<String, Self>> {
        match self {
            Self::Object(value) => Some(value),
            _ => None,
        }
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::Null => f.write_str("null"),
            Self::Bool(value) => write!(f, "{value}"),
            Self::Number(value) => write!(f, "{value}"),
            Self::String(value) => write!(f, "{value:?}"),
            Self::Array(value) => {
                f.write_str("[")?;
                for (i, value) in value.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write!(f, "{value}")?;
                }
                f.write_str("]")
            }
            Self::Object(value) => {
                f.write_str("{")?;
                for (i, (key, value)) in value.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write!(f, "\"{key}\":{value}")?;
                }
                f.write_str("}")
            }
        }
    }
}

/// A arbitrary-precision JSON number.
#[derive(Clone, Eq, PartialEq)]
pub struct Number(Cow<'static, str>);

impl Number {
    /// Converts this number to a [`BigInt`].
    pub fn to_big_int(&self) -> BigInt {
        let str = AscString::new(&self.0);
        let raw = unsafe { &*sys::json__to_big_int(str.as_ptr()) };
        BigInt::from_raw(raw)
    }

    /// Converts this number to a 64-bit float.
    pub fn to_f64(&self) -> f64 {
        let str = AscString::new(&self.0);
        unsafe { sys::json__to_f64(str.as_ptr()) }
    }

    /// Converts this number to a 64-bit signed integer.
    pub fn to_i64(&self) -> i64 {
        let str = AscString::new(&self.0);
        unsafe { sys::json__to_i64(str.as_ptr()) }
    }

    /// Converts this number to a 64-bit un-signed integer.
    pub fn to_u64(&self) -> u64 {
        let str = AscString::new(&self.0);
        unsafe { sys::json__to_u64(str.as_ptr()) }
    }
}

impl Debug for Number {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Default for Number {
    fn default() -> Self {
        Self(Cow::Borrowed("0"))
    }
}

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

impl FromStr for Value {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_bytes(s)
    }
}

/// A JSON parse error.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ParseError;

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str("JSON parse error")
    }
}

impl Error for ParseError {}