jsonb 0.5.6

JSONB implement in Rust.
Documentation
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file contains functions that specifically operate on JSONB array values.

use crate::core::ArrayBuilder;
use crate::core::ArrayDistinctBuilder;
use crate::core::ArrayIterator;
use crate::core::JsonbItemType;
use crate::error::*;
use crate::OwnedJsonb;
use crate::RawJsonb;

impl RawJsonb<'_> {
    /// Returns the number of elements in a JSONB array.
    ///
    /// If the JSONB data is an array, this function returns the number of elements in the array.
    /// If the JSONB data is not an array (e.g., it's an object or a scalar), this function returns `None`.
    /// An error is returned if the JSONB data is invalid.
    ///
    /// # Arguments
    ///
    /// * `self` - The JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(Some(usize))` - the number of elements in the array.
    /// * `Ok(None)` - If the input is not an array.
    /// * `Err(Error)` - If the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonb::OwnedJsonb;
    ///
    /// let arr_jsonb = "[1,2,3]".parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = arr_jsonb.as_raw();
    /// let len = raw_jsonb.array_length().unwrap();
    /// assert_eq!(len, Some(3));
    ///
    /// let obj_jsonb = r#"{"a": 1, "b": {"c": 2, "d": 3}}"#.parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = obj_jsonb.as_raw();
    /// let len = raw_jsonb.array_length().unwrap();
    /// assert_eq!(len, None);
    /// ```
    pub fn array_length(&self) -> Result<Option<usize>> {
        let jsonb_item_type = self.jsonb_item_type()?;
        if let JsonbItemType::Array(len) = jsonb_item_type {
            Ok(Some(len))
        } else {
            Ok(None)
        }
    }

    /// Extracts the values from a JSONB array.
    ///
    /// If the JSONB value is an array, this function returns a vector of `OwnedJsonb` representing the array elements.
    /// If the JSONB value is not an array (e.g., it's an object or a scalar), this function returns `None`.
    ///
    /// # Arguments
    ///
    /// * `self` - The JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(Some(Vec<OwnedJsonb>))` - A vector of `OwnedJsonb` values if the input is an array.
    /// * `Ok(None)` - If the input is not an array.
    /// * `Err(Error)` - If the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// // Array values extraction
    /// let arr_jsonb = r#"[1, "hello", {"a": 1}]"#.parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = arr_jsonb.as_raw();
    /// let values_result = raw_jsonb.array_values();
    /// assert!(values_result.is_ok());
    ///
    /// let values = values_result.unwrap().unwrap();
    /// assert_eq!(values.len(), 3);
    ///
    /// assert_eq!(values[0].to_string(), "1");
    /// assert_eq!(values[1].to_string(), r#""hello""#);
    /// assert_eq!(values[2].to_string(), r#"{"a":1}"#);
    ///
    /// // Object - returns None
    /// let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = obj_jsonb.as_raw();
    /// let values_result = raw_jsonb.array_values();
    /// assert!(values_result.is_ok());
    /// assert!(values_result.unwrap().is_none());
    ///
    /// // Scalar - returns None
    /// let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = scalar_jsonb.as_raw();
    /// let values_result = raw_jsonb.array_values();
    /// assert!(values_result.is_ok());
    /// assert!(values_result.unwrap().is_none());
    /// ```
    pub fn array_values(&self) -> Result<Option<Vec<OwnedJsonb>>> {
        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                let mut values = Vec::with_capacity(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    let value = OwnedJsonb::from_item(item)?;
                    values.push(value);
                }
                Ok(Some(values))
            }
            None => Ok(None),
        }
    }

    /// Returns a JSONB array with duplicate elements removed.
    ///
    /// This function takes a JSONB value as input and returns a new JSONB array containing only the unique elements from the input.
    ///
    /// The behavior depends on the input type:
    ///
    /// * **Array:** Returns a new array containing only the unique elements from the input array.
    /// * **Object/Scalar:** Returns a new array containing the original object or salar as its only element.
    /// * **Invalid JSONB:** Returns an error.
    ///
    /// # Arguments
    ///
    /// * `self` - The JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(OwnedJsonb)` - A JSONB array containing only the unique elements from the input.
    /// * `Err(Error)` - If the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// // Array with duplicates
    /// let arr_jsonb = r#"[1, 2, 2, 3, 1, 4]"#.parse::<OwnedJsonb>().unwrap();
    /// let distinct = arr_jsonb.as_raw().array_distinct().unwrap();
    /// assert_eq!(distinct.to_string(), "[1,2,3,4]"); // Order may vary
    ///
    /// // Array with only unique elements
    /// let arr_jsonb = r#"[1, 2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
    /// let distinct = arr_jsonb.as_raw().array_distinct().unwrap();
    /// assert_eq!(distinct.to_string(), "[1,2,3,4]"); // Order may vary
    ///
    /// // Object
    /// let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let distinct = obj_jsonb.as_raw().array_distinct().unwrap();
    /// assert_eq!(distinct.to_string(), r#"[{"a":1}]"#);
    ///
    /// // Scalar
    /// let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
    /// let distinct = scalar_jsonb.as_raw().array_distinct().unwrap();
    /// assert_eq!(distinct.to_string(), "[1]");
    ///
    /// // Invalid JSONB data
    /// let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
    /// let invalid_raw_jsonb = invalid_jsonb.as_raw();
    /// let result = invalid_raw_jsonb.array_distinct();
    /// assert!(result.is_err());
    /// ```
    pub fn array_distinct(&self) -> Result<OwnedJsonb> {
        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayDistinctBuilder::new(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    builder.push_jsonb_item(item);
                }
                builder.build()
            }
            None => {
                let mut builder = ArrayBuilder::with_capacity(1);
                builder.push_raw_jsonb(*self);
                builder.build()
            }
        }
    }

    /// Computes the intersection of two JSONB arrays or the containment check for objects and scalars.
    ///
    /// This function calculates the intersection of two JSONB arrays or checks if one JSONB value is contained within another.
    ///
    /// The behavior depends on the input types:
    ///
    /// * **Array + Array:** Returns a new array containing only the elements that are present in *both* input arrays.
    ///   The order of elements is not guaranteed. Duplicate elements are handled correctly,
    ///   the multiplicity of elements in the intersection is the minimum of their multiplicities in the input arrays.
    /// * **Object/Scalar + Object/Scalar:** Returns a new array containing the `self` value only if it's present in the `other` value.
    /// * **Invalid input:** Returns an error if either input is not an array, object, or scalar.
    ///
    /// # Arguments
    ///
    /// * `self` - The first JSONB value.
    /// * `other` - The second JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(OwnedJsonb)` - The intersection array (for array + array) or a single-element array indicating containment (for other combinations).
    /// * `Err(Error)` - If any of the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// // Array intersection
    /// let arr1 = r#"[1, 2, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
    /// let intersection = arr1.as_raw().array_intersection(&arr2.as_raw()).unwrap();
    /// assert_eq!(intersection.to_string(), "[2,3]"); // Order may vary, duplicates handled
    ///
    /// let arr1 = r#"[1, 1, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[1, 1, 1, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let intersection = arr1.as_raw().array_intersection(&arr2.as_raw()).unwrap();
    /// assert_eq!(intersection.to_string(), "[1,1,3]"); // Order may vary
    ///
    /// // Object containment (checks for complete equality)
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let contained = obj1.as_raw().array_intersection(&obj2.as_raw()).unwrap();
    /// assert_eq!(contained.to_string(), r#"[{"a":1}]"#);
    ///
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
    /// let contained = obj1.as_raw().array_intersection(&obj2.as_raw()).unwrap();
    /// assert_eq!(contained.to_string(), "[]"); // Not contained
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
    /// let contained = scalar1
    ///     .as_raw()
    ///     .array_intersection(&scalar2.as_raw())
    ///     .unwrap();
    /// assert_eq!(contained.to_string(), "[1]"); // Contained
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
    /// let contained = scalar1
    ///     .as_raw()
    ///     .array_intersection(&scalar2.as_raw())
    ///     .unwrap();
    /// assert_eq!(contained.to_string(), "[]"); // Not contained
    /// ```
    pub fn array_intersection(&self, other: &RawJsonb) -> Result<OwnedJsonb> {
        let other_array_iter_opt = ArrayIterator::new(*other)?;
        let mut other_builder = match other_array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayDistinctBuilder::new(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    builder.push_jsonb_item(item);
                }
                builder
            }
            None => {
                let mut builder = ArrayDistinctBuilder::new(1);
                builder.push_raw_jsonb(*other);
                builder
            }
        };

        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayBuilder::with_capacity(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    if other_builder.pop_jsonb_item(item.clone()).is_some() {
                        builder.push_jsonb_item(item);
                    }
                }
                builder.build()
            }
            None => {
                let mut builder = ArrayBuilder::with_capacity(1);
                if other_builder.pop_raw_jsonb(*self).is_some() {
                    builder.push_raw_jsonb(*self);
                }
                builder.build()
            }
        }
    }

    /// Computes the set difference between two JSONB arrays or checks for non-containment of objects and scalars.
    ///
    /// This function calculates the set difference between two JSONB arrays or checks if one JSONB value is *not* contained within another.
    ///
    /// The behavior depends on the input types:
    ///
    /// * **Array + Array:** Returns a new array containing only the elements that are present in the `self` array but *not* in the `other` array.
    ///   The order of elements is not guaranteed. Duplicate elements are handled correctly, if an element appears multiple times in `self` but is present in `other`,
    ///   it will be removed from the result only up to the number of times it appears in `other`.
    /// * **Object/Scalar + Object/Scalar:** Returns a new array containing the `self` value if it's *not* contained in the `other` value.
    /// * **Invalid input:** Returns an error if either input is not an array, object, or scalar.
    ///
    /// # Arguments
    ///
    /// * `self` - The first JSONB value.
    /// * `other` - The second JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(OwnedJsonb)` - The resulting array after removing elements from `self` that are present in `other`.
    /// * `Err(Error)` - If any of the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// // Array except
    /// let arr1 = r#"[1, 2, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
    /// let except = arr1.as_raw().array_except(&arr2.as_raw()).unwrap();
    /// assert_eq!(except.to_string(), "[1,2]"); // Order may vary, duplicates handled
    ///
    /// let arr1 = r#"[1, 1, 2, 3, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[1, 3, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let except = arr1.as_raw().array_except(&arr2.as_raw()).unwrap();
    /// assert_eq!(except.to_string(), "[1,2]"); // Order may vary
    ///
    /// // Object non-containment
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let not_contained = obj1.as_raw().array_except(&obj2.as_raw()).unwrap();
    /// assert_eq!(not_contained.to_string(), "[]"); // Completely contained
    ///
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
    /// let not_contained = obj1.as_raw().array_except(&obj2.as_raw()).unwrap();
    /// assert_eq!(not_contained.to_string(), r#"[{"a":1}]"#); // Not contained
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
    /// let not_contained = scalar1.as_raw().array_except(&scalar2.as_raw()).unwrap();
    /// assert_eq!(not_contained.to_string(), "[]"); // Contained
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
    /// let not_contained = scalar1.as_raw().array_except(&scalar2.as_raw()).unwrap();
    /// assert_eq!(not_contained.to_string(), "[1]"); // Not contained
    /// ```
    pub fn array_except(&self, other: &RawJsonb) -> Result<OwnedJsonb> {
        let other_array_iter_opt = ArrayIterator::new(*other)?;
        let mut other_builder = match other_array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayDistinctBuilder::new(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    builder.push_jsonb_item(item);
                }
                builder
            }
            None => {
                let mut builder = ArrayDistinctBuilder::new(1);
                builder.push_raw_jsonb(*other);
                builder
            }
        };

        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayBuilder::with_capacity(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    if other_builder.pop_jsonb_item(item.clone()).is_none() {
                        builder.push_jsonb_item(item);
                    }
                }
                builder.build()
            }
            None => {
                let mut builder = ArrayBuilder::with_capacity(1);
                if other_builder.pop_raw_jsonb(*self).is_none() {
                    builder.push_raw_jsonb(*self);
                }
                builder.build()
            }
        }
    }

    /// Checks if two JSONB arrays or a JSONB array and an object/scalar have any elements in common.
    ///
    /// This function determines whether two JSONB arrays, or a JSONB array and an object/scalar, share any common elements.
    ///
    /// The behavior depends on the input types:
    ///
    /// * **Array + Array:** Returns `true` if the two arrays have at least one element in common; otherwise, returns `false`.
    /// * **Array + Object/Scalar:** Returns `true` if the array contains the object/scalar; otherwise, returns `false`.
    /// * **Object/Scalar + Array:** Returns `true` if the array contains the object/scalar; otherwise, returns `false`.
    /// * **Object/Scalar + Object/Scalar:** Returns `true` only if both values are exactly equal. This is effectively an equality check.
    /// * **Invalid input:** Returns an error if either input is invalid JSONB data.
    ///
    /// # Arguments
    ///
    /// * `self` - The first JSONB value.
    /// * `other` - The second JSONB value.
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - If the two JSONB values have at least one element in common.
    /// * `Ok(false)` - If the two JSONB values have no elements in common.
    /// * `Err(Error)` - If any of the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// // Array overlap
    /// let arr1 = r#"[1, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[3, 4, 5]"#.parse::<OwnedJsonb>().unwrap();
    /// assert!(arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // True because of '3'
    ///
    /// let arr1 = r#"[1, 2]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[3, 4]"#.parse::<OwnedJsonb>().unwrap();
    /// assert!(!arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // False, no common elements
    ///
    /// let arr1 = r#"[1, 2, 2]"#.parse::<OwnedJsonb>().unwrap();
    /// let arr2 = r#"[2, 3]"#.parse::<OwnedJsonb>().unwrap();
    /// assert!(arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // True, '2' is common
    ///
    /// // Object/scalar overlap (requires complete equality for true)
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// assert!(obj1.as_raw().array_overlap(&obj2.as_raw()).unwrap()); // True, completely equal
    ///
    /// let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
    /// assert!(!obj1.as_raw().array_overlap(&obj2.as_raw()).unwrap()); // False, not equal
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
    /// assert!(scalar1.as_raw().array_overlap(&scalar2.as_raw()).unwrap()); // True, equal
    ///
    /// let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
    /// let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
    /// assert!(!scalar1.as_raw().array_overlap(&scalar2.as_raw()).unwrap()); // False, not equal
    ///
    /// // Invalid input
    /// let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
    /// let invalid_raw_jsonb = invalid_jsonb.as_raw();
    /// let result = invalid_raw_jsonb.array_overlap(&arr1.as_raw());
    /// assert!(result.is_err()); // Returns an error
    /// ```
    pub fn array_overlap(&self, other: &RawJsonb) -> Result<bool> {
        let other_array_iter_opt = ArrayIterator::new(*other)?;
        let mut other_builder = match other_array_iter_opt {
            Some(mut array_iter) => {
                let mut builder = ArrayDistinctBuilder::new(array_iter.len());
                for item_result in &mut array_iter {
                    let item = item_result?;
                    builder.push_jsonb_item(item);
                }
                builder
            }
            None => {
                let mut builder = ArrayDistinctBuilder::new(1);
                builder.push_raw_jsonb(*other);
                builder
            }
        };

        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                for item_result in &mut array_iter {
                    let item = item_result?;
                    if other_builder.pop_jsonb_item(item).is_some() {
                        return Ok(true);
                    }
                }
            }
            None => {
                if other_builder.pop_raw_jsonb(*self).is_some() {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// Inserts a new element into a JSONB array at the specified position.
    ///
    /// This function inserts the `new_val` into the JSONB array at the position specified by `pos`.
    /// The `pos` parameter can be positive or negative:
    ///
    /// * **Positive index:** 0-based index from the beginning of the array.
    /// * **Negative index:** 1-based index from the end of the array (e.g., -1 refers to the last element).
    ///
    /// If `pos` is less than 0, the element is inserted at the beginning of the array.
    /// If `pos` is greater than or equal to the length of the array, the element is appended to the end.
    /// If the input is an object or scalar, it's treated as a single element array.
    ///
    /// # Arguments
    ///
    /// * `self` - The JSONB array.
    /// * `pos` - The position at which to insert the new element (positive or negative index).
    /// * `new_val` - The new JSONB element to insert.
    ///
    /// # Returns
    ///
    /// * `Ok(OwnedJsonb)` - The modified JSONB array with the new element inserted.
    /// * `Err(Error)` - If any of the input JSONB data is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use jsonb::OwnedJsonb;
    ///
    /// let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = arr_jsonb.as_raw();
    /// let new_jsonb = "4".parse::<OwnedJsonb>().unwrap();
    /// let new_raw_jsonb = new_jsonb.as_raw();
    ///
    /// // Insert at index 1
    /// let inserted = raw_jsonb.array_insert(1, &new_raw_jsonb).unwrap();
    /// assert_eq!(inserted.to_string(), "[1,4,2,3]");
    ///
    /// // Insert at the beginning (pos = 0)
    /// let new_raw_jsonb = new_jsonb.as_raw();
    /// let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb).unwrap();
    /// assert_eq!(inserted.to_string(), "[4,1,2,3]");
    ///
    /// // Insert at the end (pos >= length)
    /// let new_raw_jsonb = new_jsonb.as_raw();
    /// let inserted = raw_jsonb.array_insert(10, &new_raw_jsonb).unwrap();
    /// assert_eq!(inserted.to_string(), "[1,2,3,4]");
    ///
    /// // Insert into an object
    /// let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = obj_jsonb.as_raw();
    /// let new_jsonb = "2".parse::<OwnedJsonb>().unwrap();
    /// let new_raw_jsonb = new_jsonb.as_raw();
    /// let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb);
    /// assert_eq!(inserted.unwrap().to_string(), r#"[2,{"a":1}]"#);
    ///
    /// // Insert into a scalar
    /// let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
    /// let raw_jsonb = scalar_jsonb.as_raw();
    /// let new_jsonb = "2".parse::<OwnedJsonb>().unwrap();
    /// let new_raw_jsonb = new_jsonb.as_raw();
    /// let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb);
    /// assert_eq!(inserted.unwrap().to_string(), "[2,1]");
    /// ```
    pub fn array_insert(&self, pos: i32, new_val: &RawJsonb) -> Result<OwnedJsonb> {
        let len = self.array_length()?.unwrap_or(1);

        let idx = if pos < 0 { len as i32 - pos.abs() } else { pos };
        let idx = if idx < 0 {
            0
        } else if idx > len as i32 {
            len
        } else {
            idx as usize
        };

        let mut builder = ArrayBuilder::with_capacity(len + 1);
        let array_iter_opt = ArrayIterator::new(*self)?;
        match array_iter_opt {
            Some(mut array_iter) => {
                let mut i = 0;
                for item_result in &mut array_iter {
                    let item = item_result?;
                    if i == idx {
                        builder.push_raw_jsonb(*new_val);
                    }
                    builder.push_jsonb_item(item);
                    i += 1;
                }
                if i == idx {
                    builder.push_raw_jsonb(*new_val);
                }
            }
            None => {
                if idx == 0 {
                    builder.push_raw_jsonb(*new_val);
                    builder.push_raw_jsonb(*self);
                } else {
                    builder.push_raw_jsonb(*self);
                    builder.push_raw_jsonb(*new_val);
                }
            }
        }
        builder.build()
    }
}