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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Type to hold a mutable reference to the target of an evaluation.

use crate::{Dynamic, Position, RhaiResultOf};
use std::borrow::{Borrow, BorrowMut};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;

/// Calculate an offset+len pair given an actual length of the underlying array.
///
/// Negative starting positions count from the end.
///
/// Values going over bounds are limited to the actual length.
#[cfg(not(feature = "no_index"))]
#[inline]
#[allow(
    clippy::cast_sign_loss,
    clippy::absurd_extreme_comparisons,
    clippy::cast_possible_truncation
)]
pub fn calc_offset_len(length: usize, start: crate::INT, len: crate::INT) -> (usize, usize) {
    let start = if start < 0 {
        let abs_start = start.unsigned_abs();

        #[allow(clippy::unnecessary_cast)]
        if abs_start as u64 > crate::MAX_USIZE_INT as u64 {
            0
        } else {
            length - usize::min(abs_start as usize, length)
        }
    } else if start > crate::MAX_USIZE_INT || start as usize >= length {
        return (length, 0);
    } else {
        start as usize
    };

    let len = if len <= 0 {
        0
    } else if len > crate::MAX_USIZE_INT || len as usize > length - start {
        length - start
    } else {
        len as usize
    };

    (start, len)
}

/// Calculate an offset+len pair given an actual length of the underlying array.
///
/// Negative starting positions count from the end.
///
/// Values going over bounds call the provided closure to return a default value or an error.
#[inline]
#[allow(dead_code)]
#[allow(
    clippy::cast_sign_loss,
    clippy::cast_possible_truncation,
    clippy::absurd_extreme_comparisons
)]
pub fn calc_index<E>(
    length: usize,
    index: crate::INT,
    negative_count_from_end: bool,
    err_func: impl FnOnce() -> Result<usize, E>,
) -> Result<usize, E> {
    if length == 0 {
        // Empty array, do nothing
    } else if index < 0 {
        if negative_count_from_end {
            let abs_index = index.unsigned_abs();

            #[allow(clippy::unnecessary_cast)]
            if abs_index as u64 <= crate::MAX_USIZE_INT as u64 && (abs_index as usize) <= length {
                return Ok(length - (abs_index as usize));
            }
        }
    } else if index <= crate::MAX_USIZE_INT && (index as usize) < length {
        return Ok(index as usize);
    }

    err_func()
}

/// _(internals)_ A type that encapsulates a mutation target for an expression with side effects.
/// Exported under the `internals` feature only.
///
/// This type is typically used to hold a mutable reference to the target of an indexing or property
/// access operation.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "internals")] {
/// # use rhai::{Dynamic, Target};
/// // Normal `Dynamic` value
/// let mut value = Dynamic::from(42_i64);
/// let target: Target = value.into();
///
/// // Mutable reference to a `Dynamic` value
/// let mut value = Dynamic::from(42_i64);
/// let value_ref = &mut value;
/// let target: Target = value.into();
/// # }
/// ```
#[derive(Debug)]
#[must_use]
pub enum Target<'a> {
    /// The target is a mutable reference to a [`Dynamic`].
    RefMut(&'a mut Dynamic),
    /// The target is a mutable reference to a _shared_ [`Dynamic`].
    #[cfg(not(feature = "no_closure"))]
    SharedValue {
        /// Lock guard to the shared [`Dynamic`].
        guard: crate::types::dynamic::DynamicWriteLock<'a, Dynamic>,
        /// Copy of the shared value.
        shared_value: Dynamic,
    },
    /// The target is a temporary [`Dynamic`] value (i.e. its mutation can cause no side effects).
    TempValue(Dynamic),
    /// The target is a bit inside an [`INT`][crate::INT].
    /// This is necessary because directly pointing to a bit inside an [`INT`][crate::INT] is impossible.
    #[cfg(not(feature = "no_index"))]
    Bit {
        /// Mutable reference to the source [`Dynamic`].
        source: &'a mut Dynamic,
        /// Copy of the boolean bit, as a [`Dynamic`].
        value: Dynamic,
        /// Bit offset.
        bit: u8,
    },
    /// The target is a range of bits inside an [`INT`][crate::INT].
    /// This is necessary because directly pointing to a range of bits inside an [`INT`][crate::INT] is impossible.
    #[cfg(not(feature = "no_index"))]
    BitField {
        /// Mutable reference to the source [`Dynamic`].
        source: &'a mut Dynamic,
        /// Copy of the integer value of the bits, as a [`Dynamic`].
        value: Dynamic,
        /// Bitmask to apply to the source value (i.e. shifted)
        mask: crate::INT,
        /// Number of bits to right-shift the source value.
        shift: u8,
    },
    /// The target is a byte inside a [`Blob`][crate::Blob].
    /// This is necessary because directly pointing to a [byte][u8] inside a BLOB is impossible.
    #[cfg(not(feature = "no_index"))]
    BlobByte {
        /// Mutable reference to the source [`Dynamic`].
        source: &'a mut Dynamic,
        /// Copy of the byte at the index, as a [`Dynamic`].
        value: Dynamic,
        /// Offset index.
        index: usize,
    },
    /// The target is a character inside a string.
    /// This is necessary because directly pointing to a [`char`] inside a [`String`] is impossible.
    #[cfg(not(feature = "no_index"))]
    StringChar {
        /// Mutable reference to the source [`Dynamic`].
        source: &'a mut Dynamic,
        /// Copy of the character at the offset, as a [`Dynamic`].
        value: Dynamic,
        /// Offset index.
        index: usize,
    },
    /// The target is a slice of a string.
    /// This is necessary because directly pointing to a [`char`] inside a [`String`] is impossible.
    #[cfg(not(feature = "no_index"))]
    StringSlice {
        /// Mutable reference to the source [`Dynamic`].
        source: &'a mut Dynamic,
        /// Copy of the character at the offset, as a [`Dynamic`].
        value: Dynamic,
        /// Offset index.
        start: usize,
        /// End index.
        end: usize,
        /// Is exclusive?
        exclusive: bool,
    },
}

impl<'a> Target<'a> {
    /// Is the [`Target`] a reference pointing to other data?
    #[allow(dead_code)]
    #[inline]
    #[must_use]
    pub const fn is_ref(&self) -> bool {
        match self {
            Self::RefMut(..) => true,
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { .. } => true,
            Self::TempValue(..) => false,
            #[cfg(not(feature = "no_index"))]
            Self::Bit { .. }
            | Self::BitField { .. }
            | Self::BlobByte { .. }
            | Self::StringChar { .. }
            | Self::StringSlice { .. } => false,
        }
    }
    /// Is the [`Target`] a temp value?
    #[inline]
    #[must_use]
    pub const fn is_temp_value(&self) -> bool {
        match self {
            Self::RefMut(..) => false,
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { .. } => false,
            Self::TempValue(..) => true,
            #[cfg(not(feature = "no_index"))]
            Self::Bit { .. }
            | Self::BitField { .. }
            | Self::BlobByte { .. }
            | Self::StringChar { .. }
            | Self::StringSlice { .. } => false,
        }
    }
    /// Is the [`Target`] a shared value?
    #[inline]
    #[must_use]
    pub fn is_shared(&self) -> bool {
        #[cfg(not(feature = "no_closure"))]
        return match self {
            Self::RefMut(r) => r.is_shared(),
            Self::SharedValue { .. } => true,
            Self::TempValue(value) => value.is_shared(),
            #[cfg(not(feature = "no_index"))]
            Self::Bit { .. }
            | Self::BitField { .. }
            | Self::BlobByte { .. }
            | Self::StringChar { .. }
            | Self::StringSlice { .. } => false,
        };
        #[cfg(feature = "no_closure")]
        return false;
    }
    /// Get the value of the [`Target`] as a [`Dynamic`], cloning a referenced value if necessary.
    #[inline]
    pub fn take_or_clone(self) -> Dynamic {
        match self {
            Self::RefMut(r) => r.clone(), // Referenced value is cloned
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { shared_value, .. } => shared_value, // Original shared value is simply taken
            Self::TempValue(value) => value, // Owned value is simply taken
            #[cfg(not(feature = "no_index"))]
            Self::Bit { value, .. }
            | Self::BitField { value, .. }
            | Self::BlobByte { value, .. }
            | Self::StringChar { value, .. }
            | Self::StringSlice { value, .. } => value, // Intermediate value is simply taken
        }
    }
    /// Take a `&mut Dynamic` reference from the `Target`.
    #[inline(always)]
    #[must_use]
    pub fn take_ref(self) -> Option<&'a mut Dynamic> {
        match self {
            Self::RefMut(r) => Some(r),
            _ => None,
        }
    }
    /// Convert a shared or reference [`Target`] into a target with an owned value.
    #[inline(always)]
    pub fn into_owned(self) -> Self {
        match self {
            Self::RefMut(r) => Self::TempValue(r.clone()),
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { shared_value, .. } => Self::TempValue(shared_value),
            _ => self,
        }
    }
    /// Get the source [`Dynamic`] of the [`Target`].
    #[allow(dead_code)]
    #[inline]
    pub fn source(&self) -> &Dynamic {
        match self {
            Self::RefMut(r) => r,
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { guard, .. } => guard,
            Self::TempValue(value) => value,
            #[cfg(not(feature = "no_index"))]
            Self::Bit { source, .. }
            | Self::BitField { source, .. }
            | Self::BlobByte { source, .. }
            | Self::StringChar { source, .. }
            | Self::StringSlice { source, .. } => source,
        }
    }
    /// Propagate a changed value back to the original source.
    /// This has no effect for direct references.
    #[inline]
    pub fn propagate_changed_value(&mut self, _pos: Position) -> RhaiResultOf<()> {
        match self {
            Self::RefMut(..) | Self::TempValue(..) => (),
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { .. } => (),
            #[cfg(not(feature = "no_index"))]
            Self::Bit { source, value, bit } => {
                // Replace the bit at the specified index position
                let new_bit = value.as_bool().map_err(|err| {
                    Box::new(crate::ERR::ErrorMismatchDataType(
                        "bool".to_string(),
                        err.to_string(),
                        _pos,
                    ))
                })?;

                let value = &mut *source.write_lock::<crate::INT>().unwrap();

                let index = *bit;

                let mask = 1 << index;
                if new_bit {
                    *value |= mask;
                } else {
                    *value &= !mask;
                }
            }
            #[cfg(not(feature = "no_index"))]
            Self::BitField {
                source,
                value,
                mask,
                shift,
            } => {
                let shift = *shift;
                let mask = *mask;

                // Replace the bit at the specified index position
                let new_value = value.as_int().map_err(|err| {
                    Box::new(crate::ERR::ErrorMismatchDataType(
                        "integer".to_string(),
                        err.to_string(),
                        _pos,
                    ))
                })?;

                let new_value = (new_value << shift) & mask;
                let value = &mut *source.write_lock::<crate::INT>().unwrap();

                *value &= !mask;
                *value |= new_value;
            }
            #[cfg(not(feature = "no_index"))]
            Self::BlobByte {
                source,
                value,
                index,
            } => {
                // Replace the byte at the specified index position
                let new_byte = value.as_int().map_err(|err| {
                    Box::new(crate::ERR::ErrorMismatchDataType(
                        "INT".to_string(),
                        err.to_string(),
                        _pos,
                    ))
                })?;

                let value = &mut *source.write_lock::<crate::Blob>().unwrap();

                #[allow(clippy::cast_sign_loss)]
                {
                    value[*index] = (new_byte & 0x00ff) as u8;
                }
            }
            #[cfg(not(feature = "no_index"))]
            Self::StringChar {
                source,
                value,
                index,
            } => {
                // Replace the character at the specified index position
                let new_ch = value.as_char().map_err(|err| {
                    Box::new(crate::ERR::ErrorMismatchDataType(
                        "char".to_string(),
                        err.to_string(),
                        _pos,
                    ))
                })?;

                let s = &mut *source.write_lock::<crate::ImmutableString>().unwrap();

                *s = s
                    .chars()
                    .enumerate()
                    .map(|(i, ch)| if i == *index { new_ch } else { ch })
                    .collect();
            }
            #[cfg(not(feature = "no_index"))]
            Self::StringSlice {
                source,
                ref start,
                ref end,
                ref value,
                exclusive,
            } => {
                let s = &mut *source.write_lock::<crate::ImmutableString>().unwrap();

                let n = s.chars().count();
                let vs = s.chars().take(*start);
                let ve = if *exclusive {
                    let end = if *end > n { n } else { *end };
                    s.chars().skip(end)
                } else {
                    let end = if *end >= n { n - 1 } else { *end };
                    s.chars().skip(end + 1)
                };
                *s = vs.chain(value.to_string().chars()).chain(ve).collect();
            }
        }

        Ok(())
    }
}

impl<'a> From<&'a mut Dynamic> for Target<'a> {
    #[inline]
    fn from(value: &'a mut Dynamic) -> Self {
        #[cfg(not(feature = "no_closure"))]
        if value.is_shared() {
            // Cloning is cheap for a shared value
            let shared_value = value.clone();
            let guard = value.write_lock::<Dynamic>().unwrap();
            return Self::SharedValue {
                guard,
                shared_value,
            };
        }

        Self::RefMut(value)
    }
}

impl AsRef<Dynamic> for Target<'_> {
    #[inline]
    fn as_ref(&self) -> &Dynamic {
        match self {
            Self::RefMut(r) => r,
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { guard, .. } => guard,
            Self::TempValue(ref value) => value,
            #[cfg(not(feature = "no_index"))]
            Self::StringSlice { ref value, .. } => value,
            #[cfg(not(feature = "no_index"))]
            Self::Bit { ref value, .. }
            | Self::BitField { ref value, .. }
            | Self::BlobByte { ref value, .. }
            | Self::StringChar { ref value, .. } => value,
        }
    }
}

impl Borrow<Dynamic> for Target<'_> {
    #[inline(always)]
    fn borrow(&self) -> &Dynamic {
        self.as_ref()
    }
}

impl AsMut<Dynamic> for Target<'_> {
    #[inline]
    fn as_mut(&mut self) -> &mut Dynamic {
        match self {
            Self::RefMut(r) => r,
            #[cfg(not(feature = "no_closure"))]
            Self::SharedValue { guard, .. } => &mut *guard,
            Self::TempValue(ref mut value) => value,
            #[cfg(not(feature = "no_index"))]
            Self::StringSlice { ref mut value, .. } => value,
            #[cfg(not(feature = "no_index"))]
            Self::Bit { ref mut value, .. }
            | Self::BitField { ref mut value, .. }
            | Self::BlobByte { ref mut value, .. }
            | Self::StringChar { ref mut value, .. } => value,
        }
    }
}

impl BorrowMut<Dynamic> for Target<'_> {
    #[inline(always)]
    fn borrow_mut(&mut self) -> &mut Dynamic {
        self.as_mut()
    }
}

impl<T: Into<Dynamic>> From<T> for Target<'_> {
    #[inline(always)]
    fn from(value: T) -> Self {
        Self::TempValue(value.into())
    }
}