rune/modules/
tuple.rs

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
//! The [`Tuple`] fixed collection.

use core::cmp::Ordering;

use crate as rune;
use crate::runtime::slice::Iter;
use crate::runtime::{
    EnvProtocolCaller, Formatter, Hasher, OwnedTuple, Ref, Tuple, Value, Vec, VmResult,
};
use crate::{docstring, ContextError, Module};

/// The [`Tuple`] fixed collection.
///
/// Tuples are anonymous types that can hold a fixed number of elements.
///
/// Tuples in Rune are declared with the special `(a)` syntax, but can also be
/// interacted with through the fundamental [`Tuple`] type.
///
/// Once a tuple has been declared, its size cannot change.
///
/// The tuple type has support for native pattern matching:
///
/// ```rune
/// let value = (1, 2);
///
/// if let (a, b) = value {
///     assert_eq!(a, 1);
///     assert_eq!(b, 2);
/// }
/// ```
///
/// # Examples
///
/// ```rune
/// let empty = ();
/// let one = (10,);
/// let two = (10, 20);
///
/// assert!(empty.is_empty());
/// assert_eq!(one.0, 10);
/// assert_eq!(two.0, 10);
/// assert_eq!(two.1, 20);
/// ```
#[rune::module(::std::tuple)]
pub fn module() -> Result<Module, ContextError> {
    let mut m = Module::from_meta(self::module_meta)?;
    m.ty::<OwnedTuple>()?.docs(docstring! {
        /// The tuple type.
    })?;
    m.function_meta(len)?;
    m.function_meta(is_empty)?;
    m.function_meta(get)?;
    m.function_meta(iter)?;
    m.function_meta(into_iter)?;

    m.function_meta(partial_eq__meta)?;
    m.implement_trait::<OwnedTuple>(rune::item!(::std::cmp::PartialEq))?;

    m.function_meta(eq__meta)?;
    m.implement_trait::<OwnedTuple>(rune::item!(::std::cmp::Eq))?;

    m.function_meta(partial_cmp__meta)?;
    m.implement_trait::<OwnedTuple>(rune::item!(::std::cmp::PartialOrd))?;

    m.function_meta(cmp__meta)?;
    m.implement_trait::<OwnedTuple>(rune::item!(::std::cmp::Ord))?;

    m.function_meta(clone__meta)?;
    m.implement_trait::<OwnedTuple>(rune::item!(::std::clone::Clone))?;

    m.function_meta(hash__meta)?;
    m.function_meta(debug_fmt__meta)?;
    Ok(m)
}

/// Returns the number of elements in the tuple.
///
/// # Examples
///
/// ```rune
/// let a = (1, 2, 3);
/// assert_eq!(a.len(), 3);
/// ```
#[rune::function(instance)]
fn len(this: &Tuple) -> usize {
    this.len()
}

/// Returns `true` if the tuple has a length of 0.
///
/// # Examples
///
/// ```rune
/// let a = (1, 2, 3);
/// assert!(!a.is_empty());
///
/// let a = ();
/// assert!(a.is_empty());
/// ```
#[rune::function(instance)]
fn is_empty(this: &Tuple) -> bool {
    this.is_empty()
}

/// Returns a reference to an element or subslice depending on the type of
/// index.
///
/// - If given a position, returns a reference to the element at that position
///   or `None` if out of bounds.
/// - If given a range, returns the subslice corresponding to that range, or
///   `None` if out of bounds.
///
/// # Examples
///
/// ```rune
/// let v = (10, 40, 30);
/// assert_eq!(Some(40), v.get(1));
/// assert_eq!(Some([10, 40]), v.get(0..2));
/// assert_eq!(None, v.get(3));
/// assert_eq!(None, v.get(0..4));
/// ```
#[rune::function(instance)]
fn get(this: &Tuple, index: Value) -> VmResult<Option<Value>> {
    Vec::index_get(this, index)
}

/// Construct an iterator over the tuple.
///
/// # Examples
///
/// ```rune
/// let tuple = (1, 2, 3);
/// assert_eq!(tuple.iter().collect::<Vec>(), [1, 2, 3]);
/// ```
#[rune::function(instance)]
fn iter(this: Ref<Tuple>) -> Iter {
    Iter::new(Ref::map(this, |tuple| &**tuple))
}

/// Construct an iterator over the tuple.
///
/// # Examples
///
/// ```rune
/// let tuple = (1, 2, 3);
/// let out = [];
///
/// for v in tuple {
///     out.push(v);
/// }
///
/// assert_eq!(out, [1, 2, 3]);
/// ```
#[rune::function(instance, instance, protocol = INTO_ITER)]
fn into_iter(this: Ref<Tuple>) -> Iter {
    Iter::new(Ref::map(this, |tuple| &**tuple))
}

/// Perform a partial equality check with this tuple.
///
/// This can take any argument which can be converted into an iterator using
/// [`INTO_ITER`].
///
/// # Examples
///
/// ```rune
/// let tuple = (1, 2, 3);
///
/// assert!(tuple == (1, 2, 3));
/// assert!(tuple == (1..=3));
/// assert!(tuple != (2, 3, 4));
/// ```
#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
fn partial_eq(this: &Tuple, other: Value) -> VmResult<bool> {
    Vec::partial_eq_with(this, other, &mut EnvProtocolCaller)
}

/// Perform a total equality check with this tuple.
///
/// # Examples
///
/// ```rune
/// use std::ops::eq;
///
/// let tuple = (1, 2, 3);
///
/// assert!(eq(tuple, (1, 2, 3)));
/// assert!(!eq(tuple, (2, 3, 4)));
/// ```
#[rune::function(keep, instance, protocol = EQ)]
fn eq(this: &Tuple, other: &Tuple) -> VmResult<bool> {
    Vec::eq_with(this, other, Value::eq_with, &mut EnvProtocolCaller)
}

/// Perform a partial comparison check with this tuple.
///
/// # Examples
///
/// ```rune
/// let tuple = (1, 2, 3);
///
/// assert!(tuple > (0, 2, 3));
/// assert!(tuple < (2, 2, 3));
/// ```
#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
fn partial_cmp(this: &Tuple, other: &Tuple) -> VmResult<Option<Ordering>> {
    Vec::partial_cmp_with(this, other, &mut EnvProtocolCaller)
}

/// Perform a total comparison check with this tuple.
///
/// # Examples
///
/// ```rune
/// use std::cmp::Ordering;
/// use std::ops::cmp;
///
/// let tuple = (1, 2, 3);
///
/// assert_eq!(cmp(tuple, (0, 2, 3)), Ordering::Greater);
/// assert_eq!(cmp(tuple, (2, 2, 3)), Ordering::Less);
/// ```
#[rune::function(keep, instance, protocol = CMP)]
fn cmp(this: &Tuple, other: &Tuple) -> VmResult<Ordering> {
    Vec::cmp_with(this, other, &mut EnvProtocolCaller)
}

/// Calculate a hash for a tuple.
///
/// # Examples
///
/// ```rune
/// use std::ops::hash;
///
/// assert_eq!(hash((0, 2, 3)), hash((0, 2, 3)));
/// // Note: this is not guaranteed to be true forever, but it's true right now.
/// assert_eq!(hash((0, 2, 3)), hash([0, 2, 3]));
/// ```
#[rune::function(keep, instance, protocol = HASH)]
fn hash(this: &Tuple, hasher: &mut Hasher) -> VmResult<()> {
    Tuple::hash_with(this, hasher, &mut EnvProtocolCaller)
}

/// Clone a tuple.
///
/// # Examples
///
/// ```rune
/// use std::ops::hash;
///
/// let a = (0, 2, 3);
/// let b = a;
/// let c = a.clone();
///
/// c.0 = 1;
///
/// assert_eq!(a, (0, 2, 3));
/// assert_eq!(c, (1, 2, 3));
/// ```
#[rune::function(keep, instance, protocol = CLONE)]
fn clone(this: &Tuple) -> VmResult<OwnedTuple> {
    VmResult::Ok(vm_try!(this.clone_with(&mut EnvProtocolCaller)))
}

/// Write a debug representation of a tuple.
///
/// # Examples
///
/// ```rune
/// let a = (1, 2, 3);
/// println!("{a:?}");
/// ```
#[rune::function(keep, instance, protocol = DEBUG_FMT)]
#[inline]
fn debug_fmt(this: &Tuple, f: &mut Formatter) -> VmResult<()> {
    this.debug_fmt_with(f, &mut EnvProtocolCaller)
}