artichoke_backend/extn/core/time/
subsec.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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Parser for Ruby Time subsecond parameters to help generate `Time`.
//!
//! This module implements the logic to parse two optional parameters in the
//! `Time.at` function call. These parameters (if specified) provide the number
//! of subsecond parts to add, and a scale of those subsecond parts (millis, micros,
//! and nanos).

use crate::convert::implicitly_convert_to_int;
use crate::extn::core::symbol::Symbol;
use crate::extn::prelude::*;

const NANOS_IN_SECOND: i64 = 1_000_000_000;

const MILLIS_IN_NANO: i64 = 1_000_000;
const MICROS_IN_NANO: i64 = 1_000;
const NANOS_IN_NANO: i64 = 1;

#[allow(clippy::cast_precision_loss)]
const MIN_FLOAT_SECONDS: f64 = i64::MIN as f64;
#[allow(clippy::cast_precision_loss)]
const MAX_FLOAT_SECONDS: f64 = i64::MAX as f64;
const MIN_FLOAT_NANOS: f64 = 0.0;
#[allow(clippy::cast_precision_loss)]
const MAX_FLOAT_NANOS: f64 = NANOS_IN_SECOND as f64;

enum SubsecMultiplier {
    Millis,
    Micros,
    Nanos,
}

impl SubsecMultiplier {
    #[must_use]
    const fn as_nanos(&self) -> i64 {
        match self {
            Self::Millis => MILLIS_IN_NANO,
            Self::Micros => MICROS_IN_NANO,
            Self::Nanos => NANOS_IN_NANO,
        }
    }
}

impl TryConvertMut<Option<Value>, SubsecMultiplier> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, subsec_type: Option<Value>) -> Result<SubsecMultiplier, Self::Error> {
        let mut subsec_type = match subsec_type {
            Some(t) => t,
            None => return Ok(SubsecMultiplier::Micros),
        };

        let subsec_type_symbol = if let Ruby::Symbol = subsec_type.ruby_type() {
            unsafe { Symbol::unbox_from_value(&mut subsec_type, self)? }.bytes(self)
        } else {
            let mut message = b"unexpected unit: ".to_vec();
            message.extend_from_slice(subsec_type.inspect(self).as_slice());
            return Err(ArgumentError::from(message).into());
        };

        match subsec_type_symbol {
            b"milliseconds" => Ok(SubsecMultiplier::Millis),
            b"usec" => Ok(SubsecMultiplier::Micros),
            b"nsec" => Ok(SubsecMultiplier::Nanos),
            _ => {
                let mut message = b"unexpected unit: ".to_vec();
                message.extend_from_slice(subsec_type_symbol);
                Err(ArgumentError::from(message).into())
            }
        }
    }
}

/// A struct that represents the adjustment needed to a `Time` based on a
/// the parsing of optional Ruby Values. Seconds can require adjustment as a
/// means for handling overflow of values. e.g. `1_001` millis can be requested
/// which should result in 1 seconds, and `1_000_000` nanoseconds.
///
/// Note: Negative nanoseconds are not supported, thus any negative adjustment
/// will generally result in at least -1 second, and the relevant positive
/// amount of nanoseconds. e.g. `-1_000` microseconds should result in -1
/// second, and `999_999_000` nanoseconds.
#[derive(Debug, Copy, Clone)]
pub struct Subsec {
    secs: i64,
    nanos: u32,
}

impl Subsec {
    /// Returns a tuple of (seconds, nanoseconds). Subseconds are provided in
    /// various accuracies, and can overflow. e.g. 1001 milliseconds, is 1
    /// second, and `1_000_000` nanoseconds.
    #[must_use]
    pub fn to_tuple(self) -> (i64, u32) {
        (self.secs, self.nanos)
    }
}

impl TryConvertMut<(Option<Value>, Option<Value>), Subsec> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, params: (Option<Value>, Option<Value>)) -> Result<Subsec, Self::Error> {
        let (subsec, subsec_unit) = params;

        let subsec = match subsec {
            Some(subsec) => subsec,
            None => return Ok(Subsec { secs: 0, nanos: 0 }),
        };

        let multiplier: SubsecMultiplier = self.try_convert_mut(subsec_unit)?;
        let multiplier_nanos = multiplier.as_nanos();
        // `subsec` represents the user provided value in `subsec_unit`
        // resolution. The base used to derive the number of seconds is based
        // on the `subsec_unit`. e.g. `1_001` milliseconds is 1 second, and
        // `1_000_000` nanoseconds.
        let seconds_base = NANOS_IN_SECOND / multiplier_nanos;

        if subsec.ruby_type() == Ruby::Float {
            // FIXME: The below deviates from the MRI implementation of Time
            // MRI uses `to_r` for subsec calculation on floats subsec nanos,
            // and this could result in different values.

            let subsec: f64 = self.try_convert(subsec)?;

            if subsec.is_nan() {
                return Err(FloatDomainError::with_message("NaN").into());
            }
            if subsec.is_infinite() {
                if subsec.is_sign_negative() {
                    return Err(FloatDomainError::with_message("-Infinity").into());
                }
                return Err(FloatDomainError::with_message("Infinity").into());
            }

            // These conversions are luckily not lossy. `seconds_base` and
            // `multiplier_nanos` are guaranteed to be represented without loss
            // in a f64.
            #[allow(clippy::cast_precision_loss)]
            let seconds_base = seconds_base as f64;
            #[allow(clippy::cast_precision_loss)]
            let multiplier_nanos = multiplier_nanos as f64;

            let mut secs = subsec / seconds_base;
            let mut nanos = (subsec % seconds_base) * multiplier_nanos;

            // `is_sign_negative()` is not enough here, since this logic should
            // also be skilled for negative zero.
            if subsec < -0.0 {
                // Nanos always needs to be a positive u32. If subsec is
                // negative, we will always need remove one second.  Nanos can
                // then be adjusted since it will always be the inverse of the
                // total nanos in a second.
                secs -= 1.0;

                #[allow(clippy::cast_precision_loss)]
                if nanos != 0.0 && nanos != -0.0 {
                    nanos += NANOS_IN_SECOND as f64;
                }
            }

            if !(MIN_FLOAT_SECONDS..=MAX_FLOAT_SECONDS).contains(&secs)
                || !(MIN_FLOAT_NANOS..=MAX_FLOAT_NANOS).contains(&nanos)
            {
                return Err(ArgumentError::with_message("subsec outside of bounds").into());
            }

            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            Ok(Subsec {
                secs: secs as i64,
                nanos: nanos as u32,
            })
        } else {
            let subsec: i64 = implicitly_convert_to_int(self, subsec)?;

            // The below calculations should always be safe. The multiplier is
            // guaranteed to not be 0, the remainder should never overflow, and
            // is guaranteed to be less than u32::MAX.
            let mut secs = subsec / seconds_base;
            let mut nanos = (subsec % seconds_base) * multiplier_nanos;

            if subsec.is_negative() {
                // Nanos always needs to be a positive u32. If subsec is
                // negative, we will always need remove one second.  Nanos can
                // then be adjusted since it will always be the inverse of the
                // total nanos in a second.
                secs = secs
                    .checked_sub(1)
                    .ok_or(ArgumentError::with_message("Time too small"))?;

                if nanos.signum() != 0 {
                    nanos += NANOS_IN_SECOND;
                }
            }

            // Cast to u32 is safe since it will always be less than
            // `NANOS_IN_SECOND` due to modulo and negative adjustments.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            Ok(Subsec {
                secs,
                nanos: nanos as u32,
            })
        }
    }
}

#[cfg(test)]
#[allow(clippy::unnecessary_literal_unwrap)]
mod tests {
    use bstr::ByteSlice;

    use super::Subsec;
    use crate::test::prelude::*;

    fn subsec(interp: &mut Artichoke, params: (Option<&[u8]>, Option<&[u8]>)) -> Result<Subsec, Error> {
        let (subsec, subsec_type) = params;
        let subsec = subsec.map(|s| interp.eval(s).unwrap());
        let subsec_type = subsec_type.map(|s| interp.eval(s).unwrap());

        interp.try_convert_mut((subsec, subsec_type))
    }

    #[test]
    fn no_subsec_provided() {
        let mut interp = interpreter();

        let result: Subsec = interp.try_convert_mut((None, None)).unwrap();
        let (secs, nanos) = result.to_tuple();
        assert_eq!(secs, 0);
        assert_eq!(nanos, 0);
    }

    #[test]
    fn no_subsec_provided_but_has_unit() {
        let mut interp = interpreter();
        let unit = interp.eval(b":usec").unwrap();

        let result: Subsec = interp.try_convert_mut((None, Some(unit))).unwrap();
        let (secs, nanos) = result.to_tuple();
        assert_eq!(secs, 0);
        assert_eq!(nanos, 0);
    }

    #[test]
    fn int_no_unit_implies_micros() {
        let mut interp = interpreter();

        let expectations = [
            (b"-1000001".as_slice(), (-2, 999_999_000)),
            (b"-1000000".as_slice(), (-2, 0)),
            (b"-999999".as_slice(), (-1, 1_000)),
            (b"-1".as_slice(), (-1, 999_999_000)),
            (b"0".as_slice(), (0, 0)),
            (b"1".as_slice(), (0, 1_000)),
            (b"999999".as_slice(), (0, 999_999_000)),
            (b"1000000".as_slice(), (1, 0)),
            (b"1000001".as_slice(), (1, 1_000)),
        ];

        let subsec_unit: Option<&[u8]> = None;

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), None), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn int_subsec_millis() {
        let mut interp = interpreter();

        let expectations = [
            (b"-1001".as_slice(), (-2, 999_000_000)),
            (b"-1000".as_slice(), (-2, 0)),
            (b"-999".as_slice(), (-1, 1_000_000)),
            (b"-1".as_slice(), (-1, 999_000_000)),
            (b"0".as_slice(), (0, 0)),
            (b"1".as_slice(), (0, 1_000_000)),
            (b"999".as_slice(), (0, 999_000_000)),
            (b"1000".as_slice(), (1, 0)),
            (b"1001".as_slice(), (1, 1_000_000)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":milliseconds");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), Some({})), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                subsec_unit.unwrap().as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn int_subsec_micros() {
        let mut interp = interpreter();

        //let expectations: [(&[u8], (i64, u32))] = [
        let expectations = [
            (b"-1000001".as_slice(), (-2, 999_999_000)),
            (b"-1000000".as_slice(), (-2, 0)),
            (b"-999999".as_slice(), (-1, 1_000)),
            (b"-1".as_slice(), (-1, 999_999_000)),
            (b"0".as_slice(), (0, 0)),
            (b"1".as_slice(), (0, 1_000)),
            (b"999999".as_slice(), (0, 999_999_000)),
            (b"1000000".as_slice(), (1, 0)),
            (b"1000001".as_slice(), (1, 1_000)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":usec");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), Some({})), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                subsec_unit.unwrap().as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn int_subsec_nanos() {
        let mut interp = interpreter();

        let expectations = [
            (b"-1000000001".as_slice(), (-2, 999_999_999)),
            (b"-1000000000".as_slice(), (-2, 0)),
            (b"-999999999".as_slice(), (-1, 1)),
            (b"-1".as_slice(), (-1, 999_999_999)),
            (b"0".as_slice(), (0, 0)),
            (b"1".as_slice(), (0, 1)),
            (b"999999999".as_slice(), (0, 999_999_999)),
            (b"1000000000".as_slice(), (1, 0)),
            (b"1000000001".as_slice(), (1, 1)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":nsec");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), Some({})), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                subsec_unit.unwrap().as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn float_no_unit_implies_micros() {
        let mut interp = interpreter();

        let expectations = [
            // Numbers in and around 0.
            (b"-1000000.5".as_slice(), (-2, 999_999_500)),
            (b"-1000000.0".as_slice(), (-2, 0)),
            (b"-999999.5".as_slice(), (-1, 500)),
            (b"-999999.0".as_slice(), (-1, 1_000)),
            (b"-1000.5".as_slice(), (-1, 998_999_500)),
            (b"-1.5".as_slice(), (-1, 999_998_500)),
            (b"-1.0".as_slice(), (-1, 999_999_000)),
            (b"-0.0".as_slice(), (0, 0)),
            (b"0.0".as_slice(), (0, 0)),
            (b"1.0".as_slice(), (0, 1_000)),
            (b"1.5".as_slice(), (0, 1_500)),
            (b"1000.5".as_slice(), (0, 1_000_500)),
            (b"999999.0".as_slice(), (0, 999_999_000)),
            (b"999999.5".as_slice(), (0, 999_999_500)),
            (b"1000000.0".as_slice(), (1, 0)),
            (b"1000000.5".as_slice(), (1, 500)),
            (b"1000001.0".as_slice(), (1, 1000)),
            // Nanosecond and below (truncates, does not round).
            (b"0.123".as_slice(), (0, 123)),
            (b"0.001".as_slice(), (0, 1)),
            (b"0.0001".as_slice(), (0, 0)),
            (b"0.0009".as_slice(), (0, 0)),
        ];

        let subsec_unit: Option<&[u8]> = None;

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), None), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn float_subsec_millis() {
        let mut interp = interpreter();

        let expectations = [
            // Numbers in and around 0.
            (b"-1000.5".as_slice(), (-2, 999_500_000)),
            (b"-1000.0".as_slice(), (-2, 0)),
            (b"-999.5".as_slice(), (-1, 500_000)),
            (b"-999.0".as_slice(), (-1, 1_000_000)),
            (b"-1.5".as_slice(), (-1, 998_500_000)),
            (b"-1.0".as_slice(), (-1, 999_000_000)),
            (b"-0.0".as_slice(), (0, 0)),
            (b"0.0".as_slice(), (0, 0)),
            (b"1.0".as_slice(), (0, 1_000_000)),
            (b"1.5".as_slice(), (0, 1_500_000)),
            (b"999.0".as_slice(), (0, 999_000_000)),
            (b"999.5".as_slice(), (0, 999_500_000)),
            (b"1000.0".as_slice(), (1, 0)),
            (b"1000.5".as_slice(), (1, 500_000)),
            (b"1001.0".as_slice(), (1, 1_000_000)),
            // Nanosecond and below (truncates, does not round).
            (b"0.123456".as_slice(), (0, 123_456)),
            (b"0.000001".as_slice(), (0, 1)),
            (b"0.0000001".as_slice(), (0, 0)),
            (b"0.0000009".as_slice(), (0, 0)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":milliseconds");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), None), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn float_subsec_micros() {
        let mut interp = interpreter();

        let expectations = [
            // Numbers in and around 0.
            (b"-1000000.5".as_slice(), (-2, 999_999_500)),
            (b"-1000000.0".as_slice(), (-2, 0)),
            (b"-999999.5".as_slice(), (-1, 500)),
            (b"-999999.0".as_slice(), (-1, 1_000)),
            (b"-1000.5".as_slice(), (-1, 998_999_500)),
            (b"-1.5".as_slice(), (-1, 999_998_500)),
            (b"-1.0".as_slice(), (-1, 999_999_000)),
            (b"-0.0".as_slice(), (0, 0)),
            (b"0.0".as_slice(), (0, 0)),
            (b"1.0".as_slice(), (0, 1_000)),
            (b"1.5".as_slice(), (0, 1_500)),
            (b"1000.5".as_slice(), (0, 1_000_500)),
            (b"999999.0".as_slice(), (0, 999_999_000)),
            (b"999999.5".as_slice(), (0, 999_999_500)),
            (b"1000000.0".as_slice(), (1, 0)),
            (b"1000000.5".as_slice(), (1, 500)),
            (b"1000001.0".as_slice(), (1, 1000)),
            // Nanosecond and below (truncates, does not round).
            (b"0.123".as_slice(), (0, 123)),
            (b"0.001".as_slice(), (0, 1)),
            (b"0.0001".as_slice(), (0, 0)),
            (b"0.0009".as_slice(), (0, 0)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":usec");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), None), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn float_subsec_nanos() {
        let mut interp = interpreter();

        let expectations = [
            // Numbers in and around 0.
            (b"-1000000000.5".as_slice(), (-2, 999_999_999)),
            (b"-1000000000.0".as_slice(), (-2, 0)),
            (b"-999999999.5".as_slice(), (-1, 0)),
            (b"-999999999.0".as_slice(), (-1, 1)),
            (b"-1000.5".as_slice(), (-1, 999_998_999)),
            (b"-1.5".as_slice(), (-1, 999_999_998)),
            (b"-1.0".as_slice(), (-1, 999_999_999)),
            (b"-0.0".as_slice(), (0, 0)),
            (b"0.0".as_slice(), (0, 0)),
            (b"1.0".as_slice(), (0, 1)),
            (b"1.5".as_slice(), (0, 1)),
            (b"1000.5".as_slice(), (0, 1_000)),
            (b"999999999.0".as_slice(), (0, 999_999_999)),
            (b"999999999.5".as_slice(), (0, 999_999_999)),
            (b"1000000000.0".as_slice(), (1, 0)),
            (b"1000000000.5".as_slice(), (1, 0)),
            (b"1000000001.0".as_slice(), (1, 1)),
            // Nanosecond and below (truncates, does not round).
            (b"-0.1".as_slice(), (-1, 999_999_999)),
            (b"0.1".as_slice(), (0, 0)),
        ];

        let subsec_unit: Option<&[u8]> = Some(b":nsec");

        for (input, expectation) in &expectations {
            let result = subsec(&mut interp, (Some(input), subsec_unit)).unwrap();
            assert_eq!(
                result.to_tuple(),
                *expectation,
                "Expected TryConvertMut<(Some({}), None), Result<Subsec>>, to return {} secs, {} nanos",
                input.as_bstr(),
                expectation.0,
                expectation.1
            );
        }
    }

    #[test]
    fn float_nan_raises() {
        let mut interp = interpreter();

        let err = subsec(&mut interp, (Some(b"Float::NAN"), None)).unwrap_err();

        assert_eq!(err.name(), "FloatDomainError");
        assert_eq!(err.message(), b"NaN".as_slice());
    }

    #[test]
    fn float_infinite_raises() {
        let mut interp = interpreter();

        let err = subsec(&mut interp, (Some(b"Float::INFINITY"), None)).unwrap_err();

        assert_eq!(err.name(), "FloatDomainError");
        assert_eq!(err.message().as_bstr(), b"Infinity".as_bstr());

        let err = subsec(&mut interp, (Some(b"-Float::INFINITY"), None)).unwrap_err();

        assert_eq!(err.name(), "FloatDomainError");
        assert_eq!(err.message().as_bstr(), b"-Infinity".as_bstr());
    }

    #[test]
    fn invalid_subsec_unit() {
        let mut interp = interpreter();

        let err = subsec(&mut interp, (Some(b"1"), Some(b":bad_unit"))).unwrap_err();

        assert_eq!(err.name(), "ArgumentError");
        assert_eq!(err.message().as_bstr(), b"unexpected unit: bad_unit".as_bstr());
    }

    #[test]
    fn subsec_unit_non_symbol() {
        let mut interp = interpreter();

        let err = subsec(&mut interp, (Some(b"1"), Some(b":bad_unit"))).unwrap_err();

        assert_eq!(err.name(), "ArgumentError");
        assert_eq!(err.message().as_bstr(), b"unexpected unit: bad_unit".as_bstr());

        let err = subsec(&mut interp, (Some(b"1"), Some(b"1"))).unwrap_err();

        assert_eq!(err.name(), "ArgumentError");
        assert_eq!(err.message().as_bstr(), b"unexpected unit: 1".as_bstr());

        let err = subsec(&mut interp, (Some(b"1"), Some(b"Object.new"))).unwrap_err();

        assert_eq!(err.name(), "ArgumentError");
        assert!(err
            .message()
            .as_bstr()
            .starts_with(b"unexpected unit: #<Object:".as_bstr()));
    }

    #[test]
    fn subsec_unit_requires_explicit_symbol() {
        let mut interp = interpreter();

        let err = subsec(
            &mut interp,
            (Some(b"1"), Some(b"class A; def to_sym; :usec; end; end && A.new")),
        )
        .unwrap_err();

        assert_eq!(err.name(), "ArgumentError");
        assert!(err.message().as_bstr().starts_with(b"unexpected unit: #<A:".as_bstr()));
    }
}