1use std::cmp::Ordering;
2use std::rc::Rc;
3
4use bigdecimal::{BigDecimal, ToPrimitive};
5
6use crate::error::{DogeError, DogeResult};
7use crate::value::Value;
8
9fn is_numeric(v: &Value) -> bool {
12 matches!(v, Value::Int(_) | Value::Float(_) | Value::Decimal(_))
13}
14
15fn numeric_f64(v: &Value) -> Option<f64> {
18 match v {
19 Value::Int(n) => n.to_f64(),
20 Value::Float(f) => Some(*f),
21 Value::Decimal(d) => d.to_f64(),
22 _ => None,
23 }
24}
25
26fn numeric_cmp(a: &Value, b: &Value) -> Option<Ordering> {
30 match (a, b) {
31 (Value::Int(x), Value::Int(y)) => Some(x.cmp(y)),
32 (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
33 (Value::Int(x), Value::Decimal(y)) => Some(BigDecimal::from(x.clone()).cmp(y)),
34 (Value::Decimal(x), Value::Int(y)) => Some(x.cmp(&BigDecimal::from(y.clone()))),
35 _ => numeric_f64(a)?.partial_cmp(&numeric_f64(b)?),
36 }
37}
38
39fn numeric_equal(a: &Value, b: &Value) -> Option<bool> {
43 if is_numeric(a) && is_numeric(b) {
44 Some(numeric_cmp(a, b) == Some(Ordering::Equal))
45 } else {
46 None
47 }
48}
49
50pub fn values_equal(a: &Value, b: &Value) -> bool {
53 if let Some(numeric) = numeric_equal(a, b) {
54 return numeric;
55 }
56 match (a, b) {
57 (Value::Str(x), Value::Str(y)) => x == y,
58 (Value::Bytes(x), Value::Bytes(y)) => x == y,
59 (Value::Bool(x), Value::Bool(y)) => x == y,
60 (Value::None, Value::None) => true,
61 (Value::List(x), Value::List(y)) => {
62 let (xb, yb) = (x.borrow(), y.borrow());
63 xb.len() == yb.len() && xb.iter().zip(yb.iter()).all(|(p, q)| values_equal(p, q))
64 }
65 (Value::Dict(x), Value::Dict(y)) => {
66 let (xb, yb) = (x.borrow(), y.borrow());
67 xb.len() == yb.len()
68 && xb
69 .iter()
70 .all(|(k, v)| yb.get(k).is_some_and(|w| values_equal(v, w)))
71 }
72 (Value::Object(x), Value::Object(y)) => Rc::ptr_eq(x, y),
74 (Value::Function(x), Value::Function(y)) => {
76 x.fn_id == y.fn_id
77 && x.captures.len() == y.captures.len()
78 && x.captures
79 .iter()
80 .zip(y.captures.iter())
81 .all(|(p, q)| Rc::ptr_eq(p, q))
82 }
83 (Value::Class(x), Value::Class(y)) => x.fn_id == y.fn_id,
85 (Value::BoundMethod(x), Value::BoundMethod(y)) => {
87 x.method == y.method && values_equal(&x.receiver, &y.receiver)
88 }
89 (Value::Error(x), Value::Error(y)) => {
91 x.kind == y.kind && x.message == y.message && x.file == y.file && x.line == y.line
92 }
93 (Value::Socket(x), Value::Socket(y)) => Rc::ptr_eq(x, y),
95 (Value::Pup(x), Value::Pup(y)) => Rc::ptr_eq(x, y),
97 (Value::Bowl(x), Value::Bowl(y)) => Rc::ptr_eq(x, y),
98 (Value::Int(_), _)
100 | (Value::Float(_), _)
101 | (Value::Decimal(_), _)
102 | (Value::Str(_), _)
103 | (Value::Bytes(_), _)
104 | (Value::Bool(_), _)
105 | (Value::None, _)
106 | (Value::List(_), _)
107 | (Value::Dict(_), _)
108 | (Value::Object(_), _)
109 | (Value::Function(_), _)
110 | (Value::Class(_), _)
111 | (Value::BoundMethod(_), _)
112 | (Value::Error(_), _)
113 | (Value::Socket(_), _)
114 | (Value::Pup(_), _)
115 | (Value::Bowl(_), _) => false,
116 }
117}
118
119pub fn eq(a: Value, b: Value) -> DogeResult {
121 Ok(Value::Bool(values_equal(&a, &b)))
122}
123
124pub fn ne(a: Value, b: Value) -> DogeResult {
126 Ok(Value::Bool(!values_equal(&a, &b)))
127}
128
129pub(crate) fn slice_contains(items: &[Value], target: &Value) -> bool {
132 items.iter().any(|element| values_equal(element, target))
133}
134
135pub fn in_(needle: Value, container: Value) -> DogeResult {
140 let found = match &container {
141 Value::List(items) => slice_contains(&items.borrow(), &needle),
142 Value::Dict(entries) => match &needle {
144 Value::Str(k) => entries.borrow().contains_key(k.as_ref()),
145 _ => false,
146 },
147 Value::Str(haystack) => match &needle {
148 Value::Str(sub) => haystack.contains(sub.as_ref()),
149 _ => {
150 return Err(DogeError::type_error(format!(
151 "can only check if a Str is in a Str, not {}",
152 needle.describe()
153 )));
154 }
155 },
156 Value::Bytes(haystack) => match &needle {
158 Value::Int(n) => n.to_u8().is_some_and(|b| haystack.contains(&b)),
159 Value::Bytes(sub) => {
160 sub.is_empty() || haystack.windows(sub.len()).any(|w| w == &sub[..])
161 }
162 _ => {
163 return Err(DogeError::type_error(format!(
164 "can only check if an Int or Bytes is in a Bytes, not {}",
165 needle.describe()
166 )));
167 }
168 },
169 Value::Int(_)
170 | Value::Float(_)
171 | Value::Decimal(_)
172 | Value::Bool(_)
173 | Value::None
174 | Value::Object(_)
175 | Value::Function(_)
176 | Value::Class(_)
177 | Value::BoundMethod(_)
178 | Value::Error(_)
179 | Value::Socket(_)
180 | Value::Pup(_)
181 | Value::Bowl(_) => {
182 return Err(DogeError::type_error(format!(
183 "in wants a List, Dict, Str, or Bytes on the right, not {}",
184 container.describe()
185 )));
186 }
187 };
188 Ok(Value::Bool(found))
189}
190
191pub fn not_in(needle: Value, container: Value) -> DogeResult {
194 match in_(needle, container)? {
195 Value::Bool(found) => Ok(Value::Bool(!found)),
196 _ => unreachable!("in_ always yields a Bool"),
197 }
198}
199
200pub(crate) fn order(a: &Value, b: &Value) -> DogeResult<Ordering> {
204 if is_numeric(a) && is_numeric(b) {
205 return numeric_cmp(a, b).ok_or_else(|| {
206 DogeError::type_error(format!(
207 "cannot compare {} and {}",
208 a.describe(),
209 b.describe()
210 ))
211 });
212 }
213 if let (Value::Str(x), Value::Str(y)) = (a, b) {
214 return Ok(x.as_ref().cmp(y.as_ref()));
215 }
216 if let (Value::Bytes(x), Value::Bytes(y)) = (a, b) {
217 return Ok(x.as_ref().cmp(y.as_ref()));
218 }
219 Err(DogeError::type_error(format!(
220 "cannot compare {} and {}",
221 a.describe(),
222 b.describe()
223 )))
224}
225
226pub fn lt(a: Value, b: Value) -> DogeResult {
228 Ok(Value::Bool(order(&a, &b)? == Ordering::Less))
229}
230
231pub fn le(a: Value, b: Value) -> DogeResult {
233 Ok(Value::Bool(matches!(
234 order(&a, &b)?,
235 Ordering::Less | Ordering::Equal
236 )))
237}
238
239pub fn gt(a: Value, b: Value) -> DogeResult {
241 Ok(Value::Bool(order(&a, &b)? == Ordering::Greater))
242}
243
244pub fn ge(a: Value, b: Value) -> DogeResult {
246 Ok(Value::Bool(matches!(
247 order(&a, &b)?,
248 Ordering::Greater | Ordering::Equal
249 )))
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn bytes_membership_subslice_and_ordering() {
258 let hay = Value::bytes([104, 105, 33]);
259 assert!(matches!(
261 in_(Value::int(105), hay.clone()).unwrap(),
262 Value::Bool(true)
263 ));
264 assert!(matches!(
265 in_(Value::int(200), hay.clone()).unwrap(),
266 Value::Bool(false)
267 ));
268 assert!(matches!(
269 in_(Value::int(999), hay.clone()).unwrap(),
270 Value::Bool(false)
271 ));
272 assert!(matches!(
274 in_(Value::bytes([105, 33]), hay.clone()).unwrap(),
275 Value::Bool(true)
276 ));
277 assert!(matches!(
278 in_(Value::bytes([104, 33]), hay.clone()).unwrap(),
279 Value::Bool(false)
280 ));
281 assert_eq!(
283 order(&Value::bytes([1, 2]), &Value::bytes([1, 3])).unwrap(),
284 Ordering::Less
285 );
286 }
287
288 #[test]
289 fn bound_methods_equal_only_on_the_same_receiver_and_name() {
290 let a = Value::object(0, "Shibe");
291 let b = Value::object(0, "Shibe");
292 assert!(values_equal(
294 &Value::bound_method(a.clone(), "speak"),
295 &Value::bound_method(a.clone(), "speak"),
296 ));
297 assert!(!values_equal(
299 &Value::bound_method(a.clone(), "speak"),
300 &Value::bound_method(a.clone(), "wag"),
301 ));
302 assert!(!values_equal(
304 &Value::bound_method(a, "speak"),
305 &Value::bound_method(b, "speak"),
306 ));
307 }
308}