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
use std::cmp::Ordering;
use std::fmt;

use kstring::KStringCow;

use super::DisplayCow;
use super::State;
use super::Value;
use crate::model::ArrayView;
use crate::model::ObjectView;
use crate::model::ScalarCow;

/// Accessor for Values.
pub trait ValueView: fmt::Debug {
    /// Get a `Debug` representation
    fn as_debug(&self) -> &dyn fmt::Debug;

    /// A `Display` for a `BoxedValue` rendered for the user.
    fn render(&self) -> DisplayCow<'_>;
    /// A `Display` for a `Value` as source code.
    fn source(&self) -> DisplayCow<'_>;
    /// Report the data type (generally for error reporting).
    fn type_name(&self) -> &'static str;
    /// Query the value's state
    fn query_state(&self, state: State) -> bool;

    /// Interpret as a string.
    fn to_kstr(&self) -> KStringCow<'_>;
    /// Convert to an owned type.
    fn to_value(&self) -> Value;

    /// Extracts the scalar value if it is a scalar.
    fn as_scalar(&self) -> Option<ScalarCow<'_>> {
        None
    }
    /// Tests whether this value is a scalar
    fn is_scalar(&self) -> bool {
        self.as_scalar().is_some()
    }

    /// Extracts the array value if it is an array.
    fn as_array(&self) -> Option<&dyn ArrayView> {
        None
    }
    /// Tests whether this value is an array
    fn is_array(&self) -> bool {
        self.as_array().is_some()
    }

    /// Extracts the object value if it is a object.
    fn as_object(&self) -> Option<&dyn ObjectView> {
        None
    }
    /// Tests whether this value is an object
    fn is_object(&self) -> bool {
        self.as_object().is_some()
    }

    /// Extracts the state if it is one
    fn as_state(&self) -> Option<State> {
        None
    }
    /// Tests whether this value is state
    fn is_state(&self) -> bool {
        self.as_state().is_some()
    }

    /// Tests whether this value is nil
    ///
    /// See https://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails
    fn is_nil(&self) -> bool {
        false
    }
}

static NIL: Value = Value::Nil;

impl<T: ValueView> ValueView for Option<T> {
    fn as_debug(&self) -> &dyn fmt::Debug {
        self
    }

    fn render(&self) -> DisplayCow<'_> {
        forward(self).render()
    }
    fn source(&self) -> DisplayCow<'_> {
        forward(self).source()
    }
    fn type_name(&self) -> &'static str {
        forward(self).type_name()
    }
    fn query_state(&self, state: State) -> bool {
        forward(self).query_state(state)
    }

    fn to_kstr(&self) -> KStringCow<'_> {
        forward(self).to_kstr()
    }
    fn to_value(&self) -> Value {
        forward(self).to_value()
    }

    fn as_scalar(&self) -> Option<ScalarCow<'_>> {
        forward(self).as_scalar()
    }

    fn as_array(&self) -> Option<&dyn ArrayView> {
        forward(self).as_array()
    }

    fn as_object(&self) -> Option<&dyn ObjectView> {
        forward(self).as_object()
    }

    fn as_state(&self) -> Option<State> {
        forward(self).as_state()
    }

    fn is_nil(&self) -> bool {
        forward(self).is_nil()
    }
}

fn forward(o: &Option<impl ValueView>) -> &dyn ValueView {
    o.as_ref()
        .map(|v| v as &dyn ValueView)
        .unwrap_or(&NIL as &dyn ValueView)
}

/// `Value` comparison semantics for types implementing `ValueView`.
#[derive(Copy, Clone, Debug)]
pub struct ValueViewCmp<'v>(&'v dyn ValueView);

impl<'v> ValueViewCmp<'v> {
    /// `Value` comparison semantics for types implementing `ValueView`.
    pub fn new(v: &dyn ValueView) -> ValueViewCmp<'_> {
        ValueViewCmp(v)
    }
}

impl<'v> PartialEq<ValueViewCmp<'v>> for ValueViewCmp<'v> {
    fn eq(&self, other: &Self) -> bool {
        value_eq(self.0, other.0)
    }
}

impl<'v> PartialEq<i64> for ValueViewCmp<'v> {
    fn eq(&self, other: &i64) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<f64> for ValueViewCmp<'v> {
    fn eq(&self, other: &f64) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<bool> for ValueViewCmp<'v> {
    fn eq(&self, other: &bool) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<crate::model::scalar::DateTime> for ValueViewCmp<'v> {
    fn eq(&self, other: &crate::model::scalar::DateTime) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<crate::model::scalar::Date> for ValueViewCmp<'v> {
    fn eq(&self, other: &crate::model::scalar::Date) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<str> for ValueViewCmp<'v> {
    fn eq(&self, other: &str) -> bool {
        let other = KStringCow::from_ref(other);
        super::value_eq(self.0, &other)
    }
}

impl<'v> PartialEq<&'v str> for ValueViewCmp<'v> {
    fn eq(&self, other: &&str) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<String> for ValueViewCmp<'v> {
    fn eq(&self, other: &String) -> bool {
        self == other.as_str()
    }
}

impl<'v> PartialEq<kstring::KString> for ValueViewCmp<'v> {
    fn eq(&self, other: &kstring::KString) -> bool {
        super::value_eq(self.0, &other.as_ref())
    }
}

impl<'v> PartialEq<kstring::KStringRef<'v>> for ValueViewCmp<'v> {
    fn eq(&self, other: &kstring::KStringRef<'v>) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialEq<kstring::KStringCow<'v>> for ValueViewCmp<'v> {
    fn eq(&self, other: &kstring::KStringCow<'v>) -> bool {
        super::value_eq(self.0, other)
    }
}

impl<'v> PartialOrd<ValueViewCmp<'v>> for ValueViewCmp<'v> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        value_cmp(self.0, other.0)
    }
}

pub(crate) fn value_eq(lhs: &dyn ValueView, rhs: &dyn ValueView) -> bool {
    if let (Some(x), Some(y)) = (lhs.as_array(), rhs.as_array()) {
        if x.size() != y.size() {
            return false;
        }
        return x.values().zip(y.values()).all(|(x, y)| value_eq(x, y));
    }

    if let (Some(x), Some(y)) = (lhs.as_object(), rhs.as_object()) {
        if x.size() != y.size() {
            return false;
        }
        return x
            .iter()
            .all(|(key, value)| y.get(key.as_str()).map_or(false, |v| value_eq(v, value)));
    }

    if lhs.is_nil() && rhs.is_nil() {
        return true;
    }

    if let Some(state) = lhs.as_state() {
        return rhs.query_state(state);
    } else if let Some(state) = rhs.as_state() {
        return lhs.query_state(state);
    }

    match (lhs.as_scalar(), rhs.as_scalar()) {
        (Some(x), Some(y)) => return x == y,
        (None, None) => (),
        // encode Ruby truthiness: all values except false and nil are true
        (Some(x), _) => {
            if rhs.is_nil() {
                return !x.to_bool().unwrap_or(true);
            } else {
                return x.to_bool().unwrap_or(false);
            }
        }
        (_, Some(x)) => {
            if lhs.is_nil() {
                return !x.to_bool().unwrap_or(true);
            } else {
                return x.to_bool().unwrap_or(false);
            }
        }
    }

    false
}

pub(crate) fn value_cmp(lhs: &dyn ValueView, rhs: &dyn ValueView) -> Option<Ordering> {
    if let (Some(x), Some(y)) = (lhs.as_scalar(), rhs.as_scalar()) {
        return x.partial_cmp(&y);
    }

    if let (Some(x), Some(y)) = (lhs.as_array(), rhs.as_array()) {
        return x
            .values()
            .map(|v| ValueViewCmp(v))
            .partial_cmp(y.values().map(|v| ValueViewCmp(v)));
    }

    if let (Some(x), Some(y)) = (lhs.as_object(), rhs.as_object()) {
        return x
            .iter()
            .map(|(k, v)| (k, ValueViewCmp(v)))
            .partial_cmp(y.iter().map(|(k, v)| (k, ValueViewCmp(v))));
    }

    None
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_debug() {
        let scalar = 5;
        println!("{:?}", scalar);
        let view: &dyn ValueView = &scalar;
        println!("{:?}", view);
        let debug: &dyn fmt::Debug = view.as_debug();
        println!("{:?}", debug);
    }
}