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`]: std::collections::vec_deque::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/// [`VecDeque::pop_front`]: std::collections::vec_deque::VecDeque::pop_front
416///
417/// # Panics
418///
419/// Panics if `index` is out of bounds.
420///
421/// ```rune,should_panic
422/// let v = [1, 2, 3];
423/// v.remove(3);
424/// ```
425///
426/// # Examples
427///
428/// ```rune
429/// let v = [1, 2, 3];
430/// assert_eq!(v.remove(1), 2);
431/// assert_eq!(v, [1, 3]);
432/// ```
433#[rune::function(instance)]
434fn remove(this: &mut Vec, index: usize) -> Result<Value, VmError> {
435    if index >= this.len() {
436        return Err(VmError::new(VmErrorKind::OutOfRange {
437            index: index.into(),
438            length: this.len().into(),
439        }));
440    }
441
442    let value = this.remove(index);
443    Ok(value)
444}
445
446/// Inserts an element at position `index` within the vector, shifting all
447/// elements after it to the right.
448///
449/// # Panics
450///
451/// Panics if `index > len`.
452///
453/// # Examples
454///
455/// ```rune
456/// let vec = [1, 2, 3];
457/// vec.insert(1, 4);
458/// assert_eq!(vec, [1, 4, 2, 3]);
459/// vec.insert(4, 5);
460/// assert_eq!(vec, [1, 4, 2, 3, 5]);
461/// ```
462#[rune::function(instance)]
463fn insert(this: &mut Vec, index: usize, value: Value) -> Result<(), VmError> {
464    if index > this.len() {
465        return Err(VmError::new(VmErrorKind::OutOfRange {
466            index: index.into(),
467            length: this.len().into(),
468        }));
469    }
470
471    this.insert(index, value)?;
472    Ok(())
473}
474
475/// Clone the vector.
476///
477/// # Examples
478///
479/// ```rune
480/// let a = [1, 2, 3];
481/// let b = a.clone();
482///
483/// b.push(4);
484///
485/// assert_eq!(a, [1, 2, 3]);
486/// assert_eq!(b, [1, 2, 3, 4]);
487/// ```
488#[rune::function(keep, instance, protocol = CLONE)]
489fn clone(this: &Vec) -> alloc::Result<Vec> {
490    this.try_clone()
491}
492
493/// Construct an iterator over the tuple.
494///
495/// # Examples
496///
497/// ```rune
498/// let vec = [1, 2, 3];
499/// let out = [];
500///
501/// for v in vec {
502///     out.push(v);
503/// }
504///
505/// assert_eq!(out, [1, 2, 3]);
506/// ```
507#[rune::function(keep, instance, protocol = INTO_ITER)]
508fn into_iter(this: Ref<Vec>) -> Iter {
509    Vec::rune_iter(this)
510}
511
512/// Returns a reference to an element or subslice depending on the type of
513/// index.
514///
515/// - If given a position, returns a reference to the element at that position
516///   or [`None`] if out of bounds.
517/// - If given a range, returns the subslice corresponding to that range, or
518///   [`None`] if out of bounds.
519///
520/// # Panics
521///
522/// Panics if the specified `index` is out of range.
523///
524/// ```rune,should_panic
525/// let v = [10, 40, 30];
526/// assert_eq!(None, v[1..4]);
527/// ```
528///
529/// ```rune,should_panic
530/// let v = [10, 40, 30];
531/// assert_eq!(None, v[3]);
532/// ```
533///
534/// # Examples
535///
536/// ```rune
537/// let v = [10, 40, 30];
538/// assert_eq!(40, v[1]);
539/// assert_eq!([10, 40], v[0..2]);
540/// ```
541#[rune::function(instance, protocol = INDEX_GET)]
542fn index_get(this: &Vec, index: Value) -> Result<Value, VmError> {
543    let Some(value) = Vec::index_get(this, index)? else {
544        return Err(VmError::new(VmErrorKind::MissingIndex {
545            target: Vec::type_info(),
546        }));
547    };
548
549    Ok(value)
550}
551
552/// Inserts a value into the vector.
553///
554/// # Examples
555///
556/// ```rune
557/// let vec = [1, 2, 3];
558/// vec[0] = "a";
559/// assert_eq!(vec, ["a", 2, 3]);
560/// ```
561#[rune::function(instance, protocol = INDEX_SET)]
562fn index_set(this: &mut Vec, index: usize, value: Value) -> Result<(), VmError> {
563    Vec::set(this, index, value)
564}
565
566/// Resizes the [`Vec`] in-place so that `len` is equal to `new_len`.
567///
568/// If `new_len` is greater than `len`, the [`Vec`] is extended by the difference,
569/// with each additional slot filled with `value`. If `new_len` is less than
570/// `len`, the [`Vec`] is simply truncated.
571///
572/// This method requires `T` to implement [`Clone`], in order to be able to
573/// clone the passed value. If you need more flexibility (or want to rely on
574/// `Default` instead of [`Clone`]), use `Vec::resize_with`. If you only
575/// need to resize to a smaller size, use `Vec::truncate`.
576///
577/// [`Clone`]: std::clone::Clone
578///
579/// # Examples
580///
581/// ```rune
582/// let vec = ["hello"];
583/// vec.resize(3, "world");
584/// assert_eq!(vec, ["hello", "world", "world"]);
585///
586/// let vec = [1, 2, 3, 4];
587/// vec.resize(2, 0);
588/// assert_eq!(vec, [1, 2]);
589/// ```
590///
591/// Resizing calls `CLONE` each new element, which means they are not
592/// structurally shared:
593///
594/// ```rune
595/// let inner = [1];
596/// let vec = [2];
597/// vec.resize(3, inner);
598///
599/// inner.push(3);
600/// vec[1].push(4);
601///
602/// assert_eq!(vec, [2, [1, 4], [1]]);
603/// ```
604#[rune::function(instance)]
605fn resize(this: &mut Vec, new_len: usize, value: Value) -> Result<(), VmError> {
606    Vec::resize(this, new_len, value)
607}
608
609/// Write a debug representation to a string.
610///
611/// This calls the `DEBUG_FMT` protocol over all elements of the
612/// collection.
613///
614/// # Examples
615///
616/// ```rune
617/// let vec = [1, 2, 3];
618/// assert_eq!(format!("{:?}", vec), "[1, 2, 3]");
619/// ```
620#[rune::function(keep, instance, protocol = DEBUG_FMT)]
621fn debug_fmt(this: &Vec, f: &mut Formatter) -> Result<(), VmError> {
622    Vec::debug_fmt_with(this, f, &mut EnvProtocolCaller)
623}
624
625/// Perform a partial equality check with this vector.
626///
627/// This can take any argument which can be converted into an iterator using
628/// `INTO_ITER`.
629///
630/// # Examples
631///
632/// ```rune
633/// let vec = [1, 2, 3];
634///
635/// assert!(vec == [1, 2, 3]);
636/// assert!(vec == (1..=3));
637/// assert!(vec != [2, 3, 4]);
638/// ```
639#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
640fn partial_eq(this: &Vec, other: Value) -> Result<bool, VmError> {
641    Vec::partial_eq_with(this, other, &mut EnvProtocolCaller)
642}
643
644/// Perform a total equality check with this vector.
645///
646/// # Examples
647///
648/// ```rune
649/// use std::ops::eq;
650///
651/// let vec = [1, 2, 3];
652///
653/// assert!(eq(vec, [1, 2, 3]));
654/// assert!(!eq(vec, [2, 3, 4]));
655/// ```
656#[rune::function(keep, instance, protocol = EQ)]
657fn eq(this: &Vec, other: &Vec) -> Result<bool, VmError> {
658    Vec::eq_with(this, other, Value::eq_with, &mut EnvProtocolCaller)
659}
660
661/// Perform a partial comparison check with this vector.
662///
663/// # Examples
664///
665/// ```rune
666/// let vec = [1, 2, 3];
667///
668/// assert!(vec > [0, 2, 3]);
669/// assert!(vec < [2, 2, 3]);
670/// ```
671#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
672fn partial_cmp(this: &Vec, other: &Vec) -> Result<Option<Ordering>, VmError> {
673    Vec::partial_cmp_with(this, other, &mut EnvProtocolCaller)
674}
675
676/// Perform a total comparison check with this vector.
677///
678/// # Examples
679///
680/// ```rune
681/// use std::cmp::Ordering;
682/// use std::ops::cmp;
683///
684/// let vec = [1, 2, 3];
685///
686/// assert_eq!(cmp(vec, [0, 2, 3]), Ordering::Greater);
687/// assert_eq!(cmp(vec, [2, 2, 3]), Ordering::Less);
688/// ```
689#[rune::function(keep, instance, protocol = CMP)]
690fn cmp(this: &Vec, other: &Vec) -> Result<Ordering, VmError> {
691    Vec::cmp_with(this, other, &mut EnvProtocolCaller)
692}
693
694/// Calculate the hash of a vector.
695///
696/// # Examples
697///
698/// ```rune
699/// use std::ops::hash;
700///
701/// assert_eq!(hash([0, 2, 3]), hash([0, 2, 3]));
702/// ```
703#[rune::function(instance, protocol = HASH)]
704fn hash(this: &Vec, hasher: &mut Hasher) -> Result<(), VmError> {
705    Vec::hash_with(this, hasher, &mut EnvProtocolCaller)
706}