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.
- checksums.yaml +7 -0
- data/LICENSE +202 -0
- data/README.md +84 -0
- data/docs/ARCHITECTURE.md +162 -0
- data/docs/PLAN.md +90 -0
- data/docs/RELEASE.md +46 -0
- data/docs/benchmarks/abi.md +41 -0
- data/docs/benchmarks/e2e.md +46 -0
- data/docs/benchmarks/rlp.md +44 -0
- data/ext/eth_native/Cargo.lock +281 -0
- data/ext/eth_native/Cargo.toml +22 -0
- data/ext/eth_native/README.md +15 -0
- data/ext/eth_native/extconf.rb +6 -0
- data/ext/eth_native/src/abi.rs +2169 -0
- data/ext/eth_native/src/lib.rs +35 -0
- data/ext/eth_native/src/rlp.rs +694 -0
- data/lib/eth/native/abi.rb +267 -0
- data/lib/eth/native/rlp.rb +147 -0
- data/lib/eth/native/version.rb +7 -0
- data/lib/eth/native.rb +82 -0
- metadata +123 -0
|
@@ -0,0 +1,2169 @@
|
|
|
1
|
+
//! Compiled-schema ABI encoding and decoding.
|
|
2
|
+
//!
|
|
3
|
+
//! Ruby owns the authoritative `Eth::Abi::Type` parsing and compiles each
|
|
4
|
+
//! type tree into a descriptor; this module validates the descriptor into an
|
|
5
|
+
//! immutable [`Schema`] and performs whole-payload encode/decode in one
|
|
6
|
+
//! boundary crossing. Semantics mirror eth.rb 0.5.18 (`Abi.encode/decode`,
|
|
7
|
+
//! `Encoder.type`, `Decoder.type`) including exception categories and stable
|
|
8
|
+
//! messages. Values the reference would coerce through BigDecimal (decimal
|
|
9
|
+
//! float strings, BigDecimal objects) are rejected as unsupported so the
|
|
10
|
+
//! Ruby layer can fall back explicitly.
|
|
11
|
+
|
|
12
|
+
use std::borrow::Cow;
|
|
13
|
+
|
|
14
|
+
use magnus::r_hash::ForEach;
|
|
15
|
+
use magnus::{
|
|
16
|
+
value::ReprValue, wrap, Error, ExceptionClass, Float, Integer, Module, RArray, RHash, RString,
|
|
17
|
+
Ruby, TryConvert, Value,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/// Payloads longer than this become shared substrings on decode.
|
|
21
|
+
const SHARED_SLICE_THRESHOLD: usize = 256;
|
|
22
|
+
|
|
23
|
+
/// Largest value a Ruby `long` can hold; index arithmetic beyond it raises
|
|
24
|
+
/// a RangeError the reference surfaces raw.
|
|
25
|
+
const LONG_MAX: u128 = (i64::MAX / 2 * 2 + 1) as u128;
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// schema
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
#[derive(Clone, Debug)]
|
|
32
|
+
enum Schema {
|
|
33
|
+
UInt(u32),
|
|
34
|
+
Int(u32),
|
|
35
|
+
Bool,
|
|
36
|
+
Address,
|
|
37
|
+
Hash(u32),
|
|
38
|
+
BytesN(u32),
|
|
39
|
+
Str,
|
|
40
|
+
Bytes,
|
|
41
|
+
/// `0` marks a dynamic length.
|
|
42
|
+
Array(Box<Schema>, usize),
|
|
43
|
+
Tuple(Vec<(Option<String>, Schema)>),
|
|
44
|
+
/// Packed fixed-point only (`ufixed`/`fixed`XxY): byte size and decimal
|
|
45
|
+
/// count follow the reference `Packed::Encoder` parameter mapping.
|
|
46
|
+
Fixed {
|
|
47
|
+
signed: bool,
|
|
48
|
+
byte_size: usize,
|
|
49
|
+
decimals: u32,
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
impl Schema {
|
|
54
|
+
/// Mirrors `Eth::Abi::Type#size`; `None` marks a dynamic type.
|
|
55
|
+
fn size(&self) -> Option<usize> {
|
|
56
|
+
match self {
|
|
57
|
+
Schema::Array(elem, len) => {
|
|
58
|
+
if *len != 0 {
|
|
59
|
+
elem.size().map(|s| s * len)
|
|
60
|
+
} else {
|
|
61
|
+
None
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
Schema::Tuple(comps) => {
|
|
65
|
+
let mut total = 0usize;
|
|
66
|
+
for (_, comp) in comps {
|
|
67
|
+
total += comp.size()?;
|
|
68
|
+
}
|
|
69
|
+
Some(total)
|
|
70
|
+
}
|
|
71
|
+
Schema::Str | Schema::Bytes | Schema::Fixed { .. } => None,
|
|
72
|
+
_ => Some(32),
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fn dynamic(&self) -> bool {
|
|
77
|
+
self.size().is_none()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// Wraps compiled schemas as an immutable Ruby object so callers compile
|
|
82
|
+
/// once (e.g. at contract-function init) and reuse the handle.
|
|
83
|
+
#[wrap(class = "EthNativeAbiSchema", free_immediately)]
|
|
84
|
+
pub struct AbiSchemaWrap {
|
|
85
|
+
schemas: Vec<Schema>,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// Defines the schema wrapper class; called from the extension init.
|
|
89
|
+
pub fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
90
|
+
ruby.define_class("EthNativeAbiSchema", ruby.class_object())?;
|
|
91
|
+
Ok(())
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// exceptions
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
struct AbiErrors {
|
|
99
|
+
unsupported_type: ExceptionClass,
|
|
100
|
+
unsupported_input: ExceptionClass,
|
|
101
|
+
encoding: ExceptionClass,
|
|
102
|
+
decoding: ExceptionClass,
|
|
103
|
+
value_out_of_bounds: ExceptionClass,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
fn abi_errors(ruby: &Ruby) -> Result<AbiErrors, Error> {
|
|
107
|
+
let eth: magnus::RModule = ruby.class_object().const_get("Eth")?;
|
|
108
|
+
let native: magnus::RModule = eth.const_get("Native")?;
|
|
109
|
+
let abi: magnus::RModule = native.const_get("Abi")?;
|
|
110
|
+
Ok(AbiErrors {
|
|
111
|
+
unsupported_type: exception_class(ruby, &abi, "UnsupportedType")?,
|
|
112
|
+
unsupported_input: exception_class(ruby, &abi, "UnsupportedInput")?,
|
|
113
|
+
encoding: exception_class(ruby, &abi, "EncodingError")?,
|
|
114
|
+
decoding: exception_class(ruby, &abi, "DecodingError")?,
|
|
115
|
+
value_out_of_bounds: exception_class(ruby, &abi, "ValueOutOfBounds")?,
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
fn exception_class(
|
|
120
|
+
ruby: &Ruby,
|
|
121
|
+
module: &magnus::RModule,
|
|
122
|
+
name: &str,
|
|
123
|
+
) -> Result<ExceptionClass, Error> {
|
|
124
|
+
let value: Value = module.const_get(name)?;
|
|
125
|
+
ExceptionClass::from_value(value).ok_or_else(|| {
|
|
126
|
+
Error::new(
|
|
127
|
+
ruby.exception_runtime_error(),
|
|
128
|
+
format!("Eth::Native::Abi::{name} is not an exception class"),
|
|
129
|
+
)
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// failures
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
enum Fail {
|
|
138
|
+
/// Value shapes reserved for the Ruby implementation (BigDecimal et al).
|
|
139
|
+
Unsupported,
|
|
140
|
+
/// A real error; already mapped to the matching Ruby exception class.
|
|
141
|
+
Native(Error),
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
impl From<Error> for Fail {
|
|
145
|
+
fn from(err: Error) -> Self {
|
|
146
|
+
Fail::Native(err)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
impl Fail {
|
|
151
|
+
fn into_error(self, ruby: &Ruby) -> Error {
|
|
152
|
+
match self {
|
|
153
|
+
Fail::Unsupported => match abi_errors(ruby) {
|
|
154
|
+
Ok(e) => Error::new(
|
|
155
|
+
e.unsupported_input,
|
|
156
|
+
"value shape is reserved for the pure-Ruby ABI implementation",
|
|
157
|
+
),
|
|
158
|
+
Err(err) => err,
|
|
159
|
+
},
|
|
160
|
+
Fail::Native(err) => err,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
fn encoding_error(ruby: &Ruby, message: impl Into<Cow<'static, str>>) -> Fail {
|
|
166
|
+
match abi_errors(ruby) {
|
|
167
|
+
Ok(e) => Fail::Native(Error::new(e.encoding, message)),
|
|
168
|
+
Err(err) => Fail::Native(err),
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
fn decoding_error(ruby: &Ruby, message: impl Into<Cow<'static, str>>) -> Fail {
|
|
173
|
+
match abi_errors(ruby) {
|
|
174
|
+
Ok(e) => Fail::Native(Error::new(e.decoding, message)),
|
|
175
|
+
Err(err) => Fail::Native(err),
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
fn value_out_of_bounds(ruby: &Ruby, message: impl Into<Cow<'static, str>>) -> Fail {
|
|
180
|
+
match abi_errors(ruby) {
|
|
181
|
+
Ok(e) => Fail::Native(Error::new(e.value_out_of_bounds, message)),
|
|
182
|
+
Err(err) => Fail::Native(err),
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
fn type_error(ruby: &Ruby, message: &'static str) -> Fail {
|
|
187
|
+
Fail::Native(Error::new(ruby.exception_type_error(), message))
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/// Reference nil-dereference failures for malformed top-level slices, which
|
|
191
|
+
/// eth.rb raises as raw `NoMethodError` outside any rescue.
|
|
192
|
+
fn nil_method_error(ruby: &Ruby, method: &str) -> Fail {
|
|
193
|
+
Fail::Native(Error::new(
|
|
194
|
+
ruby.exception_no_method_error(),
|
|
195
|
+
format!("undefined method '{method}' for nil"),
|
|
196
|
+
))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// Message text for `#{arg}` interpolation: exactly Ruby's `to_s`, so
|
|
200
|
+
/// exception messages match the reference on every value shape.
|
|
201
|
+
fn display(_ruby: &Ruby, value: Value) -> String {
|
|
202
|
+
let s: RString = match value.funcall("to_s", ()) {
|
|
203
|
+
Ok(s) => s,
|
|
204
|
+
Err(_) => return value.inspect(),
|
|
205
|
+
};
|
|
206
|
+
String::from_utf8_lossy(unsafe { s.as_slice() }).into_owned()
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// entry points
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
/// Compiles a descriptor tree (plain Ruby hashes produced by
|
|
214
|
+
/// `Eth::Native::Abi.compile`) into an immutable schema object.
|
|
215
|
+
pub fn compile_entry(ruby: &Ruby, descriptors: Value) -> Result<AbiSchemaWrap, Error> {
|
|
216
|
+
let list = match RArray::from_value(descriptors) {
|
|
217
|
+
Some(l) => l,
|
|
218
|
+
None => {
|
|
219
|
+
return Err(Error::new(
|
|
220
|
+
ruby.exception_type_error(),
|
|
221
|
+
"descriptor list must be an Array",
|
|
222
|
+
))
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
let mut schemas = Vec::with_capacity(list.len());
|
|
226
|
+
for i in 0..list.len() {
|
|
227
|
+
let node: Value = list.entry(i as isize)?;
|
|
228
|
+
schemas.push(parse_schema(ruby, node)?);
|
|
229
|
+
}
|
|
230
|
+
Ok(AbiSchemaWrap { schemas })
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// Encodes values for a compiled schema list, mirroring `Abi.encode`.
|
|
234
|
+
pub fn encode_entry(ruby: &Ruby, schema: &AbiSchemaWrap, values: Value) -> Result<RString, Error> {
|
|
235
|
+
match encode_inner(ruby, &schema.schemas, values) {
|
|
236
|
+
Ok(out) => Ok(out),
|
|
237
|
+
Err(fail) => Err(fail.into_error(ruby)),
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
fn encode_inner(ruby: &Ruby, schemas: &[Schema], values: Value) -> Result<RString, Fail> {
|
|
242
|
+
let args = match RArray::from_value(values) {
|
|
243
|
+
Some(a) => a,
|
|
244
|
+
None => {
|
|
245
|
+
return Err(encoding_error(
|
|
246
|
+
ruby,
|
|
247
|
+
"Types and values must be the same length",
|
|
248
|
+
));
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
if args.len() != schemas.len() {
|
|
252
|
+
return Err(encoding_error(
|
|
253
|
+
ruby,
|
|
254
|
+
"Types and values must be the same length",
|
|
255
|
+
));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let head_size: usize = schemas.iter().map(|s| s.size().unwrap_or(32)).sum();
|
|
259
|
+
let mut head = Vec::with_capacity(head_size);
|
|
260
|
+
let mut tail = Vec::new();
|
|
261
|
+
for (i, schema) in schemas.iter().enumerate() {
|
|
262
|
+
let value: Value = args.entry(i as isize)?;
|
|
263
|
+
if schema.dynamic() {
|
|
264
|
+
head.extend_from_slice(&be32((head_size + tail.len()) as u128));
|
|
265
|
+
encode_value(ruby, schema, value, &mut tail)?;
|
|
266
|
+
} else {
|
|
267
|
+
encode_value(ruby, schema, value, &mut head)?;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
head.extend_from_slice(&tail);
|
|
271
|
+
Ok(ruby.str_from_slice(&head))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/// Decodes one payload for a compiled schema list, mirroring `Abi.decode`.
|
|
275
|
+
pub fn decode_entry(ruby: &Ruby, schema: &AbiSchemaWrap, data: Value) -> Result<RArray, Error> {
|
|
276
|
+
let input = match RString::from_value(data) {
|
|
277
|
+
Some(s) => s,
|
|
278
|
+
None => {
|
|
279
|
+
return Err(Error::new(
|
|
280
|
+
ruby.exception_type_error(),
|
|
281
|
+
"data must be a String",
|
|
282
|
+
))
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
let bytes = {
|
|
286
|
+
// Reserve first (may run GC), then take a fresh borrow and copy
|
|
287
|
+
// without further allocation, keeping the borrow compaction-safe.
|
|
288
|
+
let len = unsafe { input.as_slice() }.len();
|
|
289
|
+
let mut copy = Vec::with_capacity(len);
|
|
290
|
+
copy.extend_from_slice(unsafe { input.as_slice() });
|
|
291
|
+
copy
|
|
292
|
+
};
|
|
293
|
+
match decode_inner(ruby, &schema.schemas, &bytes) {
|
|
294
|
+
Ok(values) => Ok(ruby.ary_new_from_values(&values)),
|
|
295
|
+
Err(fail) => Err(fail.into_error(ruby)),
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/// Decodes many payloads with the same compiled schema (batch log indexing).
|
|
300
|
+
pub fn decode_many_entry(
|
|
301
|
+
ruby: &Ruby,
|
|
302
|
+
schema: &AbiSchemaWrap,
|
|
303
|
+
payloads: Value,
|
|
304
|
+
) -> Result<RArray, Error> {
|
|
305
|
+
let list = match RArray::from_value(payloads) {
|
|
306
|
+
Some(l) => l,
|
|
307
|
+
None => {
|
|
308
|
+
return Err(Error::new(
|
|
309
|
+
ruby.exception_type_error(),
|
|
310
|
+
"payloads must be an Array",
|
|
311
|
+
))
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
let mut results = Vec::with_capacity(list.len());
|
|
315
|
+
for i in 0..list.len() {
|
|
316
|
+
let payload: Value = list.entry(i as isize)?;
|
|
317
|
+
results.push(decode_entry(ruby, schema, payload)?);
|
|
318
|
+
}
|
|
319
|
+
Ok(ruby.ary_new_from_values(&results))
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ---------------------------------------------------------------------------
|
|
323
|
+
// schema parsing
|
|
324
|
+
// ---------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
fn parse_schema(ruby: &Ruby, node: Value) -> Result<Schema, Error> {
|
|
327
|
+
parse_descriptor(ruby, node, false)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
fn parse_descriptor(ruby: &Ruby, node: Value, packed: bool) -> Result<Schema, Error> {
|
|
331
|
+
let hash = match RHash::from_value(node) {
|
|
332
|
+
Some(h) => h,
|
|
333
|
+
None => {
|
|
334
|
+
return Err(Error::new(
|
|
335
|
+
ruby.exception_type_error(),
|
|
336
|
+
"descriptor must be a Hash",
|
|
337
|
+
))
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
let base: String = hash
|
|
341
|
+
.get("base_type")
|
|
342
|
+
.and_then(|v| String::try_convert(v).ok())
|
|
343
|
+
.ok_or_else(|| Error::new(ruby.exception_type_error(), "descriptor missing base_type"))?;
|
|
344
|
+
let get_bits =
|
|
345
|
+
|key: &str| -> Option<u32> { hash.get(key).and_then(|v| u32::try_convert(v).ok()) };
|
|
346
|
+
let dims: Vec<usize> = match hash.get("dims") {
|
|
347
|
+
Some(v) => match RArray::from_value(v) {
|
|
348
|
+
Some(a) => {
|
|
349
|
+
let mut dims = Vec::with_capacity(a.len());
|
|
350
|
+
for i in 0..a.len() {
|
|
351
|
+
let d: usize = a.entry(i as isize)?;
|
|
352
|
+
dims.push(d);
|
|
353
|
+
}
|
|
354
|
+
dims
|
|
355
|
+
}
|
|
356
|
+
None => Vec::new(),
|
|
357
|
+
},
|
|
358
|
+
None => Vec::new(),
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
let leaf = match base.as_str() {
|
|
362
|
+
"uint" => Schema::UInt(get_bits("bits").unwrap_or(256)),
|
|
363
|
+
"int" => Schema::Int(get_bits("bits").unwrap_or(256)),
|
|
364
|
+
"bool" => Schema::Bool,
|
|
365
|
+
"address" => Schema::Address,
|
|
366
|
+
"hash" => Schema::Hash(get_bits("bits").unwrap_or(0)),
|
|
367
|
+
"string" => Schema::Str,
|
|
368
|
+
"bytes" => match get_bits("bits") {
|
|
369
|
+
Some(n) if n > 0 => Schema::BytesN(n),
|
|
370
|
+
_ => Schema::Bytes,
|
|
371
|
+
},
|
|
372
|
+
"tuple" => {
|
|
373
|
+
let comps = hash
|
|
374
|
+
.get("comps")
|
|
375
|
+
.and_then(RArray::from_value)
|
|
376
|
+
.ok_or_else(|| {
|
|
377
|
+
Error::new(
|
|
378
|
+
ruby.exception_type_error(),
|
|
379
|
+
"tuple descriptor missing comps",
|
|
380
|
+
)
|
|
381
|
+
})?;
|
|
382
|
+
let names = hash.get("names").and_then(RArray::from_value);
|
|
383
|
+
let mut schemas = Vec::with_capacity(comps.len());
|
|
384
|
+
for i in 0..comps.len() {
|
|
385
|
+
let child: Value = comps.entry(i as isize)?;
|
|
386
|
+
let name: Option<String> = match names {
|
|
387
|
+
Some(n) => n.entry::<Option<String>>(i as isize)?,
|
|
388
|
+
None => None,
|
|
389
|
+
};
|
|
390
|
+
schemas.push((name, parse_descriptor(ruby, child, packed)?));
|
|
391
|
+
}
|
|
392
|
+
Schema::Tuple(schemas)
|
|
393
|
+
}
|
|
394
|
+
// real/ureal/fixed/ufixed: supported in packed encoding only, with
|
|
395
|
+
// the reference Packed::Encoder parameter mapping (byte size from
|
|
396
|
+
// the high part, scaling from the low part). The standard encoder
|
|
397
|
+
// rejects them explicitly, no silent approximation.
|
|
398
|
+
"ufixed" | "ureal" if packed => Schema::Fixed {
|
|
399
|
+
signed: false,
|
|
400
|
+
byte_size: (get_bits("bits").unwrap_or(0) / 8) as usize,
|
|
401
|
+
decimals: get_bits("decimals").unwrap_or(0),
|
|
402
|
+
},
|
|
403
|
+
"fixed" | "real" if packed => Schema::Fixed {
|
|
404
|
+
signed: true,
|
|
405
|
+
byte_size: (get_bits("bits").unwrap_or(0) / 8) as usize,
|
|
406
|
+
decimals: get_bits("decimals").unwrap_or(0),
|
|
407
|
+
},
|
|
408
|
+
other => {
|
|
409
|
+
return match abi_errors(ruby) {
|
|
410
|
+
Ok(e) => Err(Error::new(
|
|
411
|
+
e.unsupported_type,
|
|
412
|
+
format!("unsupported ABI base type for native encoding: {other}"),
|
|
413
|
+
)),
|
|
414
|
+
Err(err) => Err(err),
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
// Dimensions nest outside-in: the last dimension is the outermost
|
|
420
|
+
// array (`nested_sub` drops it), so wrap in declaration order.
|
|
421
|
+
let mut wrapped = leaf;
|
|
422
|
+
for dim in dims {
|
|
423
|
+
wrapped = Schema::Array(Box::new(wrapped), dim);
|
|
424
|
+
}
|
|
425
|
+
Ok(wrapped)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ---------------------------------------------------------------------------
|
|
429
|
+
// shared helpers
|
|
430
|
+
// ---------------------------------------------------------------------------
|
|
431
|
+
|
|
432
|
+
fn ceil32(n: usize) -> usize {
|
|
433
|
+
n.div_ceil(32) * 32
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
fn ceil32_u128(n: u128) -> u128 {
|
|
437
|
+
n.div_ceil(32) * 32
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/// Large decoded strings become shared substrings (`String#[]` semantics),
|
|
441
|
+
/// avoiding a full copy; the parent buffer stays alive via the reference.
|
|
442
|
+
fn shared_or_copy(ruby: &Ruby, data: &[u8], len: usize) -> Result<Value, Fail> {
|
|
443
|
+
if len > SHARED_SLICE_THRESHOLD {
|
|
444
|
+
let v: Value = ruby
|
|
445
|
+
.str_from_slice(&data[..len])
|
|
446
|
+
.funcall("byteslice", (0, len))
|
|
447
|
+
.map_err(Fail::Native)?;
|
|
448
|
+
Ok(v)
|
|
449
|
+
} else {
|
|
450
|
+
Ok(ruby.str_from_slice(&data[..len]).as_value())
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
fn be32(n: u128) -> [u8; 32] {
|
|
455
|
+
let mut word = [0u8; 32];
|
|
456
|
+
word[16..].copy_from_slice(&n.to_be_bytes());
|
|
457
|
+
word
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
fn fetch_class(ruby: &Ruby, path: &str) -> Result<magnus::RClass, Fail> {
|
|
461
|
+
// magnus const_get does not split "::" paths; resolve each segment.
|
|
462
|
+
let mut current = ruby.class_object().as_value();
|
|
463
|
+
for segment in path.split("::") {
|
|
464
|
+
current = current
|
|
465
|
+
.funcall("const_get", (segment,))
|
|
466
|
+
.map_err(Fail::Native)?;
|
|
467
|
+
}
|
|
468
|
+
Ok(magnus::RClass::from_value(current).ok_or_else(|| {
|
|
469
|
+
Error::new(
|
|
470
|
+
ruby.exception_runtime_error(),
|
|
471
|
+
format!("expected class {path}"),
|
|
472
|
+
)
|
|
473
|
+
})?)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/// Minimal big-endian bytes of a hex-digit string (no leading zeros).
|
|
477
|
+
fn be32_from_hex(digits: &str) -> [u8; 32] {
|
|
478
|
+
let mut word = [0u8; 32];
|
|
479
|
+
if digits.is_empty() {
|
|
480
|
+
return word;
|
|
481
|
+
}
|
|
482
|
+
let bytes_len = digits.len().div_ceil(2);
|
|
483
|
+
let padded: Cow<[u8]> = if digits.len() % 2 == 1 {
|
|
484
|
+
let mut p = Vec::with_capacity(digits.len() + 1);
|
|
485
|
+
p.push(b'0');
|
|
486
|
+
p.extend_from_slice(digits.as_bytes());
|
|
487
|
+
Cow::Owned(p)
|
|
488
|
+
} else {
|
|
489
|
+
Cow::Borrowed(digits.as_bytes())
|
|
490
|
+
};
|
|
491
|
+
for (i, pair) in padded.chunks_exact(2).enumerate() {
|
|
492
|
+
word[32 - bytes_len + i] = (nibble(pair[0]) << 4) | nibble(pair[1]);
|
|
493
|
+
}
|
|
494
|
+
word
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
fn nibble(b: u8) -> u8 {
|
|
498
|
+
match b {
|
|
499
|
+
b'0'..=b'9' => b - b'0',
|
|
500
|
+
b'a'..=b'f' => b - b'a' + 10,
|
|
501
|
+
b'A'..=b'F' => b - b'A' + 10,
|
|
502
|
+
_ => 0,
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/// Whether hex digits (no leading zeros; empty means zero) fit in `bits`
|
|
507
|
+
/// bits, i.e. the value is below `2**bits`.
|
|
508
|
+
fn hex_fits_bits(digits: &str, bits: usize) -> bool {
|
|
509
|
+
let digits = digits.trim_start_matches('0');
|
|
510
|
+
if digits.is_empty() {
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
let max_nibbles = bits.div_ceil(4);
|
|
514
|
+
if digits.len() < max_nibbles {
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
if digits.len() > max_nibbles {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
// Same nibble count: when `bits` fills whole nibbles every value of
|
|
521
|
+
// this length is below 2**bits; otherwise the leading nibble must be
|
|
522
|
+
// smaller than 2**leading.
|
|
523
|
+
let leading = bits % 4;
|
|
524
|
+
if leading == 0 {
|
|
525
|
+
return true;
|
|
526
|
+
}
|
|
527
|
+
nibble(digits.as_bytes()[0]) < (1u8 << leading)
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/// Hex digits (no leading zeros; empty means zero) to a decimal string.
|
|
531
|
+
fn hex_to_dec(digits: &str) -> String {
|
|
532
|
+
if digits.is_empty() {
|
|
533
|
+
return "0".to_owned();
|
|
534
|
+
}
|
|
535
|
+
let mut dec = vec![0u8]; // little-endian base-10 digits
|
|
536
|
+
for &n in digits.as_bytes() {
|
|
537
|
+
let mut carry = nibble(n) as u32;
|
|
538
|
+
for d in dec.iter_mut() {
|
|
539
|
+
let v = *d as u32 * 16 + carry;
|
|
540
|
+
*d = (v % 10) as u8;
|
|
541
|
+
carry = v / 10;
|
|
542
|
+
}
|
|
543
|
+
while carry > 0 {
|
|
544
|
+
dec.push((carry % 10) as u8);
|
|
545
|
+
carry /= 10;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
dec.iter().rev().map(|d| (b'0' + d) as char).collect()
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/// Decimal digit string to hex digits (no leading zeros; empty means zero).
|
|
552
|
+
fn dec_to_hex(digits: &str) -> String {
|
|
553
|
+
let mut cur = digits.to_owned();
|
|
554
|
+
let mut out = Vec::new();
|
|
555
|
+
const HEX: &[u8] = b"0123456789abcdef";
|
|
556
|
+
while !cur.is_empty() {
|
|
557
|
+
let mut rem = 0u32;
|
|
558
|
+
let mut next = String::with_capacity(cur.len());
|
|
559
|
+
let mut leading = true;
|
|
560
|
+
for d in cur.bytes() {
|
|
561
|
+
let v = rem * 10 + (d - b'0') as u32;
|
|
562
|
+
let q = (v / 16) as u8;
|
|
563
|
+
rem = v % 16;
|
|
564
|
+
let c = b'0' + q;
|
|
565
|
+
if leading && c == b'0' {
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
leading = false;
|
|
569
|
+
next.push(c as char);
|
|
570
|
+
}
|
|
571
|
+
if next.is_empty() && rem == 0 && !out.is_empty() {
|
|
572
|
+
// consumed entirely
|
|
573
|
+
}
|
|
574
|
+
out.push(HEX[rem as usize]);
|
|
575
|
+
cur = next;
|
|
576
|
+
let _ = leading;
|
|
577
|
+
if cur.is_empty() {
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
while out.len() > 1 && *out.last().unwrap() == b'0' {
|
|
582
|
+
out.pop();
|
|
583
|
+
}
|
|
584
|
+
if out.is_empty() {
|
|
585
|
+
return String::new();
|
|
586
|
+
}
|
|
587
|
+
out.iter().rev().map(|&b| b as char).collect()
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/// `Util#hex_to_bin` semantics: optional prefix, odd-length zero pad,
|
|
591
|
+
/// `TypeError` on non-hex digits.
|
|
592
|
+
fn hex_to_bin(ruby: &Ruby, bytes: &[u8]) -> Result<Vec<u8>, Fail> {
|
|
593
|
+
let body = if bytes.len() >= 2 && bytes[0] == b'0' && (bytes[1] == b'x' || bytes[1] == b'X') {
|
|
594
|
+
&bytes[2..]
|
|
595
|
+
} else {
|
|
596
|
+
bytes
|
|
597
|
+
};
|
|
598
|
+
if body.iter().any(|&b| !b.is_ascii_hexdigit()) {
|
|
599
|
+
return Err(type_error(ruby, "Non-hexadecimal digit found"));
|
|
600
|
+
}
|
|
601
|
+
let mut out = Vec::with_capacity(body.len().div_ceil(2));
|
|
602
|
+
if body.len() % 2 == 1 {
|
|
603
|
+
out.push((nibble(b'0') << 4) | nibble(body[0]));
|
|
604
|
+
}
|
|
605
|
+
let start = if body.len() % 2 == 1 { 1 } else { 0 };
|
|
606
|
+
let mut i = start;
|
|
607
|
+
while i < body.len() {
|
|
608
|
+
out.push((nibble(body[i]) << 4) | nibble(body[i + 1]));
|
|
609
|
+
i += 2;
|
|
610
|
+
}
|
|
611
|
+
Ok(out)
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/// Builds a Ruby Integer from hex digits, using fast paths below 128 bits.
|
|
615
|
+
fn integer_from_hex(ruby: &Ruby, digits: &str) -> Result<Value, Fail> {
|
|
616
|
+
if digits.is_empty() {
|
|
617
|
+
return Ok(ruby.integer_from_u64(0).as_value());
|
|
618
|
+
}
|
|
619
|
+
if digits.len() <= 32 {
|
|
620
|
+
let word = be32_from_hex(digits);
|
|
621
|
+
let mut n: u128 = 0;
|
|
622
|
+
for &b in &word[16..] {
|
|
623
|
+
n = (n << 8) | b as u128;
|
|
624
|
+
}
|
|
625
|
+
return Ok(ruby.integer_from_u128(n).as_value());
|
|
626
|
+
}
|
|
627
|
+
let hex = format!("0x{digits}");
|
|
628
|
+
let v: Value = ruby
|
|
629
|
+
.class_object()
|
|
630
|
+
.funcall("Integer", (hex,))
|
|
631
|
+
.map_err(Fail::Native)?;
|
|
632
|
+
Ok(v)
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
fn negate32(word: &mut [u8; 32]) {
|
|
636
|
+
let mut carry = 1u16;
|
|
637
|
+
for b in word.iter_mut().rev() {
|
|
638
|
+
let v = (!*b) as u16 + carry;
|
|
639
|
+
*b = v as u8;
|
|
640
|
+
carry = v >> 8;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ---------------------------------------------------------------------------
|
|
645
|
+
// encoding
|
|
646
|
+
// ---------------------------------------------------------------------------
|
|
647
|
+
|
|
648
|
+
fn encode_value(ruby: &Ruby, schema: &Schema, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
649
|
+
match schema {
|
|
650
|
+
Schema::Str | Schema::Bytes => encode_dynamic_bytes(ruby, value, out),
|
|
651
|
+
Schema::BytesN(n) => encode_fixed_bytes(ruby, *n as usize, value, out),
|
|
652
|
+
Schema::Address => encode_address(ruby, value, out),
|
|
653
|
+
Schema::Hash(bits) => encode_hash(ruby, *bits, value, out),
|
|
654
|
+
Schema::UInt(bits) => encode_int_like(ruby, *bits, value, out, false),
|
|
655
|
+
Schema::Int(bits) => encode_int_like(ruby, *bits, value, out, true),
|
|
656
|
+
Schema::Bool => {
|
|
657
|
+
if value.equal(ruby.qtrue()).unwrap_or(false) {
|
|
658
|
+
out.extend_from_slice(&[0u8; 31]);
|
|
659
|
+
out.push(1);
|
|
660
|
+
Ok(())
|
|
661
|
+
} else if value.equal(ruby.qfalse()).unwrap_or(false) {
|
|
662
|
+
out.extend_from_slice(&[0u8; 32]);
|
|
663
|
+
Ok(())
|
|
664
|
+
} else {
|
|
665
|
+
Err(encoding_error(
|
|
666
|
+
ruby,
|
|
667
|
+
format!("Argument is not bool: {}", display(ruby, value)),
|
|
668
|
+
))
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
Schema::Array(elem, length) => encode_array(ruby, elem, *length, value, out),
|
|
672
|
+
Schema::Tuple(comps) => encode_tuple(ruby, comps, value, out),
|
|
673
|
+
// unreachable: standard compile rejects the fixed family
|
|
674
|
+
Schema::Fixed { .. } => Err(encoding_error(ruby, "Unhandled type: fixed")),
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/// `handle_hex_string`: `0x` prefix or byte-doubled hex-looking content
|
|
679
|
+
/// means hex; everything else is raw bytes.
|
|
680
|
+
fn string_payload(ruby: &Ruby, value: Value, sub_type: usize) -> Result<Vec<u8>, Fail> {
|
|
681
|
+
let s = match RString::from_value(value) {
|
|
682
|
+
Some(s) => s,
|
|
683
|
+
None => {
|
|
684
|
+
return Err(encoding_error(
|
|
685
|
+
ruby,
|
|
686
|
+
format!("Expecting String: {}", display(ruby, value)),
|
|
687
|
+
))
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
let bytes = unsafe { s.as_slice() };
|
|
691
|
+
let hex_shaped = bytes.starts_with(b"0x")
|
|
692
|
+
|| bytes.starts_with(b"0X")
|
|
693
|
+
|| (sub_type > 0
|
|
694
|
+
&& bytes.len() == sub_type * 2
|
|
695
|
+
&& bytes.iter().all(|&b| b.is_ascii_hexdigit()));
|
|
696
|
+
if hex_shaped {
|
|
697
|
+
hex_to_bin(ruby, bytes)
|
|
698
|
+
} else {
|
|
699
|
+
Ok(bytes.to_vec())
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
fn encode_dynamic_bytes(ruby: &Ruby, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
704
|
+
if !exact_string(ruby, value) {
|
|
705
|
+
return Err(encoding_error(ruby, "Argument must be a String"));
|
|
706
|
+
}
|
|
707
|
+
let payload = string_payload(ruby, value, 0)?;
|
|
708
|
+
out.extend_from_slice(&be32(payload.len() as u128));
|
|
709
|
+
out.extend_from_slice(&payload);
|
|
710
|
+
out.extend(std::iter::repeat_n(
|
|
711
|
+
0u8,
|
|
712
|
+
ceil32(payload.len()) - payload.len(),
|
|
713
|
+
));
|
|
714
|
+
Ok(())
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
fn encode_fixed_bytes(ruby: &Ruby, n: usize, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
718
|
+
if !exact_string(ruby, value) {
|
|
719
|
+
return Err(encoding_error(
|
|
720
|
+
ruby,
|
|
721
|
+
format!("Expecting String: {}", display(ruby, value)),
|
|
722
|
+
));
|
|
723
|
+
}
|
|
724
|
+
let payload = string_payload(ruby, value, n)?;
|
|
725
|
+
if payload.len() > n {
|
|
726
|
+
return Err(value_out_of_bounds(
|
|
727
|
+
ruby,
|
|
728
|
+
String::from_utf8_lossy(&payload).into_owned(),
|
|
729
|
+
));
|
|
730
|
+
}
|
|
731
|
+
out.extend_from_slice(&payload);
|
|
732
|
+
out.extend(std::iter::repeat_n(0u8, 32 - payload.len()));
|
|
733
|
+
Ok(())
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/// `instance_of?(String)` semantics; subclasses are rejected.
|
|
737
|
+
fn exact_string(ruby: &Ruby, value: Value) -> bool {
|
|
738
|
+
match fetch_class(ruby, "String") {
|
|
739
|
+
Ok(cls) => value.class().equal(cls).unwrap_or(false),
|
|
740
|
+
Err(_) => false,
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
fn encode_address(ruby: &Ruby, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
745
|
+
let address_class = fetch_class(ruby, "Eth::Address")?;
|
|
746
|
+
if value.is_kind_of(address_class) {
|
|
747
|
+
let s: RString = value.funcall("to_s", ())?;
|
|
748
|
+
let text = String::from_utf8_lossy(unsafe { s.as_slice() }).into_owned();
|
|
749
|
+
let hex = text.strip_prefix("0x").unwrap_or(&text);
|
|
750
|
+
let bytes = hex_to_bin(ruby, hex.as_bytes())?;
|
|
751
|
+
if bytes.len() != 20 {
|
|
752
|
+
return Err(encoding_error(
|
|
753
|
+
ruby,
|
|
754
|
+
format!("Could not parse address: {text}"),
|
|
755
|
+
));
|
|
756
|
+
}
|
|
757
|
+
out.extend_from_slice(&[0u8; 12]);
|
|
758
|
+
out.extend_from_slice(&bytes);
|
|
759
|
+
return Ok(());
|
|
760
|
+
}
|
|
761
|
+
if let Some(int) = Integer::from_value(value) {
|
|
762
|
+
// zpad_int: negative or beyond uint256 raises ArgumentError
|
|
763
|
+
let word = uint_word_from_integer(ruby, &int, value)?;
|
|
764
|
+
out.extend_from_slice(&word);
|
|
765
|
+
return Ok(());
|
|
766
|
+
}
|
|
767
|
+
if let Some(s) = RString::from_value(value) {
|
|
768
|
+
let bytes = unsafe { s.as_slice() };
|
|
769
|
+
if bytes.len() == 20 {
|
|
770
|
+
out.extend_from_slice(&[0u8; 12]);
|
|
771
|
+
out.extend_from_slice(bytes);
|
|
772
|
+
return Ok(());
|
|
773
|
+
} else if bytes.len() == 40 {
|
|
774
|
+
let text = String::from_utf8_lossy(bytes.to_vec().as_slice()).into_owned();
|
|
775
|
+
let decoded = hex_to_bin(ruby, bytes)?;
|
|
776
|
+
let _ = text;
|
|
777
|
+
out.extend_from_slice(&[0u8; 12]);
|
|
778
|
+
out.extend_from_slice(&decoded);
|
|
779
|
+
return Ok(());
|
|
780
|
+
} else if bytes.len() == 42 && bytes.starts_with(b"0x") {
|
|
781
|
+
let decoded = hex_to_bin(ruby, bytes)?;
|
|
782
|
+
out.extend_from_slice(&[0u8; 12]);
|
|
783
|
+
out.extend_from_slice(&decoded);
|
|
784
|
+
return Ok(());
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
Err(encoding_error(
|
|
788
|
+
ruby,
|
|
789
|
+
format!("Could not parse address: {}", display(ruby, value)),
|
|
790
|
+
))
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
fn encode_hash(ruby: &Ruby, bits: u32, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
794
|
+
if bits == 0 || bits > 32 {
|
|
795
|
+
return Err(encoding_error(
|
|
796
|
+
ruby,
|
|
797
|
+
format!("Argument too long: {}", display(ruby, value)),
|
|
798
|
+
));
|
|
799
|
+
}
|
|
800
|
+
if let Some(int) = Integer::from_value(value) {
|
|
801
|
+
let word = uint_word_from_integer(ruby, &int, value)?;
|
|
802
|
+
out.extend_from_slice(&word);
|
|
803
|
+
return Ok(());
|
|
804
|
+
}
|
|
805
|
+
if let Some(s) = RString::from_value(value) {
|
|
806
|
+
let bytes = unsafe { s.as_slice() };
|
|
807
|
+
if bytes.len() == bits as usize {
|
|
808
|
+
out.extend(std::iter::repeat_n(0u8, 32 - bytes.len()));
|
|
809
|
+
out.extend_from_slice(bytes);
|
|
810
|
+
return Ok(());
|
|
811
|
+
} else if bytes.len() == bits as usize * 2 {
|
|
812
|
+
let decoded = hex_to_bin(ruby, bytes)?;
|
|
813
|
+
out.extend(std::iter::repeat_n(0u8, 32 - decoded.len()));
|
|
814
|
+
out.extend_from_slice(&decoded);
|
|
815
|
+
return Ok(());
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
Err(encoding_error(
|
|
819
|
+
ruby,
|
|
820
|
+
format!("Could not parse hash: {}", display(ruby, value)),
|
|
821
|
+
))
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
fn encode_int_like(
|
|
825
|
+
ruby: &Ruby,
|
|
826
|
+
bits: u32,
|
|
827
|
+
value: Value,
|
|
828
|
+
out: &mut Vec<u8>,
|
|
829
|
+
signed: bool,
|
|
830
|
+
) -> Result<(), Fail> {
|
|
831
|
+
// `coerce_number`: Numeric passes; matching strings become Integers;
|
|
832
|
+
// decimal-float strings become BigDecimal (unsupported here).
|
|
833
|
+
let parsed = coerce_numeric_string(ruby, value)?;
|
|
834
|
+
let (negative, hex_digits, original) = parsed;
|
|
835
|
+
let _ = original;
|
|
836
|
+
|
|
837
|
+
// 256-bit range first, with the "Number out of range: " prefix the
|
|
838
|
+
// reference uses for `Constant::INT_MAX/INT_MIN`/`UINT_MAX` bounds.
|
|
839
|
+
if signed {
|
|
840
|
+
if negative {
|
|
841
|
+
// value < -2**255 is out of range entirely
|
|
842
|
+
if !hex_fits_bits(&hex_digits, 255) && !is_exact_pow2(&hex_digits, 255) {
|
|
843
|
+
return Err(value_out_of_bounds(
|
|
844
|
+
ruby,
|
|
845
|
+
format!(
|
|
846
|
+
"Number out of range: {}",
|
|
847
|
+
canonical_number_message(ruby, negative, &hex_digits, value)
|
|
848
|
+
),
|
|
849
|
+
));
|
|
850
|
+
}
|
|
851
|
+
} else if !hex_fits_bits(&hex_digits, 255) {
|
|
852
|
+
return Err(value_out_of_bounds(
|
|
853
|
+
ruby,
|
|
854
|
+
format!(
|
|
855
|
+
"Number out of range: {}",
|
|
856
|
+
canonical_number_message(ruby, negative, &hex_digits, value)
|
|
857
|
+
),
|
|
858
|
+
));
|
|
859
|
+
}
|
|
860
|
+
} else {
|
|
861
|
+
if negative {
|
|
862
|
+
// `arg < UINT_MIN` uses the prefixed form in the reference
|
|
863
|
+
return Err(value_out_of_bounds(
|
|
864
|
+
ruby,
|
|
865
|
+
format!(
|
|
866
|
+
"Number out of range: {}",
|
|
867
|
+
canonical_number_message(ruby, true, &hex_digits, value)
|
|
868
|
+
),
|
|
869
|
+
));
|
|
870
|
+
}
|
|
871
|
+
if !hex_fits_bits(&hex_digits, 256) {
|
|
872
|
+
return Err(value_out_of_bounds(
|
|
873
|
+
ruby,
|
|
874
|
+
format!(
|
|
875
|
+
"Number out of range: {}",
|
|
876
|
+
canonical_number_message(ruby, false, &hex_digits, value)
|
|
877
|
+
),
|
|
878
|
+
));
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// sub-256-bit bound; the reference message is the bare coerced value
|
|
883
|
+
if signed {
|
|
884
|
+
let half = (bits - 1) as usize;
|
|
885
|
+
let fits = if negative {
|
|
886
|
+
hex_fits_bits(&hex_digits, half) || is_exact_pow2(&hex_digits, half)
|
|
887
|
+
} else {
|
|
888
|
+
hex_fits_bits(&hex_digits, half)
|
|
889
|
+
};
|
|
890
|
+
if !fits {
|
|
891
|
+
return Err(value_out_of_bounds(
|
|
892
|
+
ruby,
|
|
893
|
+
canonical_number_message(ruby, negative, &hex_digits, value),
|
|
894
|
+
));
|
|
895
|
+
}
|
|
896
|
+
let mut word = be32_from_hex(&hex_digits);
|
|
897
|
+
if negative {
|
|
898
|
+
negate32(&mut word);
|
|
899
|
+
}
|
|
900
|
+
out.extend_from_slice(&word);
|
|
901
|
+
return Ok(());
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
if bits < 256 && !hex_fits_bits(&hex_digits, bits as usize) {
|
|
905
|
+
return Err(value_out_of_bounds(
|
|
906
|
+
ruby,
|
|
907
|
+
canonical_number_message(ruby, false, &hex_digits, value),
|
|
908
|
+
));
|
|
909
|
+
}
|
|
910
|
+
let word = be32_from_hex(&hex_digits);
|
|
911
|
+
out.extend_from_slice(&word);
|
|
912
|
+
Ok(())
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/// `Number out of range: #{arg}` uses the coerced Integer's decimal form.
|
|
916
|
+
fn canonical_number_message(
|
|
917
|
+
_ruby: &Ruby,
|
|
918
|
+
negative: bool,
|
|
919
|
+
hex_digits: &str,
|
|
920
|
+
original: Value,
|
|
921
|
+
) -> String {
|
|
922
|
+
// Original Ruby Integers render themselves (including the sign);
|
|
923
|
+
// string inputs render the coerced value's canonical decimal.
|
|
924
|
+
if Integer::from_value(original).is_some() {
|
|
925
|
+
return display(_ruby, original);
|
|
926
|
+
}
|
|
927
|
+
let mut dec = hex_to_dec(if hex_digits.is_empty() {
|
|
928
|
+
"0"
|
|
929
|
+
} else {
|
|
930
|
+
hex_digits
|
|
931
|
+
});
|
|
932
|
+
if negative && dec != "0" {
|
|
933
|
+
dec.insert(0, '-');
|
|
934
|
+
}
|
|
935
|
+
dec
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
type ParsedNumber = (bool, String, Value);
|
|
939
|
+
|
|
940
|
+
/// Mirrors `Encoder#coerce_number` for the cases native encoding supports:
|
|
941
|
+
/// Numeric values and integer-shaped strings ("0x"-prefixed hex or plain
|
|
942
|
+
/// decimal). Decimal-float strings and other objects are unsupported.
|
|
943
|
+
fn coerce_numeric_string(ruby: &Ruby, value: Value) -> Result<ParsedNumber, Fail> {
|
|
944
|
+
if let Some(int) = Integer::from_value(value) {
|
|
945
|
+
// sign + minimal hex digits
|
|
946
|
+
if let Ok(i) = int.to_i64() {
|
|
947
|
+
let negative = i < 0;
|
|
948
|
+
let digits = dec_to_hex(&i.unsigned_abs().to_string());
|
|
949
|
+
return Ok((negative, digits, value));
|
|
950
|
+
}
|
|
951
|
+
let negative: bool = value.funcall("<", (0,)).map_err(Fail::Native)?;
|
|
952
|
+
if let Ok(n) = int.to_u128() {
|
|
953
|
+
let digits = format!("{n:x}");
|
|
954
|
+
return Ok((negative, digits, value));
|
|
955
|
+
}
|
|
956
|
+
if let Ok(i) = int.to_i128() {
|
|
957
|
+
let digits = format!("{:x}", i.unsigned_abs());
|
|
958
|
+
return Ok((negative, digits, value));
|
|
959
|
+
}
|
|
960
|
+
let abs: Value = value.funcall("abs", ()).map_err(Fail::Native)?;
|
|
961
|
+
let hex: RString = abs.funcall("to_s", (16,)).map_err(Fail::Native)?;
|
|
962
|
+
let digits = String::from_utf8_lossy(unsafe { hex.as_slice() })
|
|
963
|
+
.trim_start_matches('0')
|
|
964
|
+
.to_owned();
|
|
965
|
+
return Ok((negative, digits, value));
|
|
966
|
+
}
|
|
967
|
+
if Float::from_value(value).is_some() {
|
|
968
|
+
// The reference accepts Floats (truncation); handled by caller only
|
|
969
|
+
// when the value is finite and fits; otherwise Ruby handles it.
|
|
970
|
+
return Err(Fail::Unsupported);
|
|
971
|
+
}
|
|
972
|
+
if let Some(s) = RString::from_value(value) {
|
|
973
|
+
let text = String::from_utf8_lossy(unsafe { s.as_slice() }).into_owned();
|
|
974
|
+
let (negative, body) = match text.strip_prefix('-') {
|
|
975
|
+
Some(rest) => (true, rest),
|
|
976
|
+
None => (false, text.as_str()),
|
|
977
|
+
};
|
|
978
|
+
let digits: String = if let Some(hex) = body.strip_prefix("0x") {
|
|
979
|
+
if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
|
980
|
+
return Err(Fail::Unsupported);
|
|
981
|
+
}
|
|
982
|
+
hex.trim_start_matches('0').to_owned()
|
|
983
|
+
} else {
|
|
984
|
+
if body.is_empty() || !body.bytes().all(|b| b.is_ascii_digit()) {
|
|
985
|
+
// decimal-float strings go to BigDecimal in the reference
|
|
986
|
+
return Err(Fail::Unsupported);
|
|
987
|
+
}
|
|
988
|
+
dec_to_hex(body)
|
|
989
|
+
};
|
|
990
|
+
let value_int = integer_from_hex(ruby, &digits)?;
|
|
991
|
+
return Ok((negative, digits, value_int));
|
|
992
|
+
}
|
|
993
|
+
Err(Fail::Unsupported)
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/// `Util#zpad_int` semantics including its out-of-range ArgumentError.
|
|
997
|
+
fn uint_word_from_integer(ruby: &Ruby, int: &Integer, value: Value) -> Result<[u8; 32], Fail> {
|
|
998
|
+
if let Ok(i) = int.to_i64() {
|
|
999
|
+
if i < 0 {
|
|
1000
|
+
return Err(Fail::Native(Error::new(
|
|
1001
|
+
ruby.exception_arg_error(),
|
|
1002
|
+
format!("Integer invalid or out of range: {}", display(ruby, value)),
|
|
1003
|
+
)));
|
|
1004
|
+
}
|
|
1005
|
+
let mut word = [0u8; 32];
|
|
1006
|
+
word[24..].copy_from_slice(&i.unsigned_abs().to_be_bytes());
|
|
1007
|
+
return Ok(word);
|
|
1008
|
+
}
|
|
1009
|
+
let negative: bool = value.funcall("<", (0,)).map_err(Fail::Native)?;
|
|
1010
|
+
if negative {
|
|
1011
|
+
return Err(Fail::Native(Error::new(
|
|
1012
|
+
ruby.exception_arg_error(),
|
|
1013
|
+
format!("Integer invalid or out of range: {}", display(ruby, value)),
|
|
1014
|
+
)));
|
|
1015
|
+
}
|
|
1016
|
+
if let Ok(n) = int.to_u128() {
|
|
1017
|
+
let mut word = [0u8; 32];
|
|
1018
|
+
word[16..].copy_from_slice(&n.to_be_bytes());
|
|
1019
|
+
return Ok(word);
|
|
1020
|
+
}
|
|
1021
|
+
let hex: RString = value.funcall("to_s", (16,)).map_err(Fail::Native)?;
|
|
1022
|
+
let digits = String::from_utf8_lossy(unsafe { hex.as_slice() })
|
|
1023
|
+
.trim_start_matches('0')
|
|
1024
|
+
.to_owned();
|
|
1025
|
+
if digits.len() > 64 {
|
|
1026
|
+
return Err(Fail::Native(Error::new(
|
|
1027
|
+
ruby.exception_arg_error(),
|
|
1028
|
+
format!("Integer invalid or out of range: {}", display(ruby, value)),
|
|
1029
|
+
)));
|
|
1030
|
+
}
|
|
1031
|
+
Ok(be32_from_hex(&digits))
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
fn encode_array(
|
|
1035
|
+
ruby: &Ruby,
|
|
1036
|
+
elem: &Schema,
|
|
1037
|
+
length: usize,
|
|
1038
|
+
value: Value,
|
|
1039
|
+
out: &mut Vec<u8>,
|
|
1040
|
+
) -> Result<(), Fail> {
|
|
1041
|
+
let array_class = fetch_class(ruby, "Array")?;
|
|
1042
|
+
if !value.is_kind_of(array_class) {
|
|
1043
|
+
return Err(encoding_error(ruby, "Expecting Array value"));
|
|
1044
|
+
}
|
|
1045
|
+
let values = match RArray::from_value(value) {
|
|
1046
|
+
Some(a) => a,
|
|
1047
|
+
None => return Err(encoding_error(ruby, "Expecting Array value")),
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
if length != 0 && values.len() != length {
|
|
1051
|
+
return Err(encoding_error(
|
|
1052
|
+
ruby,
|
|
1053
|
+
format!("Expecting {length} elements: {} provided", values.len()),
|
|
1054
|
+
));
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
if length == 0 {
|
|
1058
|
+
out.extend_from_slice(&be32(values.len() as u128));
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
if elem.dynamic() {
|
|
1062
|
+
let mut heads = Vec::new();
|
|
1063
|
+
let mut tails = Vec::new();
|
|
1064
|
+
let mut offset = values.len() * 32;
|
|
1065
|
+
for i in 0..values.len() {
|
|
1066
|
+
let item: Value = values.entry(i as isize)?;
|
|
1067
|
+
heads.extend_from_slice(&be32(offset as u128));
|
|
1068
|
+
let before = tails.len();
|
|
1069
|
+
encode_value(ruby, elem, item, &mut tails)?;
|
|
1070
|
+
offset += tails.len() - before;
|
|
1071
|
+
}
|
|
1072
|
+
out.extend_from_slice(&heads);
|
|
1073
|
+
out.extend_from_slice(&tails);
|
|
1074
|
+
} else {
|
|
1075
|
+
for i in 0..values.len() {
|
|
1076
|
+
let item: Value = values.entry(i as isize)?;
|
|
1077
|
+
encode_value(ruby, elem, item, out)?;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
Ok(())
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
fn encode_tuple(
|
|
1084
|
+
ruby: &Ruby,
|
|
1085
|
+
comps: &[(Option<String>, Schema)],
|
|
1086
|
+
value: Value,
|
|
1087
|
+
out: &mut Vec<u8>,
|
|
1088
|
+
) -> Result<(), Fail> {
|
|
1089
|
+
let hash_class = fetch_class(ruby, "Hash")?;
|
|
1090
|
+
let array_class = fetch_class(ruby, "Array")?;
|
|
1091
|
+
let is_hash = value.is_kind_of(hash_class);
|
|
1092
|
+
let is_array = value.is_kind_of(array_class);
|
|
1093
|
+
if !is_hash && !is_array {
|
|
1094
|
+
return Err(encoding_error(
|
|
1095
|
+
ruby,
|
|
1096
|
+
format!("Expecting Hash or Array: {}", display(ruby, value)),
|
|
1097
|
+
));
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// Hash keys are normalized with `transform_keys(&:to_s)` in the
|
|
1101
|
+
// reference; a nil key stays nil (`Hash#[]`/`fetch(nil)` semantics).
|
|
1102
|
+
let entries: Option<Vec<(Option<String>, Value)>> = if is_hash {
|
|
1103
|
+
let hash = RHash::from_value(value)
|
|
1104
|
+
.ok_or_else(|| encoding_error(ruby, "Expecting Hash or Array"))?;
|
|
1105
|
+
let mut collected = Vec::with_capacity(hash.len());
|
|
1106
|
+
hash.foreach(|k: Value, v: Value| -> Result<ForEach, Error> {
|
|
1107
|
+
if k.is_nil() {
|
|
1108
|
+
collected.push((None, v));
|
|
1109
|
+
} else {
|
|
1110
|
+
let key: RString = k.funcall("to_s", ())?;
|
|
1111
|
+
collected.push((Some(key.to_string()?), v));
|
|
1112
|
+
}
|
|
1113
|
+
Ok(ForEach::Continue)
|
|
1114
|
+
})?;
|
|
1115
|
+
Some(collected)
|
|
1116
|
+
} else {
|
|
1117
|
+
None
|
|
1118
|
+
};
|
|
1119
|
+
|
|
1120
|
+
let value_len = match &entries {
|
|
1121
|
+
Some(entries) => entries.len(),
|
|
1122
|
+
None => RArray::from_value(value)
|
|
1123
|
+
.map(|a| a.len())
|
|
1124
|
+
.unwrap_or_default(),
|
|
1125
|
+
};
|
|
1126
|
+
if comps.len() != value_len {
|
|
1127
|
+
return Err(encoding_error(
|
|
1128
|
+
ruby,
|
|
1129
|
+
format!(
|
|
1130
|
+
"Expecting {} elements: {}",
|
|
1131
|
+
comps.len(),
|
|
1132
|
+
display(ruby, value)
|
|
1133
|
+
),
|
|
1134
|
+
));
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
let static_size: usize = comps
|
|
1138
|
+
.iter()
|
|
1139
|
+
.map(|(_, s)| {
|
|
1140
|
+
if s.dynamic() {
|
|
1141
|
+
32
|
|
1142
|
+
} else {
|
|
1143
|
+
ceil32(s.size().unwrap_or(0))
|
|
1144
|
+
}
|
|
1145
|
+
})
|
|
1146
|
+
.sum();
|
|
1147
|
+
|
|
1148
|
+
let mut heads = Vec::new();
|
|
1149
|
+
let mut tails = Vec::new();
|
|
1150
|
+
let mut dynamic_offset = static_size;
|
|
1151
|
+
for (i, (name, comp)) in comps.iter().enumerate() {
|
|
1152
|
+
let item: Value = if let Some(entries) = &entries {
|
|
1153
|
+
let found = entries
|
|
1154
|
+
.iter()
|
|
1155
|
+
.find(|(k, _)| k.as_deref() == name.as_deref())
|
|
1156
|
+
.map(|(_, v)| *v);
|
|
1157
|
+
if comp.dynamic() {
|
|
1158
|
+
// `arg[name]` — a missing key encodes nil and fails deeper
|
|
1159
|
+
found.unwrap_or_else(|| ruby.qnil().as_value())
|
|
1160
|
+
} else {
|
|
1161
|
+
// `arg.fetch(name)` — a missing key raises KeyError
|
|
1162
|
+
found.ok_or_else(|| {
|
|
1163
|
+
Fail::Native(Error::new(
|
|
1164
|
+
ruby.exception_key_error(),
|
|
1165
|
+
format!("key not found: {}", name.as_deref().unwrap_or("nil")),
|
|
1166
|
+
))
|
|
1167
|
+
})?
|
|
1168
|
+
}
|
|
1169
|
+
} else {
|
|
1170
|
+
let ary = match RArray::from_value(value) {
|
|
1171
|
+
Some(a) => a,
|
|
1172
|
+
None => return Err(encoding_error(ruby, "Expecting Hash or Array")),
|
|
1173
|
+
};
|
|
1174
|
+
ary.entry(i as isize)?
|
|
1175
|
+
};
|
|
1176
|
+
|
|
1177
|
+
if comp.dynamic() {
|
|
1178
|
+
heads.extend_from_slice(&be32(dynamic_offset as u128));
|
|
1179
|
+
let mut encoded = Vec::new();
|
|
1180
|
+
encode_value(ruby, comp, item, &mut encoded)?;
|
|
1181
|
+
dynamic_offset += encoded.len();
|
|
1182
|
+
tails.extend_from_slice(&encoded);
|
|
1183
|
+
} else {
|
|
1184
|
+
encode_value(ruby, comp, item, &mut heads)?;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
out.extend_from_slice(&heads);
|
|
1188
|
+
out.extend_from_slice(&tails);
|
|
1189
|
+
Ok(())
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// ---------------------------------------------------------------------------
|
|
1193
|
+
// packed (solidity_packed) encoding
|
|
1194
|
+
// ---------------------------------------------------------------------------
|
|
1195
|
+
|
|
1196
|
+
/// Compiles a descriptor list for packed encoding; fixed-point family is
|
|
1197
|
+
/// accepted here (standard compile keeps rejecting it).
|
|
1198
|
+
pub fn packed_compile_entry(ruby: &Ruby, descriptors: Value) -> Result<AbiSchemaWrap, Error> {
|
|
1199
|
+
let list = match RArray::from_value(descriptors) {
|
|
1200
|
+
Some(l) => l,
|
|
1201
|
+
None => {
|
|
1202
|
+
return Err(Error::new(
|
|
1203
|
+
ruby.exception_type_error(),
|
|
1204
|
+
"descriptor list must be an Array",
|
|
1205
|
+
))
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
let mut schemas = Vec::with_capacity(list.len());
|
|
1209
|
+
for i in 0..list.len() {
|
|
1210
|
+
let node: Value = list.entry(i as isize)?;
|
|
1211
|
+
schemas.push(parse_descriptor(ruby, node, true)?);
|
|
1212
|
+
}
|
|
1213
|
+
Ok(AbiSchemaWrap { schemas })
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/// Packed encode, mirroring `Abi.solidity_packed`: no length wrapping, no
|
|
1217
|
+
/// head/tail, arrays concatenate element encodings, integers left-pad
|
|
1218
|
+
/// without truncation, and `Numeric` values are used as-is (no string
|
|
1219
|
+
/// coercion).
|
|
1220
|
+
pub fn packed_encode_entry(
|
|
1221
|
+
ruby: &Ruby,
|
|
1222
|
+
schema: &AbiSchemaWrap,
|
|
1223
|
+
values: Value,
|
|
1224
|
+
) -> Result<RString, Error> {
|
|
1225
|
+
match packed_encode_inner(ruby, &schema.schemas, values) {
|
|
1226
|
+
Ok(out) => Ok(out),
|
|
1227
|
+
Err(fail) => Err(fail.into_error(ruby)),
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
fn packed_encode_inner(ruby: &Ruby, schemas: &[Schema], values: Value) -> Result<RString, Fail> {
|
|
1232
|
+
let args = match RArray::from_value(values) {
|
|
1233
|
+
Some(a) => a,
|
|
1234
|
+
None => {
|
|
1235
|
+
return Err(Fail::Native(Error::new(
|
|
1236
|
+
ruby.exception_arg_error(),
|
|
1237
|
+
"Types and values must be the same length",
|
|
1238
|
+
)));
|
|
1239
|
+
}
|
|
1240
|
+
};
|
|
1241
|
+
if args.len() != schemas.len() {
|
|
1242
|
+
// solidity_packed raises ArgumentError (not EncodingError) here
|
|
1243
|
+
return Err(Fail::Native(Error::new(
|
|
1244
|
+
ruby.exception_arg_error(),
|
|
1245
|
+
"Types and values must be the same length",
|
|
1246
|
+
)));
|
|
1247
|
+
}
|
|
1248
|
+
let mut out = Vec::new();
|
|
1249
|
+
for (i, schema) in schemas.iter().enumerate() {
|
|
1250
|
+
let value: Value = args.entry(i as isize)?;
|
|
1251
|
+
packed_encode_value(ruby, schema, value, &mut out)?;
|
|
1252
|
+
}
|
|
1253
|
+
Ok(ruby.str_from_slice(&out))
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
fn packed_encode_value(
|
|
1257
|
+
ruby: &Ruby,
|
|
1258
|
+
schema: &Schema,
|
|
1259
|
+
value: Value,
|
|
1260
|
+
out: &mut Vec<u8>,
|
|
1261
|
+
) -> Result<(), Fail> {
|
|
1262
|
+
match schema {
|
|
1263
|
+
Schema::UInt(bits) => packed_uint(ruby, *bits, value, out),
|
|
1264
|
+
Schema::Int(bits) => packed_int(ruby, *bits, value, out),
|
|
1265
|
+
Schema::Bool => {
|
|
1266
|
+
if value.equal(ruby.qtrue()).unwrap_or(false) {
|
|
1267
|
+
out.push(1);
|
|
1268
|
+
Ok(())
|
|
1269
|
+
} else if value.equal(ruby.qfalse()).unwrap_or(false) {
|
|
1270
|
+
out.push(0);
|
|
1271
|
+
Ok(())
|
|
1272
|
+
} else {
|
|
1273
|
+
Err(encoding_error(
|
|
1274
|
+
ruby,
|
|
1275
|
+
format!("Argument is not bool: {}", display(ruby, value)),
|
|
1276
|
+
))
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
Schema::Address => packed_address(ruby, value, out),
|
|
1280
|
+
Schema::Hash(bits) => {
|
|
1281
|
+
if *bits == 0 || *bits > 32 {
|
|
1282
|
+
return Err(encoding_error(
|
|
1283
|
+
ruby,
|
|
1284
|
+
format!("Argument too long: {}", display(ruby, value)),
|
|
1285
|
+
));
|
|
1286
|
+
}
|
|
1287
|
+
let s = match RString::from_value(value) {
|
|
1288
|
+
Some(s) => s,
|
|
1289
|
+
None => {
|
|
1290
|
+
return Err(encoding_error(
|
|
1291
|
+
ruby,
|
|
1292
|
+
format!("Expecting String: {}", display(ruby, value)),
|
|
1293
|
+
))
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
// packed handle_hex_string uses `len === val.size / 2`
|
|
1297
|
+
let bytes = unsafe { s.as_slice() };
|
|
1298
|
+
let hex_shaped = bytes.starts_with(b"0x")
|
|
1299
|
+
|| bytes.starts_with(b"0X")
|
|
1300
|
+
|| (bytes.len() / 2 == (*bits / 8) as usize
|
|
1301
|
+
&& bytes.iter().all(|&b| b.is_ascii_hexdigit()));
|
|
1302
|
+
if hex_shaped {
|
|
1303
|
+
out.extend_from_slice(&hex_to_bin(ruby, bytes)?);
|
|
1304
|
+
} else {
|
|
1305
|
+
out.extend_from_slice(bytes);
|
|
1306
|
+
}
|
|
1307
|
+
Ok(())
|
|
1308
|
+
}
|
|
1309
|
+
Schema::Str | Schema::Bytes => {
|
|
1310
|
+
// `string(value)` checks is_a?(String) (subclasses pass)
|
|
1311
|
+
let array_class = fetch_class(ruby, "String")?;
|
|
1312
|
+
if !value.is_kind_of(array_class) {
|
|
1313
|
+
return Err(Fail::Native(Error::new(
|
|
1314
|
+
ruby.exception_arg_error(),
|
|
1315
|
+
"Value must be a string",
|
|
1316
|
+
)));
|
|
1317
|
+
}
|
|
1318
|
+
let s = RString::from_value(value).ok_or(Fail::Unsupported)?;
|
|
1319
|
+
out.extend_from_slice(unsafe { s.as_slice() });
|
|
1320
|
+
Ok(())
|
|
1321
|
+
}
|
|
1322
|
+
Schema::BytesN(n) => {
|
|
1323
|
+
if !exact_string(ruby, value) {
|
|
1324
|
+
return Err(encoding_error(
|
|
1325
|
+
ruby,
|
|
1326
|
+
format!("Expecting String: {}", display(ruby, value)),
|
|
1327
|
+
));
|
|
1328
|
+
}
|
|
1329
|
+
let s = RString::from_value(value).ok_or(Fail::Unsupported)?;
|
|
1330
|
+
let raw = unsafe { s.as_slice() }.to_vec();
|
|
1331
|
+
let hex_shaped = raw.starts_with(b"0x")
|
|
1332
|
+
|| raw.starts_with(b"0X")
|
|
1333
|
+
|| (raw.len() / 2 == *n as usize && raw.iter().all(|&b| b.is_ascii_hexdigit()));
|
|
1334
|
+
let bytes = if hex_shaped {
|
|
1335
|
+
hex_to_bin(ruby, &raw)?
|
|
1336
|
+
} else {
|
|
1337
|
+
raw
|
|
1338
|
+
};
|
|
1339
|
+
if bytes.len() != *n as usize {
|
|
1340
|
+
return Err(Fail::Native(Error::new(
|
|
1341
|
+
ruby.exception_arg_error(),
|
|
1342
|
+
format!("Value must be a string of length {n}"),
|
|
1343
|
+
)));
|
|
1344
|
+
}
|
|
1345
|
+
out.extend_from_slice(&bytes);
|
|
1346
|
+
Ok(())
|
|
1347
|
+
}
|
|
1348
|
+
Schema::Fixed {
|
|
1349
|
+
signed,
|
|
1350
|
+
byte_size,
|
|
1351
|
+
decimals,
|
|
1352
|
+
} => packed_fixed(ruby, *signed, *byte_size, *decimals, value, out),
|
|
1353
|
+
Schema::Array(elem, 0) => {
|
|
1354
|
+
let array_class = fetch_class(ruby, "Array")?;
|
|
1355
|
+
if !value.is_kind_of(array_class) {
|
|
1356
|
+
// the reference simply calls values.map; unsupported shapes
|
|
1357
|
+
// fall back so the reference raises its own errors
|
|
1358
|
+
return Err(Fail::Unsupported);
|
|
1359
|
+
}
|
|
1360
|
+
let ary = match RArray::from_value(value) {
|
|
1361
|
+
Some(a) => a,
|
|
1362
|
+
None => return Err(Fail::Unsupported),
|
|
1363
|
+
};
|
|
1364
|
+
for i in 0..ary.len() {
|
|
1365
|
+
let item: Value = ary.entry(i as isize)?;
|
|
1366
|
+
packed_encode_value(ruby, elem, item, out)?;
|
|
1367
|
+
}
|
|
1368
|
+
Ok(())
|
|
1369
|
+
}
|
|
1370
|
+
Schema::Array(elem, length) => {
|
|
1371
|
+
let array_class = fetch_class(ruby, "Array")?;
|
|
1372
|
+
if !value.is_kind_of(array_class) {
|
|
1373
|
+
return Err(Fail::Unsupported);
|
|
1374
|
+
}
|
|
1375
|
+
let ary = match RArray::from_value(value) {
|
|
1376
|
+
Some(a) => a,
|
|
1377
|
+
None => return Err(Fail::Unsupported),
|
|
1378
|
+
};
|
|
1379
|
+
if ary.len() != *length {
|
|
1380
|
+
return Err(Fail::Native(Error::new(
|
|
1381
|
+
ruby.exception_arg_error(),
|
|
1382
|
+
"Array size does not match",
|
|
1383
|
+
)));
|
|
1384
|
+
}
|
|
1385
|
+
for i in 0..ary.len() {
|
|
1386
|
+
let item: Value = ary.entry(i as isize)?;
|
|
1387
|
+
packed_encode_value(ruby, elem, item, out)?;
|
|
1388
|
+
}
|
|
1389
|
+
Ok(())
|
|
1390
|
+
}
|
|
1391
|
+
Schema::Tuple(comps) => {
|
|
1392
|
+
let array_class = fetch_class(ruby, "Array")?;
|
|
1393
|
+
if !value.is_kind_of(array_class) {
|
|
1394
|
+
return Err(Fail::Unsupported);
|
|
1395
|
+
}
|
|
1396
|
+
let ary = match RArray::from_value(value) {
|
|
1397
|
+
Some(a) => a,
|
|
1398
|
+
None => return Err(Fail::Unsupported),
|
|
1399
|
+
};
|
|
1400
|
+
if ary.len() != comps.len() {
|
|
1401
|
+
return Err(encoding_error(
|
|
1402
|
+
ruby,
|
|
1403
|
+
"Types and values must be the same length",
|
|
1404
|
+
));
|
|
1405
|
+
}
|
|
1406
|
+
for (i, (_, comp)) in comps.iter().enumerate() {
|
|
1407
|
+
let item: Value = ary.entry(i as isize)?;
|
|
1408
|
+
packed_encode_value(ruby, comp, item, out)?;
|
|
1409
|
+
}
|
|
1410
|
+
Ok(())
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
/// Packed `uint(N, value)`: 256-bit bounds then left-pad to N bytes with
|
|
1416
|
+
/// `Util#lpad` semantics (no truncation when longer).
|
|
1417
|
+
fn packed_uint(ruby: &Ruby, bits: u32, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
1418
|
+
let parsed = packed_numeric(ruby, value)?;
|
|
1419
|
+
let (negative, hex_digits) = match parsed {
|
|
1420
|
+
None => return Err(Fail::Unsupported),
|
|
1421
|
+
Some(p) => p,
|
|
1422
|
+
};
|
|
1423
|
+
if negative {
|
|
1424
|
+
return Err(value_out_of_bounds(
|
|
1425
|
+
ruby,
|
|
1426
|
+
format!(
|
|
1427
|
+
"Number out of range: {}",
|
|
1428
|
+
canonical_number_message(ruby, true, &hex_digits, value)
|
|
1429
|
+
),
|
|
1430
|
+
));
|
|
1431
|
+
}
|
|
1432
|
+
if !hex_fits_bits(&hex_digits, 256) {
|
|
1433
|
+
return Err(value_out_of_bounds(
|
|
1434
|
+
ruby,
|
|
1435
|
+
format!(
|
|
1436
|
+
"Number out of range: {}",
|
|
1437
|
+
canonical_number_message(ruby, false, &hex_digits, value)
|
|
1438
|
+
),
|
|
1439
|
+
));
|
|
1440
|
+
}
|
|
1441
|
+
let byte_len = (bits / 8) as usize;
|
|
1442
|
+
let word = be32_from_hex(&hex_digits);
|
|
1443
|
+
let minimal_len = 32 - word.iter().take_while(|&&b| b == 0).count();
|
|
1444
|
+
// `lpad` keeps longer values untouched
|
|
1445
|
+
if minimal_len > byte_len {
|
|
1446
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1447
|
+
} else {
|
|
1448
|
+
out.extend(std::iter::repeat_n(0u8, byte_len - minimal_len));
|
|
1449
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1450
|
+
}
|
|
1451
|
+
Ok(())
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/// Packed `int(N, value)`: INT_MAX/INT_MIN bounds then two's complement
|
|
1455
|
+
/// within N bytes (no truncation when longer).
|
|
1456
|
+
fn packed_int(ruby: &Ruby, bits: u32, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
1457
|
+
let parsed = packed_numeric(ruby, value)?;
|
|
1458
|
+
let (negative, hex_digits) = match parsed {
|
|
1459
|
+
None => return Err(Fail::Unsupported),
|
|
1460
|
+
Some(p) => p,
|
|
1461
|
+
};
|
|
1462
|
+
if negative {
|
|
1463
|
+
// magnitude <= 2**255 required by the INT_MAX/INT_MIN bound
|
|
1464
|
+
if !hex_fits_bits(&hex_digits, 255) && !is_exact_pow2(&hex_digits, 255) {
|
|
1465
|
+
return Err(value_out_of_bounds(
|
|
1466
|
+
ruby,
|
|
1467
|
+
format!(
|
|
1468
|
+
"Number out of range: {}",
|
|
1469
|
+
canonical_number_message(ruby, true, &hex_digits, value)
|
|
1470
|
+
),
|
|
1471
|
+
));
|
|
1472
|
+
}
|
|
1473
|
+
} else if !hex_fits_bits(&hex_digits, 255) {
|
|
1474
|
+
return Err(value_out_of_bounds(
|
|
1475
|
+
ruby,
|
|
1476
|
+
format!(
|
|
1477
|
+
"Number out of range: {}",
|
|
1478
|
+
canonical_number_message(ruby, false, &hex_digits, value)
|
|
1479
|
+
),
|
|
1480
|
+
));
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
let byte_len = (bits / 8) as usize;
|
|
1484
|
+
let real_bits = bits as usize;
|
|
1485
|
+
let mut word = be32_from_hex(&hex_digits);
|
|
1486
|
+
if negative {
|
|
1487
|
+
// two's complement within 256 bits, then reduce modulo 2**real_bits
|
|
1488
|
+
// by keeping the low `real_bits` bits (value was within bounds, so
|
|
1489
|
+
// this reproduces `value.to_i % 2 ** real_size`)
|
|
1490
|
+
negate32(&mut word);
|
|
1491
|
+
mask_bits(&mut word, real_bits);
|
|
1492
|
+
} else {
|
|
1493
|
+
mask_bits(&mut word, real_bits);
|
|
1494
|
+
}
|
|
1495
|
+
let minimal_len = 32 - word.iter().take_while(|&&b| b == 0).count();
|
|
1496
|
+
if minimal_len > byte_len {
|
|
1497
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1498
|
+
} else {
|
|
1499
|
+
out.extend(std::iter::repeat_n(0u8, byte_len - minimal_len));
|
|
1500
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1501
|
+
}
|
|
1502
|
+
Ok(())
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/// Keeps the low `bits` bits of a 32-byte big-endian word.
|
|
1506
|
+
fn mask_bits(word: &mut [u8; 32], bits: usize) {
|
|
1507
|
+
let keep_bytes = bits / 8;
|
|
1508
|
+
let rem = bits % 8;
|
|
1509
|
+
for b in word.iter_mut().take(32 - keep_bytes) {
|
|
1510
|
+
*b = 0;
|
|
1511
|
+
}
|
|
1512
|
+
if rem > 0 && keep_bytes < 32 {
|
|
1513
|
+
let idx = 32 - keep_bytes - 1;
|
|
1514
|
+
word[idx] &= (1u8 << rem) - 1;
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/// Packed numeric: Integer/Float only (the reference does not coerce
|
|
1519
|
+
/// strings here); BigDecimal shapes fall back to Ruby.
|
|
1520
|
+
fn packed_numeric(ruby: &Ruby, value: Value) -> Result<Option<(bool, String)>, Fail> {
|
|
1521
|
+
if let Some(int) = Integer::from_value(value) {
|
|
1522
|
+
if let Ok(i) = int.to_i64() {
|
|
1523
|
+
let digits = dec_to_hex(&i.unsigned_abs().to_string());
|
|
1524
|
+
return Ok(Some((i < 0, digits)));
|
|
1525
|
+
}
|
|
1526
|
+
let negative: bool = value.funcall("<", (0,)).map_err(Fail::Native)?;
|
|
1527
|
+
if let Ok(n) = int.to_u128() {
|
|
1528
|
+
return Ok(Some((negative, format!("{n:x}"))));
|
|
1529
|
+
}
|
|
1530
|
+
if let Ok(i) = int.to_i128() {
|
|
1531
|
+
return Ok(Some((negative, format!("{:x}", i.unsigned_abs()))));
|
|
1532
|
+
}
|
|
1533
|
+
let abs: Value = value.funcall("abs", ()).map_err(Fail::Native)?;
|
|
1534
|
+
let hex: RString = abs.funcall("to_s", (16,)).map_err(Fail::Native)?;
|
|
1535
|
+
let digits = String::from_utf8_lossy(unsafe { hex.as_slice() })
|
|
1536
|
+
.trim_start_matches('0')
|
|
1537
|
+
.to_owned();
|
|
1538
|
+
return Ok(Some((negative, digits)));
|
|
1539
|
+
}
|
|
1540
|
+
if let Some(f) = Float::from_value(value) {
|
|
1541
|
+
let v = f.to_f64();
|
|
1542
|
+
if !v.is_finite() {
|
|
1543
|
+
return Ok(None);
|
|
1544
|
+
}
|
|
1545
|
+
// Ruby: Integer#to_i truncates toward zero; keep the same behaviour
|
|
1546
|
+
let t = v.trunc();
|
|
1547
|
+
if t.abs() < 1e30 {
|
|
1548
|
+
let i = t as i128;
|
|
1549
|
+
let digits = format!("{:x}", i.unsigned_abs());
|
|
1550
|
+
return Ok(Some((i < 0, digits)));
|
|
1551
|
+
}
|
|
1552
|
+
return Ok(None);
|
|
1553
|
+
}
|
|
1554
|
+
let _ = ruby;
|
|
1555
|
+
Ok(None)
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/// Packed fixed-point: bounds against `2**decimals` on the unscaled value
|
|
1559
|
+
/// (the reference quirk), scaling by `10**decimals`, then uint/int of the
|
|
1560
|
+
/// scaled value with its own bounds.
|
|
1561
|
+
fn packed_fixed(
|
|
1562
|
+
ruby: &Ruby,
|
|
1563
|
+
signed: bool,
|
|
1564
|
+
byte_size: usize,
|
|
1565
|
+
decimals: u32,
|
|
1566
|
+
value: Value,
|
|
1567
|
+
out: &mut Vec<u8>,
|
|
1568
|
+
) -> Result<(), Fail> {
|
|
1569
|
+
// Bounds are checked on the unscaled value: 0 <= value < 2**decimals
|
|
1570
|
+
// (unsigned) or -2**(decimals-1) <= value < 2**(decimals-1) (signed).
|
|
1571
|
+
let int_part_bound = decimals as usize; // 2**decimals
|
|
1572
|
+
let (negative, int_digits) = decimal_parts(ruby, value)?;
|
|
1573
|
+
let int_hex = dec_to_hex(&int_digits);
|
|
1574
|
+
let int_part = int_hex.trim_start_matches('0');
|
|
1575
|
+
|
|
1576
|
+
// Bounds compare the integer part against 2**decimals in hex.
|
|
1577
|
+
if signed {
|
|
1578
|
+
let half = decimals.saturating_sub(1) as usize;
|
|
1579
|
+
// negatives may be exactly -2**(decimals-1)
|
|
1580
|
+
let ok = hex_fits_bits(int_part, half) || (negative && is_exact_pow2(int_part, half));
|
|
1581
|
+
if !ok {
|
|
1582
|
+
return Err(value_out_of_bounds(ruby, display(ruby, value)));
|
|
1583
|
+
}
|
|
1584
|
+
} else if negative || !hex_fits_bits(int_part, int_part_bound) {
|
|
1585
|
+
return Err(value_out_of_bounds(ruby, display(ruby, value)));
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
// Integer values scale exactly (value * 10**decimals); Float/BigDecimal
|
|
1589
|
+
// shapes fall back so the reference's own arithmetic and rounding apply
|
|
1590
|
+
// verbatim.
|
|
1591
|
+
let scaled_dec = mul_dec(&int_digits, &format!("1{}", "0".repeat(decimals as usize)));
|
|
1592
|
+
let sdigits = dec_to_hex(&scaled_dec);
|
|
1593
|
+
let sneg = negative;
|
|
1594
|
+
|
|
1595
|
+
if signed {
|
|
1596
|
+
// int(scaled, byte_size): INT_MAX/INT_MIN bound on the scaled
|
|
1597
|
+
// value, then two's complement modulo 2**(byte_size * 8)
|
|
1598
|
+
if sneg {
|
|
1599
|
+
if !hex_fits_bits(&sdigits, 255) && !is_exact_pow2(&sdigits, 255) {
|
|
1600
|
+
return Err(value_out_of_bounds(
|
|
1601
|
+
ruby,
|
|
1602
|
+
format!("Number out of range: -{}", hex_to_dec(&sdigits)),
|
|
1603
|
+
));
|
|
1604
|
+
}
|
|
1605
|
+
} else if !hex_fits_bits(&sdigits, 255) {
|
|
1606
|
+
return Err(value_out_of_bounds(
|
|
1607
|
+
ruby,
|
|
1608
|
+
format!("Number out of range: {}", hex_to_dec(&sdigits)),
|
|
1609
|
+
));
|
|
1610
|
+
}
|
|
1611
|
+
let mut word = be32_from_hex(&sdigits);
|
|
1612
|
+
if sneg {
|
|
1613
|
+
negate32(&mut word);
|
|
1614
|
+
}
|
|
1615
|
+
mask_bits(&mut word, byte_size * 8);
|
|
1616
|
+
emit_packed_word(ruby, &word, byte_size, out)
|
|
1617
|
+
} else {
|
|
1618
|
+
// uint(scaled, byte_size): 256-bit bound, left-pad without masking
|
|
1619
|
+
if !hex_fits_bits(&sdigits, 256) {
|
|
1620
|
+
return Err(value_out_of_bounds(
|
|
1621
|
+
ruby,
|
|
1622
|
+
format!("Number out of range: {}", hex_to_dec(&sdigits)),
|
|
1623
|
+
));
|
|
1624
|
+
}
|
|
1625
|
+
emit_packed_word(ruby, &be32_from_hex(&sdigits), byte_size, out)
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
/// Decimal string multiplication (both operands are decimal digit strings).
|
|
1630
|
+
fn mul_dec(a: &str, b: &str) -> String {
|
|
1631
|
+
let a: Vec<u8> = a.bytes().map(|c| c - b'0').collect();
|
|
1632
|
+
let b: Vec<u8> = b.bytes().map(|c| c - b'0').collect();
|
|
1633
|
+
let mut result = vec![0u8; a.len() + b.len()];
|
|
1634
|
+
for i in 0..a.len() {
|
|
1635
|
+
let da = a[a.len() - 1 - i] as u32;
|
|
1636
|
+
let mut carry = 0u32;
|
|
1637
|
+
for j in 0..b.len() {
|
|
1638
|
+
let db = b[b.len() - 1 - j] as u32;
|
|
1639
|
+
let v = result[i + j] as u32 + da * db + carry;
|
|
1640
|
+
result[i + j] = (v % 10) as u8;
|
|
1641
|
+
carry = v / 10;
|
|
1642
|
+
}
|
|
1643
|
+
let mut idx = i + b.len();
|
|
1644
|
+
while carry > 0 {
|
|
1645
|
+
let v = result[idx] as u32 + carry;
|
|
1646
|
+
result[idx] = (v % 10) as u8;
|
|
1647
|
+
carry = v / 10;
|
|
1648
|
+
if idx == result.len() - 1 {
|
|
1649
|
+
break;
|
|
1650
|
+
}
|
|
1651
|
+
idx += 1;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
let s: String = result
|
|
1655
|
+
.iter()
|
|
1656
|
+
.rev()
|
|
1657
|
+
.skip_while(|&&d| d == 0)
|
|
1658
|
+
.map(|&d| (b'0' + d) as char)
|
|
1659
|
+
.collect();
|
|
1660
|
+
if s.is_empty() {
|
|
1661
|
+
"0".to_owned()
|
|
1662
|
+
} else {
|
|
1663
|
+
s
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
/// Integer values only, as decimal digits: the fixed-point scaling is a
|
|
1668
|
+
/// decimal multiplication. Float/BigDecimal shapes fall back (the reference
|
|
1669
|
+
/// computes them via Float/BigDecimal arithmetic whose rounding must apply
|
|
1670
|
+
/// verbatim).
|
|
1671
|
+
fn decimal_parts(_ruby: &Ruby, value: Value) -> Result<(bool, String), Fail> {
|
|
1672
|
+
if let Some(int) = Integer::from_value(value) {
|
|
1673
|
+
if let Ok(i) = int.to_i64() {
|
|
1674
|
+
return Ok((i < 0, i.unsigned_abs().to_string()));
|
|
1675
|
+
}
|
|
1676
|
+
let negative: bool = value.funcall("<", (0,)).map_err(Fail::Native)?;
|
|
1677
|
+
let s: RString = value.funcall("to_s", ()).map_err(Fail::Native)?;
|
|
1678
|
+
let text = String::from_utf8_lossy(unsafe { s.as_slice() }).into_owned();
|
|
1679
|
+
let digits = text
|
|
1680
|
+
.strip_prefix('-')
|
|
1681
|
+
.unwrap_or(&text)
|
|
1682
|
+
.trim_start_matches('0')
|
|
1683
|
+
.to_owned();
|
|
1684
|
+
return Ok((negative, digits));
|
|
1685
|
+
}
|
|
1686
|
+
Err(Fail::Unsupported)
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
fn emit_packed_word(
|
|
1690
|
+
ruby: &Ruby,
|
|
1691
|
+
word: &[u8; 32],
|
|
1692
|
+
byte_size: usize,
|
|
1693
|
+
out: &mut Vec<u8>,
|
|
1694
|
+
) -> Result<(), Fail> {
|
|
1695
|
+
let minimal_len = 32 - word.iter().take_while(|&&b| b == 0).count();
|
|
1696
|
+
let _ = ruby;
|
|
1697
|
+
if minimal_len > byte_size {
|
|
1698
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1699
|
+
} else {
|
|
1700
|
+
out.extend(std::iter::repeat_n(0u8, byte_size - minimal_len));
|
|
1701
|
+
out.extend_from_slice(&word[32 - minimal_len..]);
|
|
1702
|
+
}
|
|
1703
|
+
Ok(())
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
/// Packed address: the four reference branches padded to 20 bytes.
|
|
1707
|
+
fn packed_address(ruby: &Ruby, value: Value, out: &mut Vec<u8>) -> Result<(), Fail> {
|
|
1708
|
+
let address_class = fetch_class(ruby, "Eth::Address")?;
|
|
1709
|
+
if value.is_kind_of(address_class) {
|
|
1710
|
+
let s: RString = value.funcall("to_s", ())?;
|
|
1711
|
+
let text = String::from_utf8_lossy(unsafe { s.as_slice() }).into_owned();
|
|
1712
|
+
let hex = text.strip_prefix("0x").unwrap_or(&text);
|
|
1713
|
+
let bytes = hex_to_bin(ruby, hex.as_bytes())?;
|
|
1714
|
+
out.extend(std::iter::repeat_n(
|
|
1715
|
+
0u8,
|
|
1716
|
+
20usize.saturating_sub(bytes.len()),
|
|
1717
|
+
));
|
|
1718
|
+
out.extend_from_slice(&bytes);
|
|
1719
|
+
return Ok(());
|
|
1720
|
+
}
|
|
1721
|
+
if let Some(int) = Integer::from_value(value) {
|
|
1722
|
+
if int.to_i64().map(|i| i < 0).unwrap_or(true) {
|
|
1723
|
+
return Err(Fail::Native(Error::new(
|
|
1724
|
+
ruby.exception_arg_error(),
|
|
1725
|
+
format!("Integer invalid or out of range: {}", display(ruby, value)),
|
|
1726
|
+
)));
|
|
1727
|
+
}
|
|
1728
|
+
let word = uint_word_from_integer(ruby, &int, value)?;
|
|
1729
|
+
out.extend_from_slice(&word[12..]);
|
|
1730
|
+
return Ok(());
|
|
1731
|
+
}
|
|
1732
|
+
if let Some(s) = RString::from_value(value) {
|
|
1733
|
+
let bytes = unsafe { s.as_slice() };
|
|
1734
|
+
if bytes.len() == 20 {
|
|
1735
|
+
out.extend_from_slice(bytes);
|
|
1736
|
+
return Ok(());
|
|
1737
|
+
} else if bytes.len() == 40 {
|
|
1738
|
+
let decoded = hex_to_bin(ruby, bytes)?;
|
|
1739
|
+
out.extend_from_slice(&decoded);
|
|
1740
|
+
return Ok(());
|
|
1741
|
+
} else if bytes.len() == 42 && bytes.starts_with(b"0x") {
|
|
1742
|
+
let decoded = hex_to_bin(ruby, &bytes[2..])?;
|
|
1743
|
+
out.extend_from_slice(&decoded);
|
|
1744
|
+
return Ok(());
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
Err(encoding_error(
|
|
1748
|
+
ruby,
|
|
1749
|
+
format!("Could not parse address: {}", display(ruby, value)),
|
|
1750
|
+
))
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
// ---------------------------------------------------------------------------
|
|
1754
|
+
// decoding
|
|
1755
|
+
// ---------------------------------------------------------------------------
|
|
1756
|
+
|
|
1757
|
+
/// A decoded payload slice; `Nil` mirrors Ruby slicing past the end.
|
|
1758
|
+
#[derive(Clone)]
|
|
1759
|
+
enum Slice<'a> {
|
|
1760
|
+
Data(&'a [u8]),
|
|
1761
|
+
/// nil slice; carries the first method the reference derefs, so the
|
|
1762
|
+
/// raw NoMethodError message matches eth.rb.
|
|
1763
|
+
Nil(&'static str),
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
fn decode_inner(ruby: &Ruby, schemas: &[Schema], data: &[u8]) -> Result<Vec<Value>, Fail> {
|
|
1767
|
+
let n = schemas.len();
|
|
1768
|
+
let mut start_positions: Vec<Option<u128>> = vec![None; n + 1];
|
|
1769
|
+
start_positions[n] = Some(data.len() as u128);
|
|
1770
|
+
let mut outputs: Vec<Option<Slice>> = vec![None; n];
|
|
1771
|
+
let mut pos: usize = 0;
|
|
1772
|
+
|
|
1773
|
+
for (i, t) in schemas.iter().enumerate() {
|
|
1774
|
+
if t.dynamic() {
|
|
1775
|
+
if pos > data.len() {
|
|
1776
|
+
// `Util#deserialize_big_endian_to_int(data[pos, 32])` on nil
|
|
1777
|
+
return Err(nil_method_error(ruby, "sub"));
|
|
1778
|
+
}
|
|
1779
|
+
let end = (pos + 32).min(data.len());
|
|
1780
|
+
let off = be_word_sat(&data[pos..end]);
|
|
1781
|
+
start_positions[i] = Some(off);
|
|
1782
|
+
let mut j = i as isize - 1;
|
|
1783
|
+
while j >= 0 && start_positions[j as usize].is_none() {
|
|
1784
|
+
start_positions[j as usize] = start_positions[i];
|
|
1785
|
+
j -= 1;
|
|
1786
|
+
}
|
|
1787
|
+
pos += 32;
|
|
1788
|
+
} else {
|
|
1789
|
+
let size = t.size().unwrap_or(32);
|
|
1790
|
+
let end = (pos + size).min(data.len());
|
|
1791
|
+
outputs[i] = Some(Slice::Data(&data[pos.min(data.len())..end]));
|
|
1792
|
+
pos += size;
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
let mut j = n as isize - 1;
|
|
1797
|
+
while j >= 0 && start_positions[j as usize].is_none() {
|
|
1798
|
+
start_positions[j as usize] = start_positions[n];
|
|
1799
|
+
j -= 1;
|
|
1800
|
+
}
|
|
1801
|
+
if pos > data.len() {
|
|
1802
|
+
return Err(decoding_error(ruby, "Not enough data for head"));
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
for (i, t) in schemas.iter().enumerate() {
|
|
1806
|
+
if t.dynamic() {
|
|
1807
|
+
let start = start_positions[i].unwrap_or(0);
|
|
1808
|
+
let stop = start_positions[i + 1].unwrap_or(0);
|
|
1809
|
+
// Ruby slices `data[offset...next_offset]`; an index beyond
|
|
1810
|
+
// `long` raises a RangeError before any nil semantics apply.
|
|
1811
|
+
if start > LONG_MAX || stop > LONG_MAX {
|
|
1812
|
+
return Err(Fail::Native(Error::new(
|
|
1813
|
+
ruby.exception_range_error(),
|
|
1814
|
+
"bignum too big to convert into 'long'",
|
|
1815
|
+
)));
|
|
1816
|
+
}
|
|
1817
|
+
outputs[i] = if start > data.len() as u128 || stop < start {
|
|
1818
|
+
Some(Slice::Nil(nil_method_for(t)))
|
|
1819
|
+
} else {
|
|
1820
|
+
let s = start as usize;
|
|
1821
|
+
let e = (stop as usize).min(data.len());
|
|
1822
|
+
Some(Slice::Data(&data[s..e]))
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
let mut results = Vec::with_capacity(n);
|
|
1828
|
+
for (i, t) in schemas.iter().enumerate() {
|
|
1829
|
+
match outputs[i].as_ref().expect("outputs fully assigned") {
|
|
1830
|
+
Slice::Data(bytes) => results.push(decode_value(ruby, t, bytes)?),
|
|
1831
|
+
Slice::Nil(method) => match nil_output(ruby, t, method)? {
|
|
1832
|
+
Some(v) => results.push(v),
|
|
1833
|
+
None => results.push(ruby.qnil().as_value()),
|
|
1834
|
+
},
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
Ok(results)
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
/// The first method the reference decoder calls on a nil slice per branch.
|
|
1841
|
+
fn nil_method_for(schema: &Schema) -> &'static str {
|
|
1842
|
+
match schema {
|
|
1843
|
+
Schema::Tuple(_) => "size",
|
|
1844
|
+
Schema::Array(_, length) => {
|
|
1845
|
+
if *length == 0 {
|
|
1846
|
+
"[]" // reads the length word first
|
|
1847
|
+
} else {
|
|
1848
|
+
"size"
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
Schema::UInt(_) | Schema::Int(_) => "sub",
|
|
1852
|
+
Schema::Str | Schema::Bytes | Schema::Bool => "[]",
|
|
1853
|
+
Schema::Address => "unpack",
|
|
1854
|
+
Schema::Hash(_) | Schema::BytesN(_) => "[]",
|
|
1855
|
+
Schema::Fixed { .. } => "sub",
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
/// Nil slices on some branches produce non-NoMethodError outcomes.
|
|
1860
|
+
fn nil_output(ruby: &Ruby, schema: &Schema, method: &'static str) -> Result<Option<Value>, Fail> {
|
|
1861
|
+
match schema {
|
|
1862
|
+
Schema::Address => Err(Fail::Native(Error::new(
|
|
1863
|
+
ruby.exception_type_error(),
|
|
1864
|
+
"Value must be an instance of String",
|
|
1865
|
+
))),
|
|
1866
|
+
// `data[0, N]` on nil returns nil as the decoded value
|
|
1867
|
+
Schema::Hash(_) | Schema::BytesN(_) => Ok(None),
|
|
1868
|
+
_ => Err(nil_method_error(ruby, method)),
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
fn be_word_sat(word: &[u8]) -> u128 {
|
|
1873
|
+
if word.len() == 32 && word[..16].iter().any(|&b| b != 0) {
|
|
1874
|
+
return u128::MAX; // value beyond 128 bits: saturate for comparisons
|
|
1875
|
+
}
|
|
1876
|
+
let mut n: u128 = 0;
|
|
1877
|
+
for &b in word {
|
|
1878
|
+
n = (n << 8) | b as u128;
|
|
1879
|
+
}
|
|
1880
|
+
n
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
fn decode_value(ruby: &Ruby, schema: &Schema, data: &[u8]) -> Result<Value, Fail> {
|
|
1884
|
+
match schema {
|
|
1885
|
+
Schema::Str | Schema::Bytes => {
|
|
1886
|
+
let l = be_word_sat(word_prefix(data));
|
|
1887
|
+
let body: &[u8] = if data.len() >= 32 {
|
|
1888
|
+
&data[32..]
|
|
1889
|
+
} else {
|
|
1890
|
+
return Err(nil_method_error(ruby, "size"));
|
|
1891
|
+
};
|
|
1892
|
+
let expected = ceil32_u128(l);
|
|
1893
|
+
if body.len() as u128 != expected {
|
|
1894
|
+
return Err(decoding_error(
|
|
1895
|
+
ruby,
|
|
1896
|
+
"Wrong data size for string/bytes object",
|
|
1897
|
+
));
|
|
1898
|
+
}
|
|
1899
|
+
let len = (l.min(body.len() as u128)) as usize;
|
|
1900
|
+
// `Decoder.type` early-returns the binary slice for dynamic
|
|
1901
|
+
// string/bytes; the UTF-8 re-tag only exists in the unreachable
|
|
1902
|
+
// primitive branch, so parity means plain binary here.
|
|
1903
|
+
shared_or_copy(ruby, body, len)
|
|
1904
|
+
}
|
|
1905
|
+
Schema::BytesN(n_bits) => {
|
|
1906
|
+
let len = (*n_bits as usize).min(data.len());
|
|
1907
|
+
shared_or_copy(ruby, data, len)
|
|
1908
|
+
}
|
|
1909
|
+
Schema::Hash(n_bits) => {
|
|
1910
|
+
let n = *n_bits as usize;
|
|
1911
|
+
if n <= 32 {
|
|
1912
|
+
let start = 32 - n;
|
|
1913
|
+
let len = n.min(data.len().saturating_sub(start));
|
|
1914
|
+
let start = start.min(data.len());
|
|
1915
|
+
Ok(ruby.str_from_slice(&data[start..start + len]).as_value())
|
|
1916
|
+
} else {
|
|
1917
|
+
// Reference indexes with a negative start; replicate the nil
|
|
1918
|
+
// or wrapped slice Ruby produces.
|
|
1919
|
+
let start = data.len() as isize - (n as isize - 32);
|
|
1920
|
+
if start <= 0 {
|
|
1921
|
+
Ok(ruby.qnil().as_value())
|
|
1922
|
+
} else {
|
|
1923
|
+
let s = start as usize;
|
|
1924
|
+
let len = n.min(data.len().saturating_sub(s));
|
|
1925
|
+
Ok(ruby.str_from_slice(&data[s..s + len]).as_value())
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
Schema::Address => {
|
|
1930
|
+
let mut hex = String::with_capacity(42);
|
|
1931
|
+
hex.push_str("0x");
|
|
1932
|
+
for &b in &data[12..] {
|
|
1933
|
+
hex.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
|
|
1934
|
+
hex.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
|
|
1935
|
+
}
|
|
1936
|
+
let s = ruby.str_new(&hex);
|
|
1937
|
+
Ok(s.as_value())
|
|
1938
|
+
}
|
|
1939
|
+
Schema::UInt(_) => {
|
|
1940
|
+
let digits = be_word_to_hex(data);
|
|
1941
|
+
integer_from_hex(ruby, &digits)
|
|
1942
|
+
}
|
|
1943
|
+
Schema::Int(bits) => {
|
|
1944
|
+
let digits = be_word_to_hex(data);
|
|
1945
|
+
let threshold_bits = (*bits - 1) as usize;
|
|
1946
|
+
if hex_fits_bits(&digits, threshold_bits) && !is_exact_pow2(&digits, threshold_bits) {
|
|
1947
|
+
integer_from_hex(ruby, &digits)
|
|
1948
|
+
} else {
|
|
1949
|
+
// negative: value = u - 2**256 = -(2**256 - u)
|
|
1950
|
+
let u = be32_from_hex(&digits);
|
|
1951
|
+
let mut magnitude = [0u8; 32];
|
|
1952
|
+
magnitude.copy_from_slice(&u);
|
|
1953
|
+
negate32(&mut magnitude); // 2**256 - u
|
|
1954
|
+
let mag_digits = word_to_hex(&magnitude);
|
|
1955
|
+
let int = integer_from_hex(ruby, &mag_digits)?;
|
|
1956
|
+
let neg: Value = int.funcall("-@", ()).map_err(Fail::Native)?;
|
|
1957
|
+
Ok(neg)
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
Schema::Bool => Ok(if data.last() == Some(&1) {
|
|
1961
|
+
ruby.qtrue().as_value()
|
|
1962
|
+
} else {
|
|
1963
|
+
ruby.qfalse().as_value()
|
|
1964
|
+
}),
|
|
1965
|
+
Schema::Array(elem, length) => decode_array(ruby, elem, *length, data),
|
|
1966
|
+
Schema::Tuple(comps) => decode_tuple(ruby, comps, data),
|
|
1967
|
+
// unreachable: packed encoding has no decoder and standard compile
|
|
1968
|
+
// rejects the fixed family
|
|
1969
|
+
Schema::Fixed { .. } => Err(decoding_error(ruby, "Unknown primitive type: fixed")),
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
/// `arg[0, 32]` semantics: shorter when fewer bytes are available.
|
|
1974
|
+
fn word_prefix(data: &[u8]) -> &[u8] {
|
|
1975
|
+
&data[..data.len().min(32)]
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
fn be_word_to_hex(word: &[u8]) -> String {
|
|
1979
|
+
let mut hex = String::with_capacity(word.len() * 2);
|
|
1980
|
+
for &b in word {
|
|
1981
|
+
hex.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
|
|
1982
|
+
hex.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
|
|
1983
|
+
}
|
|
1984
|
+
hex.trim_start_matches('0').to_owned()
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
fn word_to_hex(word: &[u8; 32]) -> String {
|
|
1988
|
+
be_word_to_hex(word)
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
/// Whether hex digits equal exactly `2**k` (value 2^k, bit length k+1).
|
|
1992
|
+
fn is_exact_pow2(digits: &str, k: usize) -> bool {
|
|
1993
|
+
let digits = digits.trim_start_matches('0');
|
|
1994
|
+
if digits.is_empty() {
|
|
1995
|
+
return false;
|
|
1996
|
+
}
|
|
1997
|
+
let nibbles = (k + 1).div_ceil(4);
|
|
1998
|
+
if digits.len() != nibbles {
|
|
1999
|
+
return false;
|
|
2000
|
+
}
|
|
2001
|
+
let shift = k - 4 * (nibbles - 1);
|
|
2002
|
+
let expected: u8 = 1u8 << shift;
|
|
2003
|
+
nibble(digits.as_bytes()[0]) == expected
|
|
2004
|
+
&& digits.as_bytes()[1..].iter().all(|&b| nibble(b) == 0)
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
fn decode_array(ruby: &Ruby, elem: &Schema, length: usize, data: &[u8]) -> Result<Value, Fail> {
|
|
2008
|
+
if length == 0 {
|
|
2009
|
+
// The length word can exceed `usize`; bound checks run in u128
|
|
2010
|
+
// before any truncating conversion.
|
|
2011
|
+
let l_word = be_word_sat(word_prefix(data));
|
|
2012
|
+
let nested_size = elem.size();
|
|
2013
|
+
let mut items = Vec::new();
|
|
2014
|
+
if elem.dynamic() {
|
|
2015
|
+
if (data.len() as u128) < 32u128.saturating_add(32u128.saturating_mul(l_word)) {
|
|
2016
|
+
return Err(decoding_error(ruby, "Wrong data size for dynamic array"));
|
|
2017
|
+
}
|
|
2018
|
+
let l = l_word as usize;
|
|
2019
|
+
let mut offsets = Vec::with_capacity(l);
|
|
2020
|
+
for i in 0..l {
|
|
2021
|
+
let at = 32 + i * 32;
|
|
2022
|
+
let off = be_word_sat(word_prefix(&data[at..])) as i128;
|
|
2023
|
+
if (off < 32 * l as i128) || off > data.len() as i128 - 64 {
|
|
2024
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2025
|
+
}
|
|
2026
|
+
offsets.push(off);
|
|
2027
|
+
}
|
|
2028
|
+
for (index, &off) in offsets.iter().enumerate() {
|
|
2029
|
+
let start = 32 + off as usize;
|
|
2030
|
+
let stop = if index + 1 < offsets.len() {
|
|
2031
|
+
32 + offsets[index + 1] as usize
|
|
2032
|
+
} else {
|
|
2033
|
+
data.len()
|
|
2034
|
+
};
|
|
2035
|
+
if stop > data.len() || stop < start {
|
|
2036
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2037
|
+
}
|
|
2038
|
+
items.push(decode_value(ruby, elem, &data[start..stop])?);
|
|
2039
|
+
}
|
|
2040
|
+
} else {
|
|
2041
|
+
let size = nested_size.unwrap_or(0);
|
|
2042
|
+
if (data.len() as u128) < 32u128.saturating_add((size as u128).saturating_mul(l_word)) {
|
|
2043
|
+
return Err(decoding_error(ruby, "Wrong data size for dynamic array"));
|
|
2044
|
+
}
|
|
2045
|
+
let l = l_word as usize;
|
|
2046
|
+
for i in 0..l {
|
|
2047
|
+
let at = 32 + size * i;
|
|
2048
|
+
items.push(decode_value(
|
|
2049
|
+
ruby,
|
|
2050
|
+
elem,
|
|
2051
|
+
&data[at..(at + size).min(data.len())],
|
|
2052
|
+
)?);
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
return Ok(ruby.ary_new_from_values(&items).as_value());
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
// static array
|
|
2059
|
+
let mut items = Vec::new();
|
|
2060
|
+
if elem.dynamic() {
|
|
2061
|
+
if data.len() < 32 * length {
|
|
2062
|
+
return Err(decoding_error(ruby, "Wrong data size for static array"));
|
|
2063
|
+
}
|
|
2064
|
+
let mut offsets = Vec::with_capacity(length);
|
|
2065
|
+
for i in 0..length {
|
|
2066
|
+
let off = be_word_sat(word_prefix(&data[i * 32..])) as i128;
|
|
2067
|
+
if off < 32 * length as i128 || off > data.len() as i128 - 32 {
|
|
2068
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2069
|
+
}
|
|
2070
|
+
offsets.push(off);
|
|
2071
|
+
}
|
|
2072
|
+
for (i, &off) in offsets.iter().enumerate() {
|
|
2073
|
+
let stop = if i + 1 < offsets.len() {
|
|
2074
|
+
offsets[i + 1] as usize
|
|
2075
|
+
} else {
|
|
2076
|
+
data.len()
|
|
2077
|
+
};
|
|
2078
|
+
items.push(decode_value(ruby, elem, &data[off as usize..stop])?);
|
|
2079
|
+
}
|
|
2080
|
+
} else {
|
|
2081
|
+
let size = elem.size().unwrap_or(0);
|
|
2082
|
+
if data.len() < size * length {
|
|
2083
|
+
return Err(decoding_error(ruby, "Wrong data size for static array"));
|
|
2084
|
+
}
|
|
2085
|
+
for i in 0..length {
|
|
2086
|
+
let at = size * i;
|
|
2087
|
+
items.push(decode_value(
|
|
2088
|
+
ruby,
|
|
2089
|
+
elem,
|
|
2090
|
+
&data[at..(at + size).min(data.len())],
|
|
2091
|
+
)?);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
Ok(ruby.ary_new_from_values(&items).as_value())
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
fn decode_tuple(
|
|
2098
|
+
ruby: &Ruby,
|
|
2099
|
+
comps: &[(Option<String>, Schema)],
|
|
2100
|
+
data: &[u8],
|
|
2101
|
+
) -> Result<Value, Fail> {
|
|
2102
|
+
let mut result = Vec::with_capacity(comps.len());
|
|
2103
|
+
|
|
2104
|
+
// head scan
|
|
2105
|
+
let mut head_offset: usize = 0;
|
|
2106
|
+
let mut dynamic_offsets: Vec<(usize, u128)> = Vec::new();
|
|
2107
|
+
for (index, (_, comp)) in comps.iter().enumerate() {
|
|
2108
|
+
if comp.dynamic() {
|
|
2109
|
+
if head_offset + 32 > data.len() {
|
|
2110
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2111
|
+
}
|
|
2112
|
+
let pointer = be_word_sat(&data[head_offset..head_offset + 32]);
|
|
2113
|
+
dynamic_offsets.push((index, pointer));
|
|
2114
|
+
head_offset += 32;
|
|
2115
|
+
} else {
|
|
2116
|
+
let size = comp.size().unwrap_or(0);
|
|
2117
|
+
if head_offset + size > data.len() {
|
|
2118
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2119
|
+
}
|
|
2120
|
+
head_offset += size;
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// sorted dynamic ranges with overlap checks
|
|
2125
|
+
let mut ranges: Vec<Option<(usize, usize)>> = vec![None; comps.len()];
|
|
2126
|
+
{
|
|
2127
|
+
let mut sorted = dynamic_offsets.clone();
|
|
2128
|
+
sorted.sort_by_key(|&(_, pointer)| pointer);
|
|
2129
|
+
for (idx, &(index, pointer)) in sorted.iter().enumerate() {
|
|
2130
|
+
if (pointer as usize) < head_offset || pointer > data.len() as u128 {
|
|
2131
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2132
|
+
}
|
|
2133
|
+
let next_pointer = if idx + 1 < sorted.len() {
|
|
2134
|
+
sorted[idx + 1].1
|
|
2135
|
+
} else {
|
|
2136
|
+
data.len() as u128
|
|
2137
|
+
};
|
|
2138
|
+
if next_pointer < pointer || next_pointer > data.len() as u128 {
|
|
2139
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2140
|
+
}
|
|
2141
|
+
ranges[index] = Some((pointer as usize, next_pointer as usize));
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
let mut offset: usize = 0;
|
|
2146
|
+
for (index, (name, comp)) in comps.iter().enumerate() {
|
|
2147
|
+
let _ = name;
|
|
2148
|
+
if comp.dynamic() {
|
|
2149
|
+
let (pointer, next_offset) = ranges[index].expect("range computed");
|
|
2150
|
+
if pointer > data.len() || next_offset > data.len() || next_offset < pointer {
|
|
2151
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2152
|
+
}
|
|
2153
|
+
result.push(decode_value(ruby, comp, &data[pointer..next_offset])?);
|
|
2154
|
+
offset += 32;
|
|
2155
|
+
} else {
|
|
2156
|
+
let size = comp.size().unwrap_or(0);
|
|
2157
|
+
if offset + size > data.len() {
|
|
2158
|
+
return Err(decoding_error(ruby, "Offset out of bounds"));
|
|
2159
|
+
}
|
|
2160
|
+
result.push(decode_value(
|
|
2161
|
+
ruby,
|
|
2162
|
+
comp,
|
|
2163
|
+
&data[offset..(offset + size).min(data.len())],
|
|
2164
|
+
)?);
|
|
2165
|
+
offset += size;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
Ok(ruby.ary_new_from_values(&result).as_value())
|
|
2169
|
+
}
|