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