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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright (c) 2018 R Pratap Chakravarthy.

use std::ops::{Add, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub};
use std::ops::{BitAnd, BitOr, BitXor, Index};

use lazy_static::lazy_static;

use crate::error::{Error, Result};
use crate::json::Json;
use crate::property::{self, Property};

// TODO: use macro to implement Add<Json> and Add<&Json> and similar variant
//       for Sub, Mul, Div, Neg ...

impl Add for Json {
    type Output = Json;

    fn add(self, rhs: Json) -> Json {
        use crate::json::Json::{Array, Float, Integer, Null, Object, String as S};

        match (&self, &rhs) {
            (Null, _) => rhs.clone(),  // Identity operation
            (_, Null) => self.clone(), // Identity operation
            (Integer(_), Integer(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.integer().unwrap());
                Json::new(l + r)
            }
            (Float(_), Float(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.float().unwrap());
                Json::new(l + r)
            }
            (Integer(_), Float(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.float().unwrap());
                Json::new(l as f64 + r)
            }
            (Float(_), Integer(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.integer().unwrap());
                Json::new(l + r as f64)
            }
            (S(l), S(r)) => {
                let mut s = String::new();
                s.push_str(l);
                s.push_str(r);
                S(s)
            }
            (Array(l), Array(r)) => {
                let mut a = vec![];
                a.extend_from_slice(l);
                a.extend_from_slice(r);
                Array(a)
            }
            (Object(l), Object(r)) => {
                use crate::json;

                let mut obj = Json::Object(Vec::new());
                l.to_vec()
                    .into_iter()
                    .for_each(|p| json::insert(&mut obj, p));
                r.to_vec()
                    .into_iter()
                    .for_each(|p| json::insert(&mut obj, p));
                obj
            }
            (_, _) => Json::__Error(Error::AddFail(format!("{} + {}", self, rhs))),
        }
    }
}

impl Sub for Json {
    type Output = Json;

    fn sub(self, rhs: Json) -> Json {
        use crate::json::Json::{Array, Float, Integer, Null, Object};

        match (&self, &rhs) {
            (Null, _) => rhs.clone(),  // Identity operation
            (_, Null) => self.clone(), // Identity operation
            (Integer(_), Integer(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.integer().unwrap());
                Json::new(l - r)
            }
            (Float(_), Float(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.float().unwrap());
                Json::new(l - r)
            }
            (Integer(_), Float(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.float().unwrap());
                Json::new((l as f64) - r)
            }
            (Float(_), Integer(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.integer().unwrap());
                Json::new(l - (r as f64))
            }
            (Array(lhs), Array(rhs)) => {
                let mut res = lhs.clone();
                rhs.iter().for_each(|x| {
                    if let Some(pos) = res.iter().position(|y| *x == *y) {
                        res.remove(pos);
                    }
                });
                Array(res)
            }
            (Object(lhs), Object(rhs)) => {
                let mut res = lhs.clone();
                rhs.iter().for_each(|x| {
                    if let Some(pos) = res.iter().position(|y| *x == *y) {
                        res.remove(pos);
                    }
                });
                Object(res)
            }
            (_, _) => Json::__Error(Error::SubFail(format!("{} - {}", self, rhs))),
        }
    }
}

impl Mul for Json {
    type Output = Json;

    fn mul(self, rhs: Json) -> Json {
        use crate::json::Json::{Float, Integer, Null, Object, String as S};

        match (&self, &rhs) {
            (Null, _) => Json::Null,
            (_, Null) => Json::Null,
            (Integer(_), Integer(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.integer().unwrap());
                Json::new(l * r)
            }
            (Float(_), Float(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.float().unwrap());
                Json::new(l * r)
            }
            (Integer(_), Float(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.float().unwrap());
                Json::new((l as f64) * r)
            }
            (Float(_), Integer(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.integer().unwrap());
                Json::new(l * (r as f64))
            }
            (S(s), Integer(_)) => {
                let n = rhs.integer().unwrap();
                if n == 0 {
                    Null
                } else {
                    S(s.repeat(n as usize))
                }
            }
            (Integer(_), S(s)) => {
                let n = self.integer().unwrap();
                if n == 0 {
                    Null
                } else {
                    S(s.repeat(n as usize))
                }
            }
            (Object(this), Object(other)) => {
                // TODO: this is not well defined.
                let mut obj = Vec::new();
                obj = mixin_object(obj, this.to_vec());
                obj = mixin_object(obj, other.to_vec());
                Json::Object(obj)
            }
            (_, _) => Json::__Error(Error::MulFail(format!("{} * {}", self, rhs))),
        }
    }
}

impl Div for Json {
    type Output = Json;

    fn div(self, rhs: Json) -> Json {
        use crate::json::Json::{Float, Integer, Null, String as S};

        match (&self, &rhs) {
            (Null, _) => Json::Null,
            (_, Null) => Json::Null,
            (Integer(_), Integer(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.integer().unwrap());
                if r == 0 {
                    Null
                } else {
                    Json::new(l / r)
                }
            }
            (Integer(_), Float(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.float().unwrap());
                if r == 0_f64 {
                    Null
                } else {
                    Json::new((l as f64) / r)
                }
            }
            (Float(_), Integer(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.integer().unwrap());
                if r == 0 {
                    Null
                } else {
                    Json::new(l / (r as f64))
                }
            }
            (Float(_), Float(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.float().unwrap());
                if r == 0_f64 {
                    Null
                } else {
                    Json::new(l / r)
                }
            }
            (S(s), S(patt)) => {
                // TODO: not yet defined
                let arr = s.split(patt).map(|s| S(s.to_string())).collect();
                Json::Array(arr)
            }
            (_, _) => Json::__Error(Error::DivFail(format!("invalid {} / {}", self, rhs))),
        }
    }
}

impl Rem for Json {
    type Output = Json;

    fn rem(self, rhs: Json) -> Json {
        use crate::json::Json::{Float, Integer, Null};

        match (&self, &rhs) {
            (Null, _) => Json::Null,
            (_, Null) => Json::Null,
            (Integer(_), Integer(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.integer().unwrap());
                if r == 0 {
                    Null
                } else {
                    Json::new(l % r)
                }
            }
            (Integer(_), Float(_)) => {
                let (l, r) = (self.integer().unwrap(), rhs.float().unwrap());
                if r == 0_f64 {
                    Null
                } else {
                    Json::new((l as f64) % r)
                }
            }
            (Float(_), Integer(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.integer().unwrap());
                if r == 0 {
                    Null
                } else {
                    Json::new(l % (r as f64))
                }
            }
            (Float(_), Float(_)) => {
                let (l, r) = (self.float().unwrap(), rhs.float().unwrap());
                if r == 0_f64 {
                    Null
                } else {
                    Json::new(l % r)
                }
            }
            (_, _) => Json::__Error(Error::RemFail(format!("invalid {} % {}", self, rhs))),
        }
    }
}

impl Neg for Json {
    type Output = Json;

    fn neg(self) -> Json {
        match self {
            Json::Null => Json::Null,
            Json::Integer(_) => Json::new(-self.integer().unwrap()),
            Json::Float(_) => Json::new(-self.float().unwrap()),
            _ => Json::__Error(Error::NegFail(format!("-{}", self.typename()))),
        }
    }
}

impl Shl for Json {
    type Output = Json;

    fn shl(self, rhs: Json) -> Json {
        match (self.integer(), rhs.integer()) {
            (Some(l), Some(r)) => Json::new(l << r),
            (_, _) => Json::__Error(Error::ShlFail(format!("{} << {}", self, rhs))),
        }
    }
}

impl Shr for Json {
    type Output = Json;

    fn shr(self, rhs: Json) -> Json {
        match (self.integer(), rhs.integer()) {
            (Some(l), Some(r)) => Json::new(l >> r),
            (_, _) => Json::__Error(Error::ShrFail(format!("{} >> {}", self, rhs))),
        }
    }
}

impl BitAnd for Json {
    type Output = Json;

    fn bitand(self, rhs: Json) -> Json {
        use crate::json::Json::Integer;

        match (self, rhs) {
            (x @ Json::__Error(_), _) => x,
            (_, y @ Json::__Error(_)) => y,
            (x @ Integer(_), y @ Integer(_)) => {
                (x.integer().unwrap() & y.integer().unwrap()).into()
            }
            (x, y) => {
                let (x, y): (bool, bool) = (x.into(), y.into());
                (x & y).into()
            }
        }
    }
}

impl BitOr for Json {
    type Output = Json;

    fn bitor(self, rhs: Json) -> Json {
        use crate::json::Json::Integer;

        match (self, rhs) {
            (x @ Json::__Error(_), _) => x,
            (_, y @ Json::__Error(_)) => y,
            (x @ Integer(_), y @ Integer(_)) => {
                (x.integer().unwrap() | y.integer().unwrap()).into()
            }
            (x, y) => {
                let (x, y): (bool, bool) = (x.into(), y.into());
                (x | y).into()
            }
        }
    }
}

impl BitXor for Json {
    type Output = Json;

    fn bitxor(self, rhs: Json) -> Json {
        use crate::json::Json::Integer;

        match (self, rhs) {
            (x @ Json::__Error(_), _) => x,
            (_, y @ Json::__Error(_)) => y,
            (x @ Integer(_), y @ Integer(_)) => {
                (x.integer().unwrap() ^ y.integer().unwrap()).into()
            }
            (x, y) => {
                let (x, y): (bool, bool) = (x.into(), y.into());
                (x ^ y).into()
            }
        }
    }
}

impl Not for Json {
    type Output = Json;

    fn not(self) -> Json {
        if self.is_error() {
            return self;
        }
        let value: bool = self.into();
        value.not().into()
    }
}

lazy_static! {
    pub static ref INDEX_OUT_OF_BOUND: Json = Json::__Error(Error::IndexOutofBound(-1));
    pub static ref NOT_AN_ARRAY: Json = Json::__Error(Error::NotAnArray("--na--".to_string()));
    pub static ref NOT_AN_INDEX: Json = Json::__Error(Error::NotAnIndex("--na--".to_string()));
    pub static ref NOT_A_CONTAINER: Json =
        Json::__Error(Error::NotAContainer("--na--".to_string()));
    pub static ref PROPERTY_NOT_FOUND: Json =
        Json::__Error(Error::PropertyNotFound("--na--".to_string()));
}

impl Index<isize> for Json {
    type Output = Json;

    fn index(&self, index: isize) -> &Json {
        match self {
            Json::Array(arr) => match normalized_offset(index, arr.len()) {
                Some(off) => &arr[off],
                None => &INDEX_OUT_OF_BOUND,
            },
            Json::__Error(_) => self,
            _ => &NOT_AN_ARRAY,
        }
    }
}

impl Index<&str> for Json {
    type Output = Json;

    fn index(&self, index: &str) -> &Json {
        match self {
            Json::Object(obj) => match property::search_by_key(obj, index) {
                Ok(off) => obj[off].value_ref(),
                Err(_) => &PROPERTY_NOT_FOUND,
            },
            Json::Array(arr) => match index.parse::<isize>() {
                Ok(n) => match normalized_offset(n, arr.len()) {
                    Some(off) => &arr[off],
                    None => &INDEX_OUT_OF_BOUND,
                },
                Err(_) => &NOT_AN_INDEX,
            },
            Json::__Error(_) => self,
            _ => &NOT_A_CONTAINER,
        }
    }
}

pub fn index_mut<'a>(j: &'a mut Json, i: &str) -> Result<&'a mut Json> {
    match j {
        Json::Object(obj) => match property::search_by_key(obj, i) {
            Ok(off) => Ok(obj[off].value_mut()),
            Err(_) => Err(Error::PropertyNotFound(i.to_string())),
        },
        Json::Array(arr) => match i.parse::<isize>() {
            Ok(n) => match normalized_offset(n, arr.len()) {
                Some(off) => Ok(&mut arr[off]),
                None => Err(Error::IndexOutofBound(n)),
            },
            Err(err) => Err(Error::NotAnIndex(err.to_string())),
        },
        Json::__Error(_) => Ok(j),
        _ => Err(Error::NotAContainer(j.typename())),
    }
}

//// TODO: To handle || and && short-circuiting operations.
////impl And for Json {
////    type Output=Json;
////
////    fn and(self, other: Json) -> Self::Output {
////        let lhs = bool::from(self);
////        let rhs = bool::from(other);
////        Json::Bool(lhs & rhs)
////    }
////}
////
////impl Or for Json {
////    type Output=Json;
////
////    fn or(self, other: Json) -> Self::Output {
////        let lhs = bool::from(self);
////        let rhs = bool::from(other);
////        Json::Bool(lhs | rhs)
////    }
////}

fn mixin_object(mut this: Vec<Property>, other: Vec<Property>) -> Vec<Property> {
    use crate::json::Json::Object;

    for o in other.into_iter() {
        match property::search_by_key(&this, o.key_ref()) {
            Ok(off) => match (this[off].clone().value(), o.clone().value()) {
                (Object(val), Object(val2)) => this[off].set_value(Object(mixin_object(val, val2))),
                _ => this.insert(off, o),
            },
            Err(off) => this.insert(off, o.clone()),
        }
    }
    this
}

pub fn normalized_offset(off: isize, len: usize) -> Option<usize> {
    let len = len as isize;
    let off = if off < 0 { off + len } else { off };
    if off >= 0 && off < len {
        Some(off as usize)
    } else {
        None
    }
}