eth-native 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,694 @@
1
+ //! Whole-payload RLP encoding and decoding for Ruby object trees.
2
+ //!
3
+ //! Semantics mirror the eth.rb 0.5.18 reference implementation (`Eth::Rlp::Encoder`
4
+ //! and `Eth::Rlp::Decoder`) byte for byte, including exception categories and
5
+ //! stable messages. Trees the reference implementation would route through
6
+ //! custom sedes, non-Array enumerables or `Rlp::Data` are rejected with the
7
+ //! dedicated `UnsupportedInput` exception so the Ruby compatibility layer can
8
+ //! delegate them to the pure-Ruby implementation; no other failure triggers a
9
+ //! fallback.
10
+
11
+ use std::borrow::Cow;
12
+
13
+ use magnus::{
14
+ value::ReprValue, Error, ExceptionClass, Integer, Module, RArray, RClass, RString, Ruby, Value,
15
+ };
16
+
17
+ /// Maximum tree depth handled natively. Deeper trees are rejected as
18
+ /// unsupported so the Ruby fallback can apply its own reference behaviour
19
+ /// (including its stack-depth limits) without risking a Rust stack overflow.
20
+ const MAX_NATIVE_DEPTH: usize = 256;
21
+
22
+ const ORD_NIL: &str = "undefined method 'ord' for nil";
23
+ const UNPACK_NIL: &str = "undefined method 'unpack' for nil";
24
+ const SHORT_AS_SINGLE: &str = "Encoded as short string although single byte was possible";
25
+ const ZERO_LEN: &str = "Length starts with zero bytes";
26
+ const LONG_STR_SHORT: &str = "Long string prefix used for short string";
27
+ const LONG_LIST_SHORT: &str = "Long list prefix used for short list";
28
+ const LIST_TOO_SMALL: &str = "List length prefix announced a too small length";
29
+ const BIGNUM_SLICE: &str = "bignum too big to convert into 'long'";
30
+
31
+ /// Largest value a Ruby `long` can hold; String slices beyond it raise.
32
+ const LONG_MAX: i64 = i64::MAX / 2 * 2 + 1; // 2^63 - 1 on 64-bit
33
+
34
+ /// Payloads longer than this become shared substrings instead of copies.
35
+ const SHARED_SLICE_THRESHOLD: usize = 256;
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // entry points
39
+ // ---------------------------------------------------------------------------
40
+
41
+ /// Decodes RLP bytes (hex-or-binary, per the reference heuristic) into
42
+ /// `String`/`Array` trees, mirroring the reference decoder including its
43
+ /// canonical checks, boundary behaviour and stable messages.
44
+ pub fn decode_entry(ruby: &Ruby, input: Value) -> Result<Value, Error> {
45
+ let rstr = match RString::from_value(input) {
46
+ Some(s) => s,
47
+ // The Ruby wrapper validates the exact type first; kept defensive.
48
+ None => {
49
+ return Err(decoding_error(
50
+ ruby,
51
+ "Cannot decode rlp string: input must be a String".to_owned(),
52
+ ))
53
+ }
54
+ };
55
+ let data = {
56
+ // Reserve first (this allocation may run GC or compaction), then
57
+ // take a fresh borrow and copy it without any further allocation.
58
+ let len = unsafe { rstr.as_slice() }.len();
59
+ let mut copy = Vec::with_capacity(len);
60
+ copy.extend_from_slice(unsafe { rstr.as_slice() });
61
+ copy
62
+ };
63
+
64
+ match decode_item(ruby, rstr, &data, 0, 0) {
65
+ Ok((value, next)) if next == data.len() as u128 => Ok(value),
66
+ Ok((_, next)) => {
67
+ let superfluous = data.len() as i128 - next as i128;
68
+ Err(decoding_error(
69
+ ruby,
70
+ format!("RLP string ends with {superfluous} superfluous bytes"),
71
+ ))
72
+ }
73
+ Err(DecFail::Unsupported) => Err(unsupported_error(ruby)),
74
+ Err(DecFail::Inner(inner)) => Err(decoding_error(
75
+ ruby,
76
+ format!("Cannot decode rlp string: {inner}"),
77
+ )),
78
+ }
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // shared helpers
83
+ // ---------------------------------------------------------------------------
84
+
85
+ struct Classes {
86
+ string: RClass,
87
+ array: RClass,
88
+ }
89
+
90
+ impl Classes {
91
+ fn fetch(ruby: &Ruby) -> Result<Self, Error> {
92
+ Ok(Self {
93
+ string: fetch_class(ruby, "String")?,
94
+ array: fetch_class(ruby, "Array")?,
95
+ })
96
+ }
97
+ }
98
+
99
+ fn fetch_class(ruby: &Ruby, name: &str) -> Result<RClass, Error> {
100
+ let value: Value = ruby.class_object().const_get(name)?;
101
+ RClass::from_value(value).ok_or_else(|| {
102
+ Error::new(
103
+ ruby.exception_runtime_error(),
104
+ format!("expected class {name}"),
105
+ )
106
+ })
107
+ }
108
+
109
+ fn rlp_exceptions(ruby: &Ruby) -> Result<(ExceptionClass, ExceptionClass, ExceptionClass), Error> {
110
+ let eth: magnus::RModule = ruby.class_object().const_get("Eth")?;
111
+ let native: magnus::RModule = eth.const_get("Native")?;
112
+ let rlp: magnus::RModule = native.const_get("Rlp")?;
113
+ Ok((
114
+ exception_class(ruby, &rlp, "UnsupportedInput")?,
115
+ exception_class(ruby, &rlp, "EncodingError")?,
116
+ exception_class(ruby, &rlp, "DecodingError")?,
117
+ ))
118
+ }
119
+
120
+ fn exception_class(
121
+ ruby: &Ruby,
122
+ rlp: &magnus::RModule,
123
+ name: &str,
124
+ ) -> Result<ExceptionClass, Error> {
125
+ let value: Value = rlp.const_get(name)?;
126
+ ExceptionClass::from_value(value).ok_or_else(|| {
127
+ Error::new(
128
+ ruby.exception_runtime_error(),
129
+ format!("Eth::Native::Rlp::{name} is not an exception class"),
130
+ )
131
+ })
132
+ }
133
+
134
+ fn unsupported_error(ruby: &Ruby) -> Error {
135
+ match rlp_exceptions(ruby) {
136
+ Ok((unsupported, _, _)) => Error::new(
137
+ unsupported,
138
+ "input is reserved for the pure-Ruby RLP implementation",
139
+ ),
140
+ Err(err) => err,
141
+ }
142
+ }
143
+
144
+ fn decoding_error(ruby: &Ruby, message: String) -> Error {
145
+ match rlp_exceptions(ruby) {
146
+ Ok((_, _, decoding)) => Error::new(decoding, message),
147
+ Err(err) => err,
148
+ }
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // encoding
153
+ // ---------------------------------------------------------------------------
154
+
155
+ enum Fail {
156
+ /// Input belongs to the pure-Ruby implementation; the wrapper falls back.
157
+ Unsupported,
158
+ /// A real error; propagated as-is.
159
+ Native(Error),
160
+ }
161
+
162
+ impl From<Error> for Fail {
163
+ fn from(err: Error) -> Self {
164
+ Fail::Native(err)
165
+ }
166
+ }
167
+
168
+ /// Encodes in two passes over the tree: measure the exact encoded size, then
169
+ /// write into a pre-sized Ruby string. Every payload byte is copied exactly
170
+ /// once and no Ruby allocation happens while a Ruby string buffer is
171
+ /// borrowed, so the borrows stay valid even under GC compaction.
172
+ pub fn encode_entry(ruby: &Ruby, obj: Value) -> Result<RString, Error> {
173
+ let classes = Classes::fetch(ruby)?;
174
+ let total = match measure_item(&classes, obj, 0) {
175
+ Ok(size) => size,
176
+ Err(Fail::Unsupported) => return Err(unsupported_error(ruby)),
177
+ Err(Fail::Native(err)) => return Err(err),
178
+ };
179
+ let out = ruby.str_buf_new(total);
180
+ match write_item(&classes, out, obj, 0) {
181
+ Ok(()) => Ok(out),
182
+ Err(Fail::Unsupported) => Err(unsupported_error(ruby)),
183
+ Err(Fail::Native(err)) => Err(err),
184
+ }
185
+ }
186
+
187
+ /// Integers (fixnum, bignum and subclasses), matching `Sedes.infer`'s
188
+ /// `is_a?(Integer) && obj >= 0` branch. Negatives go back to Ruby so the
189
+ /// reference raises its own `TypeError`.
190
+ fn measure_item(classes: &Classes, value: Value, depth: usize) -> Result<usize, Fail> {
191
+ if let Some(int) = Integer::from_value(value) {
192
+ return measure_integer(int, value);
193
+ }
194
+
195
+ // Exact String instances. `Rlp::Data` and other subclasses fall back to
196
+ // Ruby, where `Binary.valid_type?` rejects them with a `TypeError`.
197
+ if value.class().equal(classes.string)? {
198
+ let s = RString::from_value(value).ok_or(Fail::Unsupported)?;
199
+ // Borrow only; no allocation happens before the borrow is dropped.
200
+ let bytes = unsafe { s.as_slice() };
201
+ return Ok(encoded_string_size(bytes));
202
+ }
203
+
204
+ // Exact Array instances. Other enumerables (Hash, Set, custom sedes,
205
+ // ...) fall back to Ruby.
206
+ if value.class().equal(classes.array)? {
207
+ if depth >= MAX_NATIVE_DEPTH {
208
+ return Err(Fail::Unsupported);
209
+ }
210
+ let ary = RArray::from_value(value).ok_or(Fail::Unsupported)?;
211
+ let mut payload = 0usize;
212
+ for i in 0..ary.len() {
213
+ let child: Value = ary.entry(i as isize)?;
214
+ payload += measure_item(classes, child, depth + 1)?;
215
+ }
216
+ return Ok(length_prefix_size(payload) + payload);
217
+ }
218
+
219
+ Err(Fail::Unsupported)
220
+ }
221
+
222
+ fn write_item(classes: &Classes, out: RString, value: Value, depth: usize) -> Result<(), Fail> {
223
+ if let Some(int) = Integer::from_value(value) {
224
+ return write_integer(out, int, value);
225
+ }
226
+
227
+ if value.class().equal(classes.string)? {
228
+ let s = RString::from_value(value).ok_or(Fail::Unsupported)?;
229
+ // `as_slice` borrows the Ruby string buffer. The write pass performs
230
+ // no Ruby allocation while the borrow is live (the output string is
231
+ // pre-sized; `cat` only writes into it), keeping the borrow stable.
232
+ let bytes = unsafe { s.as_slice() };
233
+ push_string_payload(out, bytes);
234
+ return Ok(());
235
+ }
236
+
237
+ if value.class().equal(classes.array)? {
238
+ if depth >= MAX_NATIVE_DEPTH {
239
+ return Err(Fail::Unsupported);
240
+ }
241
+ let ary = RArray::from_value(value).ok_or(Fail::Unsupported)?;
242
+ let mut payload = 0usize;
243
+ for i in 0..ary.len() {
244
+ let child: Value = ary.entry(i as isize)?;
245
+ payload += measure_item(classes, child, depth + 1)?;
246
+ }
247
+ push_length_prefix(out, payload, 0xc0);
248
+ for i in 0..ary.len() {
249
+ let child: Value = ary.entry(i as isize)?;
250
+ write_item(classes, out, child, depth + 1)?;
251
+ }
252
+ return Ok(());
253
+ }
254
+
255
+ Err(Fail::Unsupported)
256
+ }
257
+
258
+ fn measure_integer(int: Integer, value: Value) -> Result<usize, Fail> {
259
+ // Fast path: everything that fits in an i64 (all fixnums).
260
+ if let Ok(n) = int.to_i64() {
261
+ if n < 0 {
262
+ return Err(Fail::Unsupported);
263
+ }
264
+ return Ok(encoded_int_value_size(n as u128));
265
+ }
266
+ // Mid path: positive values up to u128.
267
+ if let Ok(n) = int.to_u128() {
268
+ return Ok(encoded_int_value_size(n));
269
+ }
270
+ // Negative bignums that still fit in i128.
271
+ if let Ok(n) = int.to_i128() {
272
+ if n < 0 {
273
+ return Err(Fail::Unsupported);
274
+ }
275
+ return Ok(encoded_int_value_size(n as u128));
276
+ }
277
+ // Large bignums: sign and hex digits via Ruby (cold path). Their
278
+ // payloads always span multiple bytes, so the single-byte rule of the
279
+ // string encoding never applies.
280
+ let negative: bool = value.funcall("<", (0,))?;
281
+ if negative {
282
+ return Err(Fail::Unsupported);
283
+ }
284
+ let hex: String = value.funcall("to_s", (16,))?;
285
+ let len = hex_to_be_len(&hex);
286
+ Ok(length_prefix_size(len) + len)
287
+ }
288
+
289
+ fn write_integer(out: RString, int: Integer, value: Value) -> Result<(), Fail> {
290
+ if let Ok(n) = int.to_i64() {
291
+ if n < 0 {
292
+ return Err(Fail::Unsupported);
293
+ }
294
+ return write_int_payload(out, n as u128);
295
+ }
296
+ if let Ok(n) = int.to_u128() {
297
+ return write_int_payload(out, n);
298
+ }
299
+ if let Ok(n) = int.to_i128() {
300
+ if n < 0 {
301
+ return Err(Fail::Unsupported);
302
+ }
303
+ return write_int_payload(out, n as u128);
304
+ }
305
+ let negative: bool = value.funcall("<", (0,))?;
306
+ if negative {
307
+ return Err(Fail::Unsupported);
308
+ }
309
+ let hex: String = value.funcall("to_s", (16,))?;
310
+ push_string_payload(out, &hex_to_be_bytes(&hex));
311
+ Ok(())
312
+ }
313
+
314
+ fn write_int_payload(out: RString, n: u128) -> Result<(), Fail> {
315
+ if n == 0 {
316
+ push_length_prefix(out, 0, 0x80);
317
+ return Ok(());
318
+ }
319
+ if n < 0x80 {
320
+ out.cat([n as u8]);
321
+ return Ok(());
322
+ }
323
+ let (len, bytes) = be_bytes128(n);
324
+ push_length_prefix(out, len, 0x80);
325
+ out.cat(&bytes[..len]);
326
+ Ok(())
327
+ }
328
+
329
+ /// Minimal big-endian byte length of `n`; `0` encodes as the empty payload.
330
+ fn min_be_len(n: u128) -> usize {
331
+ be_bytes128(n).0
332
+ }
333
+
334
+ /// Minimal big-endian bytes, front-aligned with their length.
335
+ fn be_bytes128(n: u128) -> (usize, [u8; 16]) {
336
+ let be = n.to_be_bytes();
337
+ if n == 0 {
338
+ return (0, be);
339
+ }
340
+ let first = be.iter().position(|&b| b != 0).expect("nonzero");
341
+ let len = 16 - first;
342
+ let mut out = [0u8; 16];
343
+ out.copy_from_slice(&be);
344
+ out.rotate_left(first);
345
+ (len, out)
346
+ }
347
+
348
+ /// Encoded size of a non-negative integer value: values below 0x80 are
349
+ /// their own single-byte encoding, `0` is the empty payload (0x80), and
350
+ /// everything else gets a length prefix around its minimal bytes.
351
+ fn encoded_int_value_size(n: u128) -> usize {
352
+ if n < 0x80 {
353
+ 1
354
+ } else {
355
+ let len = min_be_len(n);
356
+ length_prefix_size(len) + len
357
+ }
358
+ }
359
+
360
+ fn encoded_string_size(payload: &[u8]) -> usize {
361
+ if payload.len() == 1 && payload[0] < 0x80 {
362
+ 1
363
+ } else {
364
+ length_prefix_size(payload.len()) + payload.len()
365
+ }
366
+ }
367
+
368
+ fn length_prefix_size(length: usize) -> usize {
369
+ if length < 56 {
370
+ 1
371
+ } else {
372
+ 1 + min_be_len(length as u128)
373
+ }
374
+ }
375
+
376
+ /// Hex digits (no leading zeros, as produced by `Integer#to_s(16)`) to
377
+ /// minimal big-endian bytes, padding odd lengths like `Util#int_to_big_endian`.
378
+ fn hex_to_be_bytes(hex: &str) -> Vec<u8> {
379
+ let padded: Cow<[u8]> = if hex.len() % 2 == 1 {
380
+ let mut h = Vec::with_capacity(hex.len() + 1);
381
+ h.push(b'0');
382
+ h.extend_from_slice(hex.as_bytes());
383
+ Cow::Owned(h)
384
+ } else {
385
+ Cow::Borrowed(hex.as_bytes())
386
+ };
387
+ padded
388
+ .chunks_exact(2)
389
+ .map(|pair| (nibble(pair[0]) << 4) | nibble(pair[1]))
390
+ .collect()
391
+ }
392
+
393
+ fn hex_to_be_len(hex: &str) -> usize {
394
+ hex.len().div_ceil(2)
395
+ }
396
+
397
+ fn nibble(b: u8) -> u8 {
398
+ match b {
399
+ b'0'..=b'9' => b - b'0',
400
+ b'a'..=b'f' => b - b'a' + 10,
401
+ b'A'..=b'F' => b - b'A' + 10,
402
+ _ => unreachable!("only called with validated hex digits"),
403
+ }
404
+ }
405
+
406
+ fn push_string_payload(out: RString, payload: &[u8]) {
407
+ if payload.len() == 1 && payload[0] < 0x80 {
408
+ out.cat(&payload[..1]);
409
+ } else {
410
+ push_length_prefix(out, payload.len(), 0x80);
411
+ out.cat(payload);
412
+ }
413
+ }
414
+
415
+ fn push_length_prefix(out: RString, length: usize, offset: u8) {
416
+ if length < 56 {
417
+ out.cat([offset + length as u8]);
418
+ } else {
419
+ // On 64-bit platforms `length >= 256**8` is unreachable, matching
420
+ // eth.rb where the `EncodingError` raise is equally unreachable.
421
+ let (len, bytes) = be_bytes128(length as u128);
422
+ debug_assert!(len <= 8, "Length greater than 256**8");
423
+ out.cat([offset + 55 + len as u8]);
424
+ out.cat(&bytes[..len]);
425
+ }
426
+ }
427
+
428
+ // ---------------------------------------------------------------------------
429
+ // decoding
430
+ // ---------------------------------------------------------------------------
431
+
432
+ #[derive(Debug)]
433
+ enum DecFail {
434
+ /// Deep trees fall back to the reference decoder.
435
+ Unsupported,
436
+ /// A reference-internal failure; wrapped as
437
+ /// "Cannot decode rlp string: {inner}" like eth.rb's rescue.
438
+ Inner(Cow<'static, str>),
439
+ }
440
+
441
+ impl From<Cow<'static, str>> for DecFail {
442
+ fn from(inner: Cow<'static, str>) -> Self {
443
+ DecFail::Inner(inner)
444
+ }
445
+ }
446
+
447
+ impl From<&'static str> for DecFail {
448
+ fn from(inner: &'static str) -> Self {
449
+ DecFail::Inner(Cow::Borrowed(inner))
450
+ }
451
+ }
452
+
453
+ impl From<Error> for DecFail {
454
+ fn from(err: Error) -> Self {
455
+ DecFail::Inner(Cow::Owned(format!("internal error: {err}")))
456
+ }
457
+ }
458
+
459
+ fn byte_at(data: &[u8], i: u128) -> Option<u8> {
460
+ if i < data.len() as u128 {
461
+ Some(data[i as usize])
462
+ } else {
463
+ None
464
+ }
465
+ }
466
+
467
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
468
+ enum Kind {
469
+ Str,
470
+ List,
471
+ }
472
+
473
+ /// Mirrors `Decoder#consume_length_prefix`, including its nil-byte semantics.
474
+ fn consume_prefix(data: &[u8], start: u128) -> Result<(Kind, u128, u128), DecFail> {
475
+ let b0 = byte_at(data, start).ok_or(ORD_NIL)?;
476
+
477
+ if b0 < 0x80 {
478
+ return Ok((Kind::Str, 1, start));
479
+ }
480
+ if b0 < 0xb8 {
481
+ let length = (b0 - 0x80) as u128;
482
+ if length == 1 {
483
+ let b1 = byte_at(data, start + 1).ok_or(ORD_NIL)?;
484
+ if b1 < 0x80 {
485
+ return Err(SHORT_AS_SINGLE.into());
486
+ }
487
+ }
488
+ return Ok((Kind::Str, length, start + 1));
489
+ }
490
+ if b0 < 0xc0 {
491
+ let ll = (b0 - 183) as u128; // b0 - 0x80 - 56 + 1
492
+ enforce_no_zero_bytes(data, start)?;
493
+ let length = length_from_prefix(data, start + 1, ll)?;
494
+ if length < 56 {
495
+ return Err(LONG_STR_SHORT.into());
496
+ }
497
+ return Ok((Kind::Str, length, start + 1 + ll));
498
+ }
499
+ if b0 < 0xf8 {
500
+ return Ok((Kind::List, (b0 - 0xc0) as u128, start + 1));
501
+ }
502
+
503
+ let ll = (b0 - 247) as u128; // b0 - 0xc0 - 56 + 1
504
+ enforce_no_zero_bytes(data, start)?;
505
+ let length = length_from_prefix(data, start + 1, ll)?;
506
+ if length < 56 {
507
+ return Err(LONG_LIST_SHORT.into());
508
+ }
509
+ Ok((Kind::List, length, start + 1 + ll))
510
+ }
511
+
512
+ /// Only the first length byte is checked, exactly like
513
+ /// `Decoder#enforce_no_zero_bytes` (a missing byte compares unequal to 0x00).
514
+ fn enforce_no_zero_bytes(data: &[u8], start: u128) -> Result<(), DecFail> {
515
+ if byte_at(data, start + 1) == Some(0) {
516
+ Err(ZERO_LEN.into())
517
+ } else {
518
+ Ok(())
519
+ }
520
+ }
521
+
522
+ /// Big-endian length from the prefix bytes. Truncated prefixes decode from
523
+ /// the bytes available (`Util#big_endian_to_int` of an empty slice is 0);
524
+ /// a slice starting past the end is nil in Ruby, which surfaces as the
525
+ /// wrapped `unpack` NoMethodError.
526
+ fn length_from_prefix(data: &[u8], from: u128, ll: u128) -> Result<u128, DecFail> {
527
+ if from > data.len() as u128 {
528
+ return Err(UNPACK_NIL.into());
529
+ }
530
+ let begin = from as usize;
531
+ let end = (from + ll).min(data.len() as u128) as usize;
532
+ let mut value: u128 = 0;
533
+ for &b in &data[begin..end] {
534
+ value = (value << 8) | b as u128;
535
+ }
536
+ Ok(value)
537
+ }
538
+
539
+ /// Mirrors `Decoder#consume_item`/`consume_payload`. Truncated payloads yield
540
+ /// the bytes available and advance the cursor by the claimed length, matching
541
+ /// Ruby slicing; overshooting cursors always trip a boundary check later, so
542
+ /// such values never reach the caller.
543
+ fn decode_item(
544
+ ruby: &Ruby,
545
+ input: RString,
546
+ data: &[u8],
547
+ start: u128,
548
+ depth: usize,
549
+ ) -> Result<(Value, u128), DecFail> {
550
+ let (kind, length, payload_start) = consume_prefix(data, start)?;
551
+
552
+ match kind {
553
+ Kind::Str => {
554
+ // Ruby slices the payload with `rlp[start...(start + length)]`;
555
+ // an end beyond `long` raises a RangeError that the decoder's
556
+ // rescue wraps into a DecodingError. Replicate that threshold
557
+ // instead of quietly truncating.
558
+ let end = payload_start.saturating_add(length);
559
+ if end > LONG_MAX as u128 {
560
+ return Err(BIGNUM_SLICE.into());
561
+ }
562
+ let begin = payload_start.min(data.len() as u128) as usize;
563
+ let end = end.min(data.len() as u128) as usize;
564
+ let value = if end - begin > SHARED_SLICE_THRESHOLD {
565
+ // Large payloads become shared substrings (`rb_str_subseq`
566
+ // semantics of `String#[]`), avoiding a full copy; Ruby keeps
567
+ // the parent buffer alive through the shared reference.
568
+ input.funcall("byteslice", (begin, end - begin))?
569
+ } else {
570
+ ruby.str_from_slice(&data[begin..end]).as_value()
571
+ };
572
+ Ok((value, payload_start + length))
573
+ }
574
+ Kind::List => {
575
+ if depth >= MAX_NATIVE_DEPTH {
576
+ return Err(DecFail::Unsupported);
577
+ }
578
+ let capacity = if length <= data.len() as u128 {
579
+ length as usize
580
+ } else {
581
+ 4
582
+ };
583
+ let items = ruby.ary_new_capa(capacity);
584
+ let payload_end = payload_start + length;
585
+ let mut next = payload_start;
586
+ while next < payload_end {
587
+ let (item, after) = decode_item(ruby, input, data, next, depth + 1)?;
588
+ items.push(item)?;
589
+ next = after;
590
+ }
591
+ if next > payload_end {
592
+ return Err(LIST_TOO_SMALL.into());
593
+ }
594
+ Ok((items.as_value(), next))
595
+ }
596
+ }
597
+ }
598
+
599
+ // ---------------------------------------------------------------------------
600
+ // pure unit tests (no Ruby runtime involved)
601
+ // ---------------------------------------------------------------------------
602
+
603
+ #[cfg(test)]
604
+ mod tests {
605
+ use super::*;
606
+
607
+ #[test]
608
+ fn be_bytes128_matches_reference_shapes() {
609
+ assert_eq!(min_be_len(0), 0);
610
+ let (len, bytes) = be_bytes128(1);
611
+ assert_eq!((len, &bytes[..len]), (1, &[0x01][..]));
612
+ let (len, bytes) = be_bytes128(0x80);
613
+ assert_eq!((len, &bytes[..len]), (1, &[0x80][..]));
614
+ let (len, bytes) = be_bytes128(1024);
615
+ assert_eq!((len, &bytes[..len]), (2, &[0x04, 0x00][..]));
616
+ let (len, bytes) = be_bytes128(u128::MAX);
617
+ assert_eq!((len, &bytes[..len]), (16, &[0xff; 16][..]));
618
+ }
619
+
620
+ #[test]
621
+ fn encoded_sizes_match_reference_shapes() {
622
+ assert_eq!(encoded_string_size(b""), 1);
623
+ assert_eq!(encoded_string_size(b"\x00"), 1);
624
+ assert_eq!(encoded_string_size(b"\x7f"), 1);
625
+ assert_eq!(encoded_string_size(b"\x80"), 2);
626
+ assert_eq!(encoded_string_size(b"dog"), 4);
627
+ assert_eq!(encoded_string_size(&[b'x'; 55]), 56);
628
+ assert_eq!(encoded_string_size(&[b'x'; 56]), 58);
629
+ assert_eq!(encoded_int_value_size(0), 1);
630
+ assert_eq!(encoded_int_value_size(1), 1);
631
+ assert_eq!(encoded_int_value_size(127), 1);
632
+ assert_eq!(encoded_int_value_size(128), 2);
633
+ assert_eq!(encoded_int_value_size(255), 2);
634
+ assert_eq!(encoded_int_value_size(256), 3);
635
+ assert_eq!(length_prefix_size(55), 1);
636
+ assert_eq!(length_prefix_size(56), 2);
637
+ assert_eq!(length_prefix_size(u64::MAX as usize), 9);
638
+ }
639
+
640
+ #[test]
641
+ fn hex_to_be_bytes_pads_odd_lengths() {
642
+ assert_eq!(hex_to_be_bytes("0"), vec![0x00]);
643
+ assert_eq!(hex_to_be_bytes("1"), vec![0x01]);
644
+ assert_eq!(hex_to_be_bytes("1234"), vec![0x12, 0x34]);
645
+ assert_eq!(hex_to_be_bytes("123"), vec![0x01, 0x23]);
646
+ }
647
+
648
+ fn prefix(data: &[u8]) -> (Kind, u128, u128) {
649
+ consume_prefix(data, 0).unwrap()
650
+ }
651
+
652
+ fn prefix_err(data: &[u8]) -> Cow<'static, str> {
653
+ match consume_prefix(data, 0) {
654
+ Err(DecFail::Inner(msg)) => msg,
655
+ other => panic!("expected inner error, got {other:?}"),
656
+ }
657
+ }
658
+
659
+ #[test]
660
+ fn prefix_ranges() {
661
+ assert_eq!(prefix(b"\x00"), (Kind::Str, 1, 0));
662
+ assert_eq!(prefix(b"\x7f"), (Kind::Str, 1, 0));
663
+ assert_eq!(prefix(b"\x80\x01"), (Kind::Str, 0, 1));
664
+ assert_eq!(prefix(b"\x81\x80"), (Kind::Str, 1, 1));
665
+ assert_eq!(prefix(b"\xb7\x37"), (Kind::Str, 55, 1));
666
+ assert_eq!(prefix(b"\xb8\x38"), (Kind::Str, 56, 2));
667
+ assert_eq!(
668
+ prefix(b"\xbf\xff\xff\xff\xff\xff\xff\xff\xff"),
669
+ (Kind::Str, u128::from(u64::MAX), 9),
670
+ );
671
+ assert_eq!(prefix(b"\xc0"), (Kind::List, 0, 1));
672
+ assert_eq!(prefix(b"\xf7\x37"), (Kind::List, 55, 1));
673
+ assert_eq!(prefix(b"\xf8\x38"), (Kind::List, 56, 2));
674
+ }
675
+
676
+ #[test]
677
+ fn prefix_canonical_errors() {
678
+ assert_eq!(prefix_err(b"\x81\x00"), SHORT_AS_SINGLE);
679
+ assert_eq!(prefix_err(b"\xb8\x05"), LONG_STR_SHORT);
680
+ assert_eq!(prefix_err(b"\xf8\x05"), LONG_LIST_SHORT);
681
+ assert_eq!(prefix_err(b"\xb8\x00\x61\x62\x63\x64"), ZERO_LEN);
682
+ assert_eq!(prefix_err(b"\xf8\x00\x61\x62\x63\x64"), ZERO_LEN);
683
+ assert_eq!(prefix_err(b"\x81"), ORD_NIL);
684
+ }
685
+
686
+ #[test]
687
+ fn prefix_truncated_length_decodes_from_available_bytes() {
688
+ // Ruby: rlp[1...2] of "\xb8\x01" is "" -> length 0 -> "Long string
689
+ // prefix used for short string".
690
+ assert_eq!(prefix_err(b"\xb8\x01"), LONG_STR_SHORT);
691
+ // Ruby: rlp[1...3] of "\xb9\x02\x38" is "\x02\x38" -> 0x238 (>= 56).
692
+ assert_eq!(prefix(b"\xb9\x02\x38"), (Kind::Str, 0x238, 3));
693
+ }
694
+ }