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
use crate::{
    FromValue, InstallWith, Iterator, Mut, Named, Panic, RawMut, RawRef, RawStr, Ref, ToValue,
    UnsafeFromValue, Value, Vm, VmError, VmErrorKind,
};
use std::fmt;
use std::ops;

/// Struct representing a dynamic anonymous object.
///
/// # Examples
///
/// ```rust
/// use runestick::{Range, RangeLimits, ToValue as _};
///
/// # fn main() -> runestick::Result<()> {
/// let from = 42i64.to_value()?;
/// let _ = Range::new(Some(from), None, RangeLimits::HalfOpen);
/// # Ok(()) }
/// ```
#[derive(Clone)]
pub struct Range {
    /// The start value of the range.
    pub start: Option<Value>,
    /// The to value of the range.
    pub end: Option<Value>,
    /// The limits of the range.
    pub limits: RangeLimits,
}

impl Range {
    /// Construct a new range.
    pub fn new(start: Option<Value>, end: Option<Value>, limits: RangeLimits) -> Self {
        Self { start, end, limits }
    }

    /// Coerce range into an iterator.
    pub fn into_iterator(self) -> Result<Iterator, Panic> {
        match (self.limits, self.start, self.end) {
            (RangeLimits::HalfOpen, Some(Value::Integer(start)), Some(Value::Integer(end))) => {
                return Ok(Iterator::from_double_ended("std::ops::Range", start..end));
            }
            (RangeLimits::Closed, Some(Value::Integer(start)), Some(Value::Integer(end))) => {
                return Ok(Iterator::from_double_ended(
                    "std::ops::RangeToInclusive",
                    start..=end,
                ));
            }
            (_, Some(Value::Integer(start)), None) => {
                return Ok(Iterator::from("std::ops::RangeFrom", start..));
            }
            _ => (),
        }

        Err(Panic::custom("not an iterator"))
    }

    /// Value pointer equals implementation for a range.
    pub(crate) fn value_ptr_eq(vm: &mut Vm, a: &Self, b: &Self) -> Result<bool, VmError> {
        if a.limits != b.limits {
            return Ok(false);
        }

        match (&a.start, &b.start) {
            (None, None) => (),
            (Some(a), Some(b)) if Value::value_ptr_eq(vm, a, b)? => (),
            _ => return Ok(false),
        }

        match (&a.end, &b.end) {
            (None, None) => (),
            (Some(a), Some(b)) if Value::value_ptr_eq(vm, a, b)? => (),
            _ => return Ok(false),
        }

        Ok(true)
    }

    /// Test if the current range contains the given integer.
    pub(crate) fn contains_int(&self, n: i64) -> Result<bool, VmError> {
        let start: Option<i64> = match self.start.clone() {
            Some(value) => Some(FromValue::from_value(value)?),
            None => None,
        };

        let end: Option<i64> = match self.end.clone() {
            Some(value) => Some(FromValue::from_value(value)?),
            None => None,
        };

        let out = match self.limits {
            RangeLimits::HalfOpen => match (start, end) {
                (Some(start), Some(end)) => (start..end).contains(&n),
                (Some(start), None) => (start..).contains(&n),
                (None, Some(end)) => (..end).contains(&n),
                (None, None) => true,
            },
            RangeLimits::Closed => match (start, end) {
                (Some(start), Some(end)) => (start..=end).contains(&n),
                (None, Some(end)) => (..=end).contains(&n),
                _ => return Err(VmError::from(VmErrorKind::UnsupportedRange)),
            },
        };

        Ok(out)
    }
}

impl fmt::Debug for Range {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(start) = &self.start {
            write!(f, "{:?}", start)?;
        }

        match self.limits {
            RangeLimits::HalfOpen => write!(f, "..")?,
            RangeLimits::Closed => write!(f, "..=")?,
        }

        if let Some(end) = &self.end {
            write!(f, "{:?}", end)?;
        }

        Ok(())
    }
}

/// The limits of a range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RangeLimits {
    /// A half-open range `..`.
    HalfOpen,
    /// A closed range `..=`.
    Closed,
}

/// Coercing `start..end` into a [Range].
impl<Idx> ToValue for ops::Range<Idx>
where
    Idx: ToValue,
{
    fn to_value(self) -> Result<Value, VmError> {
        let start = self.start.to_value()?;
        let end = self.end.to_value()?;
        let range = Range::new(Some(start), Some(end), RangeLimits::HalfOpen);
        Ok(Value::from(range))
    }
}

/// Coercing `start..` into a [Range].
impl<Idx> ToValue for ops::RangeFrom<Idx>
where
    Idx: ToValue,
{
    fn to_value(self) -> Result<Value, VmError> {
        let start = self.start.to_value()?;
        let range = Range::new(Some(start), None, RangeLimits::HalfOpen);
        Ok(Value::from(range))
    }
}

/// Coercing `..` into a [Range].
impl ToValue for ops::RangeFull {
    fn to_value(self) -> Result<Value, VmError> {
        let range = Range::new(None, None, RangeLimits::HalfOpen);
        Ok(Value::from(range))
    }
}

/// Coercing `start..=end` into a [Range].
impl<Idx> ToValue for ops::RangeInclusive<Idx>
where
    Idx: ToValue,
{
    fn to_value(self) -> Result<Value, VmError> {
        let (start, end) = self.into_inner();
        let start = start.to_value()?;
        let end = end.to_value()?;
        let range = Range::new(Some(start), Some(end), RangeLimits::Closed);
        Ok(Value::from(range))
    }
}

/// Coercing `..end` into a [Range].
impl<Idx> ToValue for ops::RangeTo<Idx>
where
    Idx: ToValue,
{
    fn to_value(self) -> Result<Value, VmError> {
        let end = self.end.to_value()?;
        let range = Range::new(None, Some(end), RangeLimits::HalfOpen);
        Ok(Value::from(range))
    }
}

/// Coercing `..=end` into a [Range].
impl<Idx> ToValue for ops::RangeToInclusive<Idx>
where
    Idx: ToValue,
{
    fn to_value(self) -> Result<Value, VmError> {
        let end = self.end.to_value()?;
        let range = Range::new(None, Some(end), RangeLimits::Closed);
        Ok(Value::from(range))
    }
}

impl FromValue for Range {
    fn from_value(value: Value) -> Result<Self, VmError> {
        Ok(value.into_range()?.take()?)
    }
}

impl FromValue for Mut<Range> {
    fn from_value(value: Value) -> Result<Self, VmError> {
        let object = value.into_range()?;
        let object = object.into_mut()?;
        Ok(object)
    }
}

impl FromValue for Ref<Range> {
    fn from_value(value: Value) -> Result<Self, VmError> {
        let object = value.into_range()?;
        let object = object.into_ref()?;
        Ok(object)
    }
}

impl UnsafeFromValue for &Range {
    type Output = *const Range;
    type Guard = RawRef;

    fn from_value(value: Value) -> Result<(Self::Output, Self::Guard), VmError> {
        let object = value.into_range()?;
        let object = object.into_ref()?;
        Ok(Ref::into_raw(object))
    }

    unsafe fn unsafe_coerce(output: Self::Output) -> Self {
        &*output
    }
}

impl UnsafeFromValue for &mut Range {
    type Output = *mut Range;
    type Guard = RawMut;

    fn from_value(value: Value) -> Result<(Self::Output, Self::Guard), VmError> {
        let object = value.into_range()?;
        let object = object.into_mut()?;
        Ok(Mut::into_raw(object))
    }

    unsafe fn unsafe_coerce(output: Self::Output) -> Self {
        &mut *output
    }
}

impl Named for Range {
    const BASE_NAME: RawStr = RawStr::from_str("Range");
}

impl InstallWith for Range {
    fn install_with(module: &mut crate::Module) -> Result<(), crate::ContextError> {
        module.field_fn(crate::Protocol::GET, "start", |r: &Range| r.start.clone())?;
        module.field_fn(crate::Protocol::GET, "end", |r: &Range| r.end.clone())?;
        module.inst_fn(crate::Protocol::INTO_ITER, Range::into_iterator)?;
        module.inst_fn("iter", Range::into_iterator)?;
        Ok(())
    }
}