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
use {
    hina,

    arya::JsonError,
    arya::JsonStatus,
    arya::JsonVerifier,
};



/// expanded options for constructing a [`JsonBuilder`](./struct.JsonBuilder.html) instance.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JsonBuilderOptions {
    maximum_depth:    usize,
    initial_capacity: usize,
}

impl Default for JsonBuilderOptions {
    fn default() -> JsonBuilderOptions {
        JsonBuilderOptions {
            maximum_depth:    std::usize::MAX,
            initial_capacity: 512,
        }
    }
}



/// a string builder for json that can repair and complete incomplete ("damaged") json.
///
/// # remarks
///
/// unlike the [`JsonVerifier`](./struct.JsonVerifier.html), adding a sequence of characters that would make the
/// underlying json object invalid will cause the [`JsonBuilder`](./struct.JsonBuilder.html) to remain invalid, even if
/// more characters are added to it later.
///
/// # examples
/// ```
/// # use arya::JsonBuilder;
/// #
/// # fn main() {
/// #
/// let mut builder = JsonBuilder::new();
///
/// builder.update(r#"{
///     "name": "annie",
///     "age": 14,
///     "parents": {
///         "mother": null,
///         "bro
/// "#);
///
/// builder.update("ken");
///
/// builder.completed_string();
/// // => Ok({
/// // =>     "name": "annie",
/// // =>     "age": 14,
/// // =>     "nested": {
/// // =>         "mother": null
/// // =>     }
/// // => })
/// # }
/// ```
pub struct JsonBuilder {
    data:     Vec<u8>,
    invalid:  bool,
    verifier: JsonVerifier,
}

impl JsonBuilder {
    pub fn new() -> JsonBuilder {
        JsonBuilder {
            data:     vec![],
            invalid:  false,
            verifier: JsonVerifier::new()
        }
    }

    pub fn with_maximum_depth(maximum_depth: usize) -> JsonBuilder {
        JsonBuilder::with_options(JsonBuilderOptions { maximum_depth, ..Default::default() })
    }

    pub fn with_capacity(initial_capacity: usize) -> JsonBuilder {
        JsonBuilder::with_options(JsonBuilderOptions { initial_capacity, ..Default::default() })
    }

    pub fn with_options(options: JsonBuilderOptions) -> JsonBuilder {
        JsonBuilder {
            data:     Vec::with_capacity(options.initial_capacity),
            invalid:  false,
            verifier: JsonVerifier::with_maximum_depth(options.maximum_depth),
        }
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }

    pub fn status(&self) -> JsonStatus {
        self.verifier.status()
    }

    pub fn reset(&mut self) {
        self.invalid = false;

        self.data.clear();
        self.verifier.reset();
    }

    pub fn update(&mut self, source: impl JsonSource) -> Result<(), JsonError> {
        if self.invalid {
            Err(JsonError::Invalid)
        } else {
            for character in source.stream() {
                match self.verifier.update(*character) {
                    Ok(()) => {
                        self.data.push(*character);
                    },
                    Err(e) => {
                        self.invalid = true;
                        return Err(e);
                    },
                }
            }

            Ok(())
        }
    }

    pub fn bytes(self) -> Result<Vec<u8>, JsonError> {
        match self.invalid {
            true  => Err(JsonError::Invalid),
            false => Ok(self.data),
        }
    }

    pub fn string(self) -> Result<String, JsonError> {
        let data = self.bytes()?;

        String::from_utf8(data).map_err(|_| JsonError::Utf8)
    }

    pub fn completed_bytes(mut self) -> Result<Vec<u8>, JsonError> {
        if self.invalid {
            Err(JsonError::Invalid)
        } else {
            if self.verifier.status() == JsonStatus::Continue {
                let (until, tokens) = self.verifier.complete();

                self.data.truncate(until);
                self.data.extend(tokens);
            }

            Ok(self.data)
        }
    }

    pub fn completed_string(self) -> Result<String, JsonError> {
        let data = self.completed_bytes()?;

        String::from_utf8(data).map_err(|_| JsonError::Utf8)
    }
}



/// utf8 byte streams for arya's json parsers.
pub trait JsonSource {
    fn stream(&self) -> &[u8];
}

impl JsonSource for u8 {
    fn stream(&self) -> &[u8] {
        hina::as_slice(&self)
    }
}

impl JsonSource for &[u8] {
    fn stream(&self) -> &[u8] {
        &self
    }
}

impl JsonSource for Vec<u8> {
    fn stream(&self) -> &[u8] {
        &self[..]
    }
}

impl JsonSource for &str {
    fn stream(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl JsonSource for String {
    fn stream(&self) -> &[u8] {
        self.as_bytes()
    }
}