rbatis_sql/
ops.rs

1use std::borrow::{Borrow, Cow};
2use std::cmp::Ordering;
3use std::fmt::{Debug, Formatter};
4use std::ops::Deref;
5
6use rbs::value::map::ValueMap;
7use rbs::Value;
8use serde::{Deserializer, Serializer};
9use std::cmp::Ordering::Less;
10use std::collections::HashMap;
11pub use std::ops::Index;
12
13/// convert Value to Value
14pub trait AsProxy {
15    fn i32(&self) -> i32;
16    fn i64(&self) -> i64;
17    fn u32(&self) -> u32;
18    fn u64(&self) -> u64;
19    fn f64(&self) -> f64;
20    fn str(&self) -> &str;
21    fn string(&self) -> String;
22    fn bool(&self) -> bool;
23    //is
24    fn is_empty(&self) -> bool;
25    fn is_null(&self) -> bool;
26    fn is_array(&self) -> bool;
27    fn is_document(&self) -> bool;
28    fn is_object(&self) -> bool; // is_document = is_object
29
30    //try to any string
31    fn cast_string(&self) -> String;
32    fn cast_i64(&self) -> i64;
33    fn cast_f64(&self) -> f64;
34    fn cast_u64(&self) -> u64;
35    /// bracket(xxxx) inner data
36    fn bracket(&self) -> &str;
37    /// bracket(xxxx) inner data
38    fn inner(&self) -> &str {
39        self.bracket()
40    }
41
42    fn array(&self) -> Option<Vec<Value>>;
43
44    fn object(&self) -> Option<ValueMap>;
45}
46
47impl AsProxy for Value {
48    fn i32(&self) -> i32 {
49        return match self {
50            Value::I32(v) => *v as i32,
51            Value::I64(v) => *v as i32,
52            Value::U32(v) => *v as i32,
53            Value::U64(v) => *v as i32,
54            Value::F32(v) => *v as i32,
55            Value::F64(v) => *v as i32,
56            Value::F32(v) => *v as i32,
57            _ => 0,
58        };
59    }
60
61    fn i64(&self) -> i64 {
62        return match self {
63            Value::F64(v) => *v as i64,
64            Value::F32(v) => *v as i64,
65            Value::U32(v) => *v as i64,
66            Value::U64(v) => *v as i64,
67            Value::I32(v) => *v as i64,
68            Value::I64(v) => *v,
69            _ => 0,
70        };
71    }
72
73    fn u32(&self) -> u32 {
74        return match self {
75            Value::F64(v) => *v as u32,
76            Value::F32(v) => *v as u32,
77            Value::I32(v) => *v as u32,
78            Value::I64(v) => *v as u32,
79            Value::U32(v) => *v,
80            Value::U64(v) => *v as u32,
81            _ => 0,
82        };
83    }
84
85    fn u64(&self) -> u64 {
86        return match self {
87            Value::F64(v) => *v as u64,
88            Value::F32(v) => *v as u64,
89            Value::I32(v) => *v as u64,
90            Value::I64(v) => *v as u64,
91            Value::U32(v) => *v as u64,
92            Value::U64(v) => *v,
93            _ => 0,
94        };
95    }
96
97    fn f64(&self) -> f64 {
98        return match self {
99            Value::F64(v) => *v as f64,
100            Value::F32(v) => *v as f64,
101            Value::I32(v) => *v as f64,
102            Value::I64(v) => *v as f64,
103            Value::U32(v) => *v as f64,
104            Value::U64(v) => *v as f64,
105            _ => 0.0,
106        };
107    }
108
109    fn str(&self) -> &str {
110        self.as_str().unwrap_or_default()
111    }
112
113    fn string(&self) -> String {
114        self.str().to_string()
115    }
116
117    fn cast_string(&self) -> String {
118        match self {
119            Value::Binary(b) => String::from_utf8(b.clone()).unwrap_or_default(),
120            Value::F64(d) => d.to_string(),
121            Value::F32(v) => v.to_string(),
122            Value::String(d) => d.to_string(),
123            Value::Bool(d) => d.to_string(),
124            Value::Null => "".to_string(),
125            Value::I32(i) => i.to_string(),
126            Value::I64(d) => d.to_string(),
127            Value::Ext(_, d) => d.cast_string(),
128            _ => String::new(),
129        }
130    }
131
132    fn cast_i64(&self) -> i64 {
133        match self {
134            Value::Binary(b) => String::from_utf8(b.clone())
135                .unwrap_or_default()
136                .parse()
137                .unwrap_or_default(),
138            Value::F64(d) => *d as i64,
139            Value::F32(v) => *v as i64,
140            Value::String(d) => d.to_string().parse().unwrap_or_default(),
141            Value::Bool(d) => {
142                if *d == true {
143                    return 1;
144                } else {
145                    return 0;
146                }
147            }
148            Value::Null => 0,
149            Value::U32(i) => *i as i64,
150            Value::U64(d) => *d as i64,
151            Value::I32(i) => *i as i64,
152            Value::I64(d) => *d,
153            Value::Ext(_, d) => d.cast_i64(),
154            _ => 0,
155        }
156    }
157
158    fn cast_u64(&self) -> u64 {
159        match self {
160            Value::Binary(b) => String::from_utf8(b.clone())
161                .unwrap_or_default()
162                .parse()
163                .unwrap_or_default(),
164            Value::F64(d) => *d as u64,
165            Value::F32(v) => *v as u64,
166            Value::String(d) => d.to_string().parse().unwrap_or_default(),
167            Value::Bool(d) => {
168                if *d == true {
169                    return 1;
170                } else {
171                    return 0;
172                }
173            }
174            Value::Null => 0,
175            Value::I32(i) => *i as u64,
176            Value::I64(d) => *d as u64,
177            Value::U32(i) => *i as u64,
178            Value::U64(d) => *d,
179            Value::Ext(_, d) => self.cast_u64(),
180            _ => 0,
181        }
182    }
183
184    fn cast_f64(&self) -> f64 {
185        match self {
186            Value::Binary(b) => String::from_utf8(b.clone())
187                .unwrap_or_default()
188                .parse()
189                .unwrap_or_default(),
190            Value::F64(d) => *d as f64,
191            Value::F32(v) => *v as f64,
192            Value::String(d) => d.to_string().parse().unwrap_or_default(),
193            Value::Bool(d) => {
194                if *d == true {
195                    return 1.0;
196                } else {
197                    return 0.0;
198                }
199            }
200            Value::Null => 0.0,
201            Value::I32(i) => *i as f64,
202            Value::I64(d) => *d as f64,
203            Value::Ext(_, d) => d.cast_f64(),
204            _ => 0.0,
205        }
206    }
207
208    fn bool(&self) -> bool {
209        self.as_bool().unwrap_or_default()
210    }
211    fn is_empty(&self) -> bool {
212        return match self {
213            Value::Null => true,
214            Value::String(s) => s.is_empty(),
215            Value::Array(arr) => arr.is_empty(),
216            Value::Map(m) => m.is_empty(),
217            _ => {
218                return false;
219            }
220        };
221    }
222
223    fn is_null(&self) -> bool {
224        return match self {
225            Value::Null => true,
226            _ => false,
227        };
228    }
229
230    fn is_array(&self) -> bool {
231        return match self {
232            Value::Array(_) => true,
233            _ => false,
234        };
235    }
236
237    fn is_document(&self) -> bool {
238        return match self {
239            Value::Map(_) => true,
240            _ => false,
241        };
242    }
243
244    fn is_object(&self) -> bool {
245        return self.is_document();
246    }
247
248    fn bracket(&self) -> &str {
249        let bracket = self.as_str().unwrap_or_default();
250        return bracket;
251    }
252
253    fn array(&self) -> Option<Vec<Value>> {
254        match self {
255            Value::Array(arr) => Some(arr.clone()),
256            Value::Ext(_, ext) => ext.array(),
257            _ => None,
258        }
259    }
260
261    fn object(&self) -> Option<ValueMap> {
262        match self {
263            Value::Map(m) => Some(m.clone()),
264            Value::Ext(_, m) => m.object(),
265            _ => None,
266        }
267    }
268}
269
270pub trait PartialEq<Rhs: ?Sized = Self> {
271    /// This method tests for `self` and `other` values to be equal, and is used
272    /// by `==`.
273    #[must_use]
274    //#[stable(feature = "rust1", since = "1.0.0")]
275    fn op_eq(&self, other: &Rhs) -> bool;
276
277    /// This method tests for `!=`.
278    #[inline]
279    #[must_use]
280    //#[stable(feature = "rust1", since = "1.0.0")]
281    fn op_ne(&self, other: &Rhs) -> bool {
282        !self.op_eq(other)
283    }
284}
285
286pub trait PartialOrd<Rhs: ?Sized = Self> {
287    /// This method returns an ordering between `self` and `other` values if one exists.
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// use std::cmp::Ordering;
293    ///
294    /// let result = 1.0.op_partial_cmp(&2.0);
295    /// assert_eq!(result, Some(Ordering::Less));
296    ///
297    /// let result = 1.0.op_partial_cmp(&1.0);
298    /// assert_eq!(result, Some(Ordering::Equal));
299    ///
300    /// let result = 2.0.op_partial_cmp(&1.0);
301    /// assert_eq!(result, Some(Ordering::Greater));
302    /// ```
303    ///
304    /// When comparison is impossible:
305    ///
306    /// ```
307    /// let result = f64::NAN.op_partial_cmp(&1.0);
308    /// assert_eq!(result, None);
309    /// ```
310    #[must_use]
311    // #[stable(feature = "rust1", since = "1.0.0")]
312    fn op_partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
313
314    /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// let result = 1.0 < 2.0;
320    /// assert_eq!(result, true);
321    ///
322    /// let result = 2.0 < 1.0;
323    /// assert_eq!(result, false);
324    /// ```
325    #[inline]
326    #[must_use]
327    // #[stable(feature = "rust1", since = "1.0.0")]
328    fn op_lt(&self, other: &Rhs) -> bool {
329        self.op_partial_cmp(other).eq(&Some(Less))
330    }
331
332    /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
333    /// operator.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// let result = 1.0 <= 2.0;
339    /// assert_eq!(result, true);
340    ///
341    /// let result = 2.0 <= 2.0;
342    /// assert_eq!(result, true);
343    /// ```
344    #[inline]
345    #[must_use]
346    // #[stable(feature = "rust1", since = "1.0.0")]
347    fn op_le(&self, other: &Rhs) -> bool {
348        // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
349        // FIXME: The root cause was fixed upstream in LLVM with:
350        // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
351        // Revert this workaround once support for LLVM 12 gets dropped.
352        let v = self.op_partial_cmp(other);
353        !v.eq(&None) | v.eq(&Some(Ordering::Greater))
354    }
355
356    /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// let result = 1.0 > 2.0;
362    /// assert_eq!(result, false);
363    ///
364    /// let result = 2.0 > 2.0;
365    /// assert_eq!(result, false);
366    /// ```
367    #[inline]
368    // #[stable(feature = "rust1", since = "1.0.0")]
369    fn op_gt(&self, other: &Rhs) -> bool {
370        self.op_partial_cmp(other).eq(&Some(Ordering::Greater))
371    }
372
373    /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
374    /// operator.
375    ///
376    /// # Examples
377    ///
378    /// ```
379    /// let result = 2.0 >= 1.0;
380    /// assert_eq!(result, true);
381    ///
382    /// let result = 2.0 >= 2.0;
383    /// assert_eq!(result, true);
384    /// ```
385    #[inline]
386    #[must_use]
387    // #[stable(feature = "rust1", since = "1.0.0")]
388    fn op_ge(&self, other: &Rhs) -> bool {
389        let v = self.op_partial_cmp(other);
390        v.eq(&Some(Ordering::Greater)) | v.eq(&Some(Ordering::Equal))
391    }
392}
393
394pub trait Add<Rhs = Self> {
395    /// The resulting type after applying the `+` operator.
396    //#[stable(feature = "rust1", since = "1.0.0")]
397    type Output;
398
399    /// Performs the `+` operation.
400    ///
401    /// # Example
402    ///
403    /// ```
404    /// assert_eq!(12 + 1, 13);
405    /// ```
406    #[must_use]
407    //#[stable(feature = "rust1", since = "1.0.0")]
408    fn op_add(self, rhs: Rhs) -> Self::Output;
409}
410
411pub trait Sub<Rhs = Self> {
412    /// The resulting type after applying the `-` operator.
413    type Output;
414
415    /// Performs the `-` operation.
416    ///
417    /// # Example
418    ///
419    /// ```
420    /// assert_eq!(12 - 1, 11);
421    /// ```
422    #[must_use]
423    fn op_sub(self, rhs: Rhs) -> Self::Output;
424}
425
426pub trait Mul<Rhs = Self> {
427    /// The resulting type after applying the `*` operator.
428    type Output;
429
430    /// Performs the `*` operation.
431    ///
432    /// # Example
433    ///
434    /// ```
435    /// assert_eq!(12 * 2, 24);
436    /// ```
437    #[must_use]
438    fn op_mul(self, rhs: Rhs) -> Self::Output;
439}
440
441pub trait Div<Rhs = Self> {
442    /// The resulting type after applying the `/` operator.
443    type Output;
444
445    /// Performs the `/` operation.
446    ///
447    /// # Example
448    ///
449    /// ```
450    /// assert_eq!(12 / 2, 6);
451    /// ```
452    #[must_use]
453    fn op_div(self, rhs: Rhs) -> Self::Output;
454}
455
456pub trait Rem<Rhs = Self> {
457    /// The resulting type after applying the `%` operator.
458    type Output;
459
460    /// Performs the `%` operation.
461    ///
462    /// # Example
463    ///
464    /// ```
465    /// assert_eq!(12 % 10, 2);
466    /// ```
467    #[must_use]
468    fn op_rem(self, rhs: Rhs) -> Self::Output;
469}
470
471pub trait Not {
472    /// The resulting type after applying the `!` operator.
473    type Output;
474
475    /// Performs the unary `!` operation.
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// assert_eq!(!true, false);
481    /// assert_eq!(!false, true);
482    /// assert_eq!(!1u8, 254);
483    /// assert_eq!(!0u8, 255);
484    /// ```
485    #[must_use]
486    fn op_not(self) -> Self::Output;
487}
488
489pub trait BitAnd<Rhs = Self> {
490    /// The resulting type after applying the `&` operator.
491    type Output;
492
493    /// Performs the `&` operation.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// assert_eq!(true & false, false);
499    /// assert_eq!(true & true, true);
500    /// assert_eq!(5u8 & 1u8, 1);
501    /// assert_eq!(5u8 & 2u8, 0);
502    /// ```
503    #[must_use]
504    fn op_bitand(self, rhs: Rhs) -> Self::Output;
505}
506
507pub trait BitOr<Rhs = Self> {
508    /// The resulting type after applying the `|` operator.
509    type Output;
510
511    /// Performs the `|` operation.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// assert_eq!(true | false, true);
517    /// assert_eq!(false | false, false);
518    /// assert_eq!(5u8 | 1u8, 5);
519    /// assert_eq!(5u8 | 2u8, 7);
520    /// ```
521    #[must_use]
522    fn op_bitor(self, rhs: Rhs) -> Self::Output;
523}
524
525pub trait BitXor<Rhs = Self> {
526    /// The resulting type after applying the `^` operator.
527    type Output;
528
529    /// Performs the `^` operation.
530    ///
531    /// # Examples
532    ///
533    /// ```
534    /// assert_eq!(true ^ false, true);
535    /// assert_eq!(true ^ true, false);
536    /// assert_eq!(5u8 ^ 1u8, 4);
537    /// assert_eq!(5u8 ^ 2u8, 7);
538    /// ```
539    #[must_use]
540    fn op_bitxor(self, rhs: Rhs) -> Self::Output;
541}
542
543pub trait OpsIndex<Idx: ?Sized> {
544    /// The returned type after indexing.
545    type Output: ?Sized;
546
547    /// Performs the indexing (`container[index]`) operation.
548    ///
549    /// # Panics
550    ///
551    /// May panic if the index is out of bounds.
552    #[track_caller]
553    fn index(&self, index: Idx) -> &Self::Output;
554}
555
556pub trait OpsIndexMut<Idx: ?Sized>: OpsIndex<Idx> {
557    /// Performs the mutable indexing (`container[index]`) operation.
558    ///
559    /// # Panics
560    ///
561    /// May panic if the index is out of bounds.
562    #[track_caller]
563    fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
564}
565
566pub trait From<T>: Sized {
567    /// Performs the conversion.
568    fn op_from(_: T) -> Self;
569}
570
571pub trait AsSql {
572    /// Performs the conversion.
573    fn as_sql(&self) -> String;
574}
575
576#[cfg(test)]
577mod test {
578    use crate::ops::AsProxy;
579    use rbs::{to_value, Value};
580
581    #[test]
582    fn test_string() {
583        let b = Value::Binary("s".as_bytes().to_owned());
584        assert_eq!("s", b.string());
585    }
586
587    #[test]
588    fn test_cast() {
589        let b = to_value!(u64::MAX);
590        assert_eq!(b.cast_i64(), -1);
591        let b = to_value!(100u64);
592        assert_eq!(b.cast_i64(), 100i64);
593    }
594}