Skip to main content

rune/modules/
vec.rs

1//! The [`Vec`] dynamic vector.
2
3use core::cmp::Ordering;
4
5use crate as rune;
6use crate::alloc;
7use crate::alloc::prelude::*;
8use crate::runtime::slice::Iter;
9use crate::runtime::{
10    EnvProtocolCaller, Formatter, Function, Hasher, Ref, TypeOf, Value, Vec, VmError, VmErrorKind,
11    Worklist,
12};
13use crate::{docstring, ContextError, Module};
14
15/// The [`Vec`] dynamic vector.
16///
17/// The vector type is a growable dynamic array that can hold an ordered
18/// collection of values.
19///
20/// Tuples in Rune are declared with the special `[a]` syntax, but can also be
21/// interacted with through the fundamental [`Vec`] type.
22///
23/// The vector type has support for native pattern matching:
24///
25/// ```rune
26/// let value = [1, 2];
27///
28/// if let [a, b] = value {
29///     assert_eq!(a, 1);
30///     assert_eq!(b, 2);
31/// }
32/// ```
33///
34/// # Examples
35///
36/// ```rune
37/// let empty = [];
38/// let one = [10];
39/// let two = [10, 20];
40///
41/// assert!(empty.is_empty());
42/// assert_eq!(one.0, 10);
43/// assert_eq!(two.0, 10);
44/// assert_eq!(two.1, 20);
45/// ```
46#[rune::module(::std::vec)]
47pub fn module() -> Result<Module, ContextError> {
48    let mut m = Module::from_meta(self::module__meta)?;
49
50    m.ty::<Vec>()?.docs(docstring! {
51        /// A dynamic vector.
52        ///
53        /// This is the type that is constructed in rune when an array expression such as `[1, 2, 3]` is used.
54        ///
55        /// # Comparisons
56        ///
57        /// Shorter sequences are considered smaller than longer ones, and vice versa.
58        ///
59        /// ```rune
60        /// assert!([1, 2, 3] < [1, 2, 3, 4]);
61        /// assert!([1, 2, 3] < [1, 2, 4]);
62        /// assert!([1, 2, 4] > [1, 2, 3]);
63        /// ```
64    })?;
65
66    m.function_meta(vec_new)?;
67    m.function_meta(vec_with_capacity)?;
68    m.function_meta(len)?;
69    m.function_meta(is_empty)?;
70    m.function_meta(capacity)?;
71    m.function_meta(get)?;
72    m.function_meta(clear)?;
73    m.function_meta(extend)?;
74    m.function_meta(Vec::rune_iter__meta)?;
75    m.function_meta(pop)?;
76    m.function_meta(push)?;
77    m.function_meta(remove)?;
78    m.function_meta(insert)?;
79    m.function_meta(sort_by)?;
80    m.function_meta(sort)?;
81    m.function_meta(into_iter__meta)?;
82    m.function_meta(index_get)?;
83    m.function_meta(index_set)?;
84    m.function_meta(resize)?;
85    m.function_meta(debug_fmt__meta)?;
86
87    m.function_meta(clone__meta)?;
88    m.implement_trait::<Vec>(rune::item!(::std::clone::Clone))?;
89
90    m.function_meta(partial_eq__meta)?;
91    m.implement_trait::<Vec>(rune::item!(::std::cmp::PartialEq))?;
92
93    m.function_meta(eq__meta)?;
94    m.implement_trait::<Vec>(rune::item!(::std::cmp::Eq))?;
95
96    m.function_meta(partial_cmp__meta)?;
97    m.implement_trait::<Vec>(rune::item!(::std::cmp::PartialOrd))?;
98
99    m.function_meta(cmp__meta)?;
100    m.implement_trait::<Vec>(rune::item!(::std::cmp::Ord))?;
101
102    m.function_meta(hash)?;
103    Ok(m)
104}
105
106/// Constructs a new, empty dynamic `Vec`.
107///
108/// The vector will not allocate until elements are pushed onto it.
109///
110/// # Examples
111///
112/// ```rune
113/// let vec = Vec::new();
114/// ```
115#[rune::function(free, path = Vec::new)]
116fn vec_new() -> Vec {
117    Vec::new()
118}
119
120/// Constructs a new, empty dynamic `Vec` with at least the specified capacity.
121///
122/// The vector will be able to hold at least `capacity` elements without
123/// reallocating. This method is allowed to allocate for more elements than
124/// `capacity`. If `capacity` is 0, the vector will not allocate.
125///
126/// It is important to note that although the returned vector has the minimum
127/// *capacity* specified, the vector will have a zero *length*. For an
128/// explanation of the difference between length and capacity, see *[Capacity
129/// and reallocation]*.
130///
131/// If it is important to know the exact allocated capacity of a `Vec`, always
132/// use the [`capacity`] method after construction.
133///
134/// [Capacity and reallocation]: #capacity-and-reallocation
135/// [`capacity`]: Vec::capacity
136///
137/// # Panics
138///
139/// Panics if the new capacity exceeds `isize::MAX` bytes.
140///
141/// # Examples
142///
143/// ```rune
144/// let vec = Vec::with_capacity(10);
145///
146/// // The vector contains no items, even though it has capacity for more
147/// assert_eq!(vec.len(), 0);
148/// assert!(vec.capacity() >= 10);
149///
150/// // These are all done without reallocating...
151/// for i in 0..10 {
152///     vec.push(i);
153/// }
154///
155/// assert_eq!(vec.len(), 10);
156/// assert!(vec.capacity() >= 10);
157///
158/// // ...but this may make the vector reallocate
159/// vec.push(11);
160/// assert_eq!(vec.len(), 11);
161/// assert!(vec.capacity() >= 11);
162/// ```
163#[rune::function(free, path = Vec::with_capacity)]
164fn vec_with_capacity(capacity: usize) -> alloc::Result<Vec> {
165    Vec::with_capacity(capacity)
166}
167
168/// Returns the number of elements in the vector, also referred to as its
169/// 'length'.
170///
171/// # Examples
172///
173/// ```rune
174/// let a = [1, 2, 3];
175/// assert_eq!(a.len(), 3);
176/// ```
177#[rune::function(instance)]
178fn len(vec: &Vec) -> usize {
179    vec.len()
180}
181
182/// Returns `true` if the vector contains no elements.
183///
184/// # Examples
185///
186/// ```rune
187/// let v = Vec::new();
188/// assert!(v.is_empty());
189///
190/// v.push(1);
191/// assert!(!v.is_empty());
192/// ```
193#[rune::function(instance)]
194fn is_empty(vec: &Vec) -> bool {
195    vec.is_empty()
196}
197
198/// Returns the total number of elements the vector can hold without
199/// reallocating.
200///
201/// # Examples
202///
203/// ```rune
204/// let vec = Vec::with_capacity(10);
205/// vec.push(42);
206/// assert!(vec.capacity() >= 10);
207/// ```
208#[rune::function(instance)]
209fn capacity(vec: &Vec) -> usize {
210    vec.capacity()
211}
212
213/// Returns a reference to an element or subslice depending on the type of
214/// index.
215///
216/// - If given a position, returns a reference to the element at that position
217///   or `None` if out of bounds.
218/// - If given a range, returns the subslice corresponding to that range, or
219///   `None` if out of bounds.
220///
221/// # Examples
222///
223/// ```rune
224/// let v = [1, 4, 3];
225/// assert_eq!(Some(4), v.get(1));
226/// assert_eq!(Some([1, 4]), v.get(0..2));
227/// assert_eq!(Some([1, 4, 3]), v.get(0..=2));
228/// assert_eq!(Some([1, 4, 3]), v.get(0..));
229/// assert_eq!(Some([1, 4, 3]), v.get(..));
230/// assert_eq!(Some([4, 3]), v.get(1..));
231/// assert_eq!(None, v.get(3));
232/// assert_eq!(None, v.get(0..4));
233/// ```
234#[rune::function(instance)]
235fn get(this: &Vec, index: Value) -> Result<Option<Value>, VmError> {
236    Vec::index_get(this, index)
237}
238
239/// Sort a vector by the specified comparator function.
240///
241/// # Examples
242///
243/// ```rune
244/// use std::ops::cmp;
245///
246/// let values = [1, 2, 3];
247/// values.sort_by(|a, b| cmp(b, a))
248/// ```
249#[rune::function(instance)]
250fn sort_by(vec: &mut Vec, comparator: &Function) -> Result<(), VmError> {
251    let mut error = None;
252
253    vec.sort_by(|a, b| match comparator.call::<Ordering>((a, b)) {
254        Ok(ordering) => ordering,
255        Err(e) => {
256            if error.is_none() {
257                error = Some(e);
258            }
259
260            Ordering::Equal
261        }
262    })?;
263
264    if let Some(e) = error {
265        Err(e)
266    } else {
267        Ok(())
268    }
269}
270
271/// Sort the vector.
272///
273/// This require all elements to be of the same type, and implement total
274/// ordering per the [`CMP`] protocol.
275///
276/// # Panics
277///
278/// If any elements present are not comparable, this method will panic.
279///
280/// This will panic because a tuple and a string are not comparable:
281///
282/// ```rune,should_panic
283/// let values = [(3, 1), "hello"];
284/// values.sort();
285/// ```
286///
287/// This too will panic because floating point values which do not have a total
288/// ordering:
289///
290/// ```rune,should_panic
291/// let values = [1.0, 2.0, f64::NAN];
292/// values.sort();
293/// ```
294///
295/// # Examples
296///
297/// ```rune
298/// let values = [3, 2, 1];
299/// values.sort();
300/// assert_eq!(values, [1, 2, 3]);
301///
302/// let values = [(3, 1), (2, 1), (1, 1)];
303/// values.sort();
304/// assert_eq!(values, [(1, 1), (2, 1), (3, 1)]);
305/// ```
306#[rune::function(instance)]
307fn sort(vec: &mut Vec) -> Result<(), VmError> {
308    let mut err = None;
309
310    vec.sort_by(|a, b| {
311        let result: Result<Ordering, VmError> = Value::cmp(a, b);
312
313        match result {
314            Ok(cmp) => cmp,
315            Err(e) => {
316                if err.is_none() {
317                    err = Some(e);
318                }
319
320                // NB: fall back to sorting by address.
321                (a as *const _ as usize).cmp(&(b as *const _ as usize))
322            }
323        }
324    })?;
325
326    if let Some(err) = err {
327        return Err(err);
328    }
329
330    Ok(())
331}
332
333/// Clears the vector, removing all values.
334///
335/// Note that this method has no effect on the allocated capacity of the vector.
336///
337/// # Examples
338///
339/// ```rune
340/// let v = [1, 2, 3];
341///
342/// v.clear();
343///
344/// assert!(v.is_empty());
345/// ```
346#[rune::function(instance)]
347fn clear(vec: &mut Vec) {
348    // A native function has no worklist of its own to take the values apart
349    // over, so it gets one which is empty.
350    vec.dismantle(&mut Worklist::new());
351}
352
353/// Extend these bytes with another collection.
354///
355/// # Examples
356///
357/// ```rune
358/// let vec = [1, 2, 3, 4];
359/// vec.extend([5, 6, 7, 8]);
360/// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7, 8]);
361/// ```
362#[rune::function(instance)]
363fn extend(this: &mut Vec, value: Value) -> Result<(), VmError> {
364    this.extend(value)
365}
366
367/// Removes the last element from a vector and returns it, or [`None`] if it is
368/// empty.
369///
370/// If you'd like to pop the first element, consider using
371/// [`VecDeque::pop_front`] instead.
372///
373/// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
374///
375/// # Examples
376///
377/// ```rune
378/// let vec = [1, 2, 3];
379/// assert_eq!(vec.pop(), Some(3));
380/// assert_eq!(vec, [1, 2]);
381/// ```
382#[rune::function(instance)]
383fn pop(this: &mut Vec) -> Option<Value> {
384    this.pop()
385}
386
387/// Appends an element to the back of a collection.
388///
389/// # Panics
390///
391/// Panics if the new capacity exceeds `isize::MAX` bytes.
392///
393/// # Examples
394///
395/// ```rune
396/// let vec = [1, 2];
397/// vec.push(3);
398/// assert_eq!(vec, [1, 2, 3]);
399/// ```
400#[rune::function(instance)]
401fn push(this: &mut Vec, value: Value) -> Result<(), VmError> {
402    this.push(value)?;
403    Ok(())
404}
405
406/// Removes and returns the element at position `index` within the vector,
407/// shifting all elements after it to the left.
408///
409/// Note: Because this shifts over the remaining elements, it has a worst-case
410/// performance of *O*(*n*). If you don't need the order of elements to be
411/// preserved, use [`swap_remove`] instead. If you'd like to remove elements
412/// from the beginning of the `Vec`, consider using [`VecDeque::pop_front`]
413/// instead.
414///
415/// [`swap_remove`]: Vec::swap_remove
416/// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
417///
418/// # Panics
419///
420/// Panics if `index` is out of bounds.
421///
422/// ```rune,should_panic
423/// let v = [1, 2, 3];
424/// v.remove(3);
425/// ```
426///
427/// # Examples
428///
429/// ```rune
430/// let v = [1, 2, 3];
431/// assert_eq!(v.remove(1), 2);
432/// assert_eq!(v, [1, 3]);
433/// ```
434#[rune::function(instance)]
435fn remove(this: &mut Vec, index: usize) -> Result<Value, VmError> {
436    if index >= this.len() {
437        return Err(VmError::new(VmErrorKind::OutOfRange {
438            index: index.into(),
439            length: this.len().into(),
440        }));
441    }
442
443    let value = this.remove(index);
444    Ok(value)
445}
446
447/// Inserts an element at position `index` within the vector, shifting all
448/// elements after it to the right.
449///
450/// # Panics
451///
452/// Panics if `index > len`.
453///
454/// # Examples
455///
456/// ```rune
457/// let vec = [1, 2, 3];
458/// vec.insert(1, 4);
459/// assert_eq!(vec, [1, 4, 2, 3]);
460/// vec.insert(4, 5);
461/// assert_eq!(vec, [1, 4, 2, 3, 5]);
462/// ```
463#[rune::function(instance)]
464fn insert(this: &mut Vec, index: usize, value: Value) -> Result<(), VmError> {
465    if index > this.len() {
466        return Err(VmError::new(VmErrorKind::OutOfRange {
467            index: index.into(),
468            length: this.len().into(),
469        }));
470    }
471
472    this.insert(index, value)?;
473    Ok(())
474}
475
476/// Clone the vector.
477///
478/// # Examples
479///
480/// ```rune
481/// let a = [1, 2, 3];
482/// let b = a.clone();
483///
484/// b.push(4);
485///
486/// assert_eq!(a, [1, 2, 3]);
487/// assert_eq!(b, [1, 2, 3, 4]);
488/// ```
489#[rune::function(keep, instance, protocol = CLONE)]
490fn clone(this: &Vec) -> alloc::Result<Vec> {
491    this.try_clone()
492}
493
494/// Construct an iterator over the tuple.
495///
496/// # Examples
497///
498/// ```rune
499/// let vec = [1, 2, 3];
500/// let out = [];
501///
502/// for v in vec {
503///     out.push(v);
504/// }
505///
506/// assert_eq!(out, [1, 2, 3]);
507/// ```
508#[rune::function(keep, instance, protocol = INTO_ITER)]
509fn into_iter(this: Ref<Vec>) -> Iter {
510    Vec::rune_iter(this)
511}
512
513/// Returns a reference to an element or subslice depending on the type of
514/// index.
515///
516/// - If given a position, returns a reference to the element at that position
517///   or `None` if out of bounds.
518/// - If given a range, returns the subslice corresponding to that range, or
519///   `None` if out of bounds.
520///
521/// # Panics
522///
523/// Panics if the specified `index` is out of range.
524///
525/// ```rune,should_panic
526/// let v = [10, 40, 30];
527/// assert_eq!(None, v[1..4]);
528/// ```
529///
530/// ```rune,should_panic
531/// let v = [10, 40, 30];
532/// assert_eq!(None, v[3]);
533/// ```
534///
535/// # Examples
536///
537/// ```rune
538/// let v = [10, 40, 30];
539/// assert_eq!(40, v[1]);
540/// assert_eq!([10, 40], v[0..2]);
541/// ```
542#[rune::function(instance, protocol = INDEX_GET)]
543fn index_get(this: &Vec, index: Value) -> Result<Value, VmError> {
544    let Some(value) = Vec::index_get(this, index)? else {
545        return Err(VmError::new(VmErrorKind::MissingIndex {
546            target: Vec::type_info(),
547        }));
548    };
549
550    Ok(value)
551}
552
553/// Inserts a value into the vector.
554///
555/// # Examples
556///
557/// ```rune
558/// let vec = [1, 2, 3];
559/// vec[0] = "a";
560/// assert_eq!(vec, ["a", 2, 3]);
561/// ```
562#[rune::function(instance, protocol = INDEX_SET)]
563fn index_set(this: &mut Vec, index: usize, value: Value) -> Result<(), VmError> {
564    Vec::set(this, index, value)
565}
566
567/// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
568///
569/// If `new_len` is greater than `len`, the `Vec` is extended by the difference,
570/// with each additional slot filled with `value`. If `new_len` is less than
571/// `len`, the `Vec` is simply truncated.
572///
573/// This method requires `T` to implement [`Clone`], in order to be able to
574/// clone the passed value. If you need more flexibility (or want to rely on
575/// [`Default`] instead of [`Clone`]), use [`Vec::resize_with`]. If you only
576/// need to resize to a smaller size, use [`Vec::truncate`].
577///
578/// # Examples
579///
580/// ```rune
581/// let vec = ["hello"];
582/// vec.resize(3, "world");
583/// assert_eq!(vec, ["hello", "world", "world"]);
584///
585/// let vec = [1, 2, 3, 4];
586/// vec.resize(2, 0);
587/// assert_eq!(vec, [1, 2]);
588/// ```
589///
590/// Resizing calls `CLONE` each new element, which means they are not
591/// structurally shared:
592///
593/// ```rune
594/// let inner = [1];
595/// let vec = [2];
596/// vec.resize(3, inner);
597///
598/// inner.push(3);
599/// vec[1].push(4);
600///
601/// assert_eq!(vec, [2, [1, 4], [1]]);
602/// ```
603#[rune::function(instance)]
604fn resize(this: &mut Vec, new_len: usize, value: Value) -> Result<(), VmError> {
605    Vec::resize(this, new_len, value)
606}
607
608/// Write a debug representation to a string.
609///
610/// This calls the [`DEBUG_FMT`] protocol over all elements of the
611/// collection.
612///
613/// # Examples
614///
615/// ```rune
616/// let vec = [1, 2, 3];
617/// assert_eq!(format!("{:?}", vec), "[1, 2, 3]");
618/// ```
619#[rune::function(keep, instance, protocol = DEBUG_FMT)]
620fn debug_fmt(this: &Vec, f: &mut Formatter) -> Result<(), VmError> {
621    Vec::debug_fmt_with(this, f, &mut EnvProtocolCaller)
622}
623
624/// Perform a partial equality check with this vector.
625///
626/// This can take any argument which can be converted into an iterator using
627/// [`INTO_ITER`].
628///
629/// # Examples
630///
631/// ```rune
632/// let vec = [1, 2, 3];
633///
634/// assert!(vec == [1, 2, 3]);
635/// assert!(vec == (1..=3));
636/// assert!(vec != [2, 3, 4]);
637/// ```
638#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
639fn partial_eq(this: &Vec, other: Value) -> Result<bool, VmError> {
640    Vec::partial_eq_with(this, other, &mut EnvProtocolCaller)
641}
642
643/// Perform a total equality check with this vector.
644///
645/// # Examples
646///
647/// ```rune
648/// use std::ops::eq;
649///
650/// let vec = [1, 2, 3];
651///
652/// assert!(eq(vec, [1, 2, 3]));
653/// assert!(!eq(vec, [2, 3, 4]));
654/// ```
655#[rune::function(keep, instance, protocol = EQ)]
656fn eq(this: &Vec, other: &Vec) -> Result<bool, VmError> {
657    Vec::eq_with(this, other, Value::eq_with, &mut EnvProtocolCaller)
658}
659
660/// Perform a partial comparison check with this vector.
661///
662/// # Examples
663///
664/// ```rune
665/// let vec = [1, 2, 3];
666///
667/// assert!(vec > [0, 2, 3]);
668/// assert!(vec < [2, 2, 3]);
669/// ```
670#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
671fn partial_cmp(this: &Vec, other: &Vec) -> Result<Option<Ordering>, VmError> {
672    Vec::partial_cmp_with(this, other, &mut EnvProtocolCaller)
673}
674
675/// Perform a total comparison check with this vector.
676///
677/// # Examples
678///
679/// ```rune
680/// use std::cmp::Ordering;
681/// use std::ops::cmp;
682///
683/// let vec = [1, 2, 3];
684///
685/// assert_eq!(cmp(vec, [0, 2, 3]), Ordering::Greater);
686/// assert_eq!(cmp(vec, [2, 2, 3]), Ordering::Less);
687/// ```
688#[rune::function(keep, instance, protocol = CMP)]
689fn cmp(this: &Vec, other: &Vec) -> Result<Ordering, VmError> {
690    Vec::cmp_with(this, other, &mut EnvProtocolCaller)
691}
692
693/// Calculate the hash of a vector.
694///
695/// # Examples
696///
697/// ```rune
698/// use std::ops::hash;
699///
700/// assert_eq!(hash([0, 2, 3]), hash([0, 2, 3]));
701/// ```
702#[rune::function(instance, protocol = HASH)]
703fn hash(this: &Vec, hasher: &mut Hasher) -> Result<(), VmError> {
704    Vec::hash_with(this, hasher, &mut EnvProtocolCaller)
705}