base58_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/Cargo.lock +294 -0
- data/Cargo.toml +8 -0
- data/LICENSE.txt +21 -0
- data/README.md +189 -0
- data/ext/base58_codec/Cargo.toml +20 -0
- data/ext/base58_codec/examples/micro.rs +73 -0
- data/ext/base58_codec/src/lib.rs +520 -0
- data/ext/base58_native/Cargo.toml +27 -0
- data/ext/base58_native/extconf.rb +6 -0
- data/ext/base58_native/src/lib.rs +196 -0
- data/lib/base58_native/fallback.rb +67 -0
- data/lib/base58_native/parity.rb +155 -0
- data/lib/base58_native/version.rb +5 -0
- data/lib/base58_native.rb +53 -0
- metadata +73 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
//! Ruby bindings for the Base58 fast path.
|
|
2
|
+
//!
|
|
3
|
+
//! Contract with the Ruby side (lib/base58_native.rb):
|
|
4
|
+
//! * `Base58Native::Fallback` is the reference implementation (a copy of
|
|
5
|
+
//! code-3's `lib/base58.rb`). Whenever the strict native fast path declines
|
|
6
|
+
//! an input (wrong type, non-ASCII-compatible encoding, characters outside
|
|
7
|
+
//! the alphabet, values wider than 128 bits, ...) the original argument is
|
|
8
|
+
//! forwarded there unchanged. That makes results *and* exceptions (class and
|
|
9
|
+
//! message) identical to the reference for every input.
|
|
10
|
+
//! * No `unsafe` (forbidden in Cargo.toml) and no panicking constructs
|
|
11
|
+
//! (denied via clippy). As a last line of defence every entry point also
|
|
12
|
+
//! runs under `catch_unwind`, turning a hypothetical panic into a rescuable
|
|
13
|
+
//! `Base58Native::Error` instead of magnus's process-ending `fatal`.
|
|
14
|
+
|
|
15
|
+
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
16
|
+
|
|
17
|
+
use magnus::{
|
|
18
|
+
encoding::EncodingCapable,
|
|
19
|
+
function,
|
|
20
|
+
prelude::*,
|
|
21
|
+
value::{Lazy, LazyId},
|
|
22
|
+
Error, ExceptionClass, Fixnum, Integer, RBignum, RModule, RString, Ruby, Value,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
use base58_codec as codec;
|
|
26
|
+
use codec::MAX_B58_LEN;
|
|
27
|
+
|
|
28
|
+
/// Run `f`, converting any panic into a Ruby `Base58Native::Error`.
|
|
29
|
+
#[inline(always)]
|
|
30
|
+
fn guard<T>(ruby: &Ruby, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
|
|
31
|
+
match catch_unwind(AssertUnwindSafe(f)) {
|
|
32
|
+
Ok(res) => res,
|
|
33
|
+
Err(_) => Err(Error::new(
|
|
34
|
+
internal_error_class(ruby),
|
|
35
|
+
"internal error in base58_native",
|
|
36
|
+
)),
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
fn base58_native_module(ruby: &Ruby) -> Result<RModule, Error> {
|
|
41
|
+
ruby.class_object().const_get::<_, RModule>("Base58Native")
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
fn internal_error_class(ruby: &Ruby) -> ExceptionClass {
|
|
45
|
+
base58_native_module(ruby)
|
|
46
|
+
.and_then(|m| m.const_get::<_, ExceptionClass>("Error"))
|
|
47
|
+
.unwrap_or_else(|_| ruby.exception_runtime_error())
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// Cold path: delegate to the reference implementation.
|
|
51
|
+
#[cold]
|
|
52
|
+
#[inline(never)]
|
|
53
|
+
fn fallback(ruby: &Ruby, method: &'static str, arg: Value) -> Result<Value, Error> {
|
|
54
|
+
let fallback: RModule = base58_native_module(ruby)?.const_get("Fallback")?;
|
|
55
|
+
fallback.funcall(method, (arg,))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// Copy the bytes out of `arg` if it is a String in an encoding where bytes
|
|
59
|
+
/// and characters coincide for ASCII (UTF-8, US-ASCII, ASCII-8BIT).
|
|
60
|
+
#[inline(always)]
|
|
61
|
+
fn ascii_bytes(ruby: &Ruby, arg: Value) -> Option<bytes::Bytes> {
|
|
62
|
+
let s = RString::from_value(arg)?;
|
|
63
|
+
let idx = s.enc_get();
|
|
64
|
+
if idx == ruby.utf8_encindex()
|
|
65
|
+
|| idx == ruby.usascii_encindex()
|
|
66
|
+
|| idx == ruby.ascii8bit_encindex()
|
|
67
|
+
{
|
|
68
|
+
Some(s.to_bytes())
|
|
69
|
+
} else {
|
|
70
|
+
None
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// 2**64 as a Ruby Integer, created once and kept alive (and pinned) by
|
|
75
|
+
/// magnus's `Lazy`. Bignum multiplication and addition cannot raise.
|
|
76
|
+
static TWO_POW_64: Lazy<Integer> =
|
|
77
|
+
Lazy::new(|ruby| ruby.integer_from_u64(1 << 63) * ruby.integer_from_i64(2));
|
|
78
|
+
|
|
79
|
+
static ID_TO_S: LazyId = LazyId::new("to_s");
|
|
80
|
+
|
|
81
|
+
/// u128 -> Ruby Integer without magnus's `integer_from_u128`, which goes via
|
|
82
|
+
/// a decimal string and `Kernel#Integer` (slow, and `unwrap`s internally).
|
|
83
|
+
#[inline]
|
|
84
|
+
fn u128_to_integer(ruby: &Ruby, v: u128) -> Integer {
|
|
85
|
+
match u64::try_from(v) {
|
|
86
|
+
Ok(small) => ruby.integer_from_u64(small),
|
|
87
|
+
Err(_) => {
|
|
88
|
+
let hi = ruby.integer_from_u64((v >> 64) as u64);
|
|
89
|
+
let lo = ruby.integer_from_u64(v as u64);
|
|
90
|
+
hi * ruby.get_inner(&TWO_POW_64) + lo
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Ruby Integer -> u128 for non-negative values below 2**128; `None` for
|
|
96
|
+
/// everything else (negative, wider, not an Integer), which the caller sends
|
|
97
|
+
/// to the fallback. Avoids magnus's `to_u128`, which formats bignums in
|
|
98
|
+
/// decimal and re-parses them.
|
|
99
|
+
#[inline]
|
|
100
|
+
fn integer_to_u128(ruby: &Ruby, arg: Value) -> Option<u128> {
|
|
101
|
+
if let Some(fix) = Fixnum::from_value(arg) {
|
|
102
|
+
return fix.to_u64().ok().map(u128::from);
|
|
103
|
+
}
|
|
104
|
+
let big = RBignum::from_value(arg)?;
|
|
105
|
+
if big.is_negative() {
|
|
106
|
+
return None;
|
|
107
|
+
}
|
|
108
|
+
// Power-of-two radix formatting is a cheap linear pass in CRuby.
|
|
109
|
+
let hex: RString = big
|
|
110
|
+
.funcall(LazyId::get_inner_with(&ID_TO_S, ruby), (16,))
|
|
111
|
+
.ok()?;
|
|
112
|
+
codec::parse_hex(&ascii_bytes(ruby, hex.as_value())?, false)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#[inline(always)]
|
|
116
|
+
fn utf8_str(ruby: &Ruby, bytes: &[u8]) -> Value {
|
|
117
|
+
ruby.enc_str_new(bytes, ruby.utf8_encoding()).as_value()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#[inline(always)]
|
|
121
|
+
fn encode_to_value(ruby: &Ruby, v: u128) -> Value {
|
|
122
|
+
let mut buf = [0u8; MAX_B58_LEN];
|
|
123
|
+
let start = codec::encode_u128(v, &mut buf);
|
|
124
|
+
utf8_str(ruby, buf.get(start..).unwrap_or(&buf))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
fn encode_from_uuid(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
128
|
+
guard(ruby, || {
|
|
129
|
+
let parsed = ascii_bytes(ruby, arg)
|
|
130
|
+
.and_then(|b| codec::parse_canonical_uuid(&b).or_else(|| codec::parse_hex(&b, true)));
|
|
131
|
+
match parsed {
|
|
132
|
+
Some(v) => Ok(encode_to_value(ruby, v)),
|
|
133
|
+
None => fallback(ruby, "encode_from_uuid", arg),
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fn encode_from_hex(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
139
|
+
guard(ruby, || {
|
|
140
|
+
match ascii_bytes(ruby, arg).and_then(|b| codec::parse_hex(&b, false)) {
|
|
141
|
+
Some(v) => Ok(encode_to_value(ruby, v)),
|
|
142
|
+
None => fallback(ruby, "encode_from_hex", arg),
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fn encode_from_base10(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
148
|
+
guard(ruby, || match integer_to_u128(ruby, arg) {
|
|
149
|
+
Some(v) => Ok(encode_to_value(ruby, v)),
|
|
150
|
+
None => fallback(ruby, "encode_from_base10", arg),
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
fn decode_to_uuid(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
155
|
+
guard(ruby, || {
|
|
156
|
+
match ascii_bytes(ruby, arg).and_then(|b| codec::decode_u128(&b)) {
|
|
157
|
+
Some(v) => Ok(utf8_str(ruby, &codec::format_uuid(v))),
|
|
158
|
+
None => fallback(ruby, "decode_to_uuid", arg),
|
|
159
|
+
}
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
fn decode_to_hex(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
164
|
+
guard(ruby, || {
|
|
165
|
+
match ascii_bytes(ruby, arg).and_then(|b| codec::decode_u128(&b)) {
|
|
166
|
+
Some(v) => {
|
|
167
|
+
let (buf, start) = codec::format_hex(v);
|
|
168
|
+
// Integer#to_s returns US-ASCII; match it.
|
|
169
|
+
let bytes = buf.get(start..).unwrap_or(&buf);
|
|
170
|
+
Ok(ruby.enc_str_new(bytes, ruby.usascii_encoding()).as_value())
|
|
171
|
+
}
|
|
172
|
+
None => fallback(ruby, "decode_to_hex", arg),
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
fn decode_to_base10(ruby: &Ruby, arg: Value) -> Result<Value, Error> {
|
|
178
|
+
guard(ruby, || {
|
|
179
|
+
match ascii_bytes(ruby, arg).and_then(|b| codec::decode_u128(&b)) {
|
|
180
|
+
Some(v) => Ok(u128_to_integer(ruby, v).as_value()),
|
|
181
|
+
None => fallback(ruby, "decode_to_base10", arg),
|
|
182
|
+
}
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#[magnus::init]
|
|
187
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
188
|
+
let module = ruby.define_module("Base58Native")?;
|
|
189
|
+
module.define_singleton_method("encode_from_uuid", function!(encode_from_uuid, 1))?;
|
|
190
|
+
module.define_singleton_method("decode_to_uuid", function!(decode_to_uuid, 1))?;
|
|
191
|
+
module.define_singleton_method("encode_from_hex", function!(encode_from_hex, 1))?;
|
|
192
|
+
module.define_singleton_method("decode_to_hex", function!(decode_to_hex, 1))?;
|
|
193
|
+
module.define_singleton_method("encode_from_base10", function!(encode_from_base10, 1))?;
|
|
194
|
+
module.define_singleton_method("decode_to_base10", function!(decode_to_base10, 1))?;
|
|
195
|
+
Ok(())
|
|
196
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Base58Native
|
|
4
|
+
# Reference implementation, kept byte-for-byte equivalent to Pocketflows'
|
|
5
|
+
# original pure-Ruby Base58 (code-3 lib/base58.rb). The native extension
|
|
6
|
+
# handles the common strict inputs itself and forwards everything else here,
|
|
7
|
+
# so results and exceptions match the reference for every input.
|
|
8
|
+
#
|
|
9
|
+
# Do not "improve" this module: its quirks are the spec.
|
|
10
|
+
module Fallback
|
|
11
|
+
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
12
|
+
INVERSE_MAP = ALPHABET.each_char.with_index.map { |char, i| [char, i] }.to_h.freeze
|
|
13
|
+
|
|
14
|
+
class << self
|
|
15
|
+
def encode_from_uuid(uuid)
|
|
16
|
+
no_dash = uuid.gsub("-", "")
|
|
17
|
+
encode_from_hex(no_dash)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def decode_to_uuid(uuid)
|
|
21
|
+
no_dash = decode_to_hex(uuid)
|
|
22
|
+
padded = no_dash.rjust(32, "0")
|
|
23
|
+
|
|
24
|
+
raise InvalidUUIDError, "decoded to invalid uuid" if padded.length > 32
|
|
25
|
+
|
|
26
|
+
"#{padded[0...8]}-#{padded[8...12]}-#{padded[12...16]}-#{padded[16...20]}-#{padded[20...]}"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def encode_from_hex(hex)
|
|
30
|
+
int_value = Integer(hex, 16)
|
|
31
|
+
encode_from_base10(int_value)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def decode_to_hex(hex)
|
|
35
|
+
base10 = decode_to_base10(hex)
|
|
36
|
+
base10.to_s(16)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def encode_from_base10(int_value)
|
|
40
|
+
digits = []
|
|
41
|
+
|
|
42
|
+
while int_value > 0
|
|
43
|
+
int_value, remainder = int_value.divmod(58)
|
|
44
|
+
digits << ALPHABET[remainder]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
digits << ALPHABET[0] if digits.empty?
|
|
48
|
+
|
|
49
|
+
digits.reverse.join
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def decode_to_base10(s)
|
|
53
|
+
int_value = 0
|
|
54
|
+
|
|
55
|
+
base = 1
|
|
56
|
+
s.chars.reverse.each.with_index do |c, _i|
|
|
57
|
+
raise DecodeError, "Invalid character #{c} in base58 string" if !INVERSE_MAP.key?(c)
|
|
58
|
+
|
|
59
|
+
int_value += base * INVERSE_MAP[c]
|
|
60
|
+
base *= 58
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
int_value
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
|
|
5
|
+
require "base58_native"
|
|
6
|
+
|
|
7
|
+
# Differential parity harness (opt-in: `require "base58_native/parity"`).
|
|
8
|
+
#
|
|
9
|
+
# Runs the same call against a reference implementation and Base58Native and
|
|
10
|
+
# compares result value, class, encoding and frozenness, or exception class
|
|
11
|
+
# (unqualified name) and message. Used by this gem's tests and by consumers
|
|
12
|
+
# to check parity against their own pure-Ruby Base58:
|
|
13
|
+
#
|
|
14
|
+
# cases = Base58Native::Parity.cases
|
|
15
|
+
# Base58Native::Parity.each_mismatch(Base58, Base58Native, cases) { |m, arg, ref, nat| ... }
|
|
16
|
+
module Base58Native::Parity
|
|
17
|
+
STRING_METHODS = %i[encode_from_uuid decode_to_uuid encode_from_hex decode_to_hex decode_to_base10].freeze
|
|
18
|
+
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
19
|
+
HEX = "0123456789abcdefABCDEF"
|
|
20
|
+
|
|
21
|
+
module_function
|
|
22
|
+
|
|
23
|
+
def outcome(impl, method, arg)
|
|
24
|
+
value = impl.public_send(method, arg)
|
|
25
|
+
[:ok, value, value.class, value.respond_to?(:encoding) ? value.encoding : nil, value.frozen?]
|
|
26
|
+
rescue StandardError => e
|
|
27
|
+
# Error classes live under different namespaces (Base58:: vs Base58Native::),
|
|
28
|
+
# so compare the unqualified class name.
|
|
29
|
+
[:raise, e.class.name.split("::").last, e.message]
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Yields [method, arg, reference_outcome, native_outcome] for mismatches.
|
|
33
|
+
def each_mismatch(reference, native, cases)
|
|
34
|
+
cases.each do |method, arg|
|
|
35
|
+
ref = outcome(reference, method, dup_arg(arg))
|
|
36
|
+
nat = outcome(native, method, dup_arg(arg))
|
|
37
|
+
yield method, arg, ref, nat unless ref == nat
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def dup_arg(arg)
|
|
42
|
+
arg.is_a?(String) ? arg.dup : arg
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def rand_str(rng, chars, len)
|
|
46
|
+
Array.new(len) { chars[rng.rand(chars.size)] }.join
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def uuid_from_int(n)
|
|
50
|
+
h = n.to_s(16).rjust(32, "0")
|
|
51
|
+
"#{h[0, 8]}-#{h[8, 4]}-#{h[12, 4]}-#{h[16, 4]}-#{h[20, 12]}"
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Deterministic (seeded) mix of typical and adversarial inputs.
|
|
55
|
+
def cases(seed: 1234, random: 20_000)
|
|
56
|
+
rng = Random.new(seed)
|
|
57
|
+
out = []
|
|
58
|
+
add = ->(m, a) { out << [m, a] }
|
|
59
|
+
max128 = 2**128 - 1
|
|
60
|
+
|
|
61
|
+
# --- integers / boundaries -------------------------------------------
|
|
62
|
+
ints = [0, 1, 57, 58, 59, max128, max128 + 1, 2**64 - 1, 2**64, 2**200, -1, -58, -(2**130)]
|
|
63
|
+
(1..23).each { |k| ints.push(58**k - 1, 58**k, 58**k + 1) }
|
|
64
|
+
128.times { |b| ints.push(2**b, 2**b - 1) }
|
|
65
|
+
ints.each do |i|
|
|
66
|
+
add[:encode_from_base10, i]
|
|
67
|
+
next if i.negative?
|
|
68
|
+
|
|
69
|
+
hex = i.to_s(16)
|
|
70
|
+
add[:encode_from_hex, hex]
|
|
71
|
+
add[:encode_from_hex, hex.upcase]
|
|
72
|
+
add[:encode_from_hex, "000#{hex}"]
|
|
73
|
+
b58 = Base58Native::Fallback.encode_from_base10(i)
|
|
74
|
+
%i[decode_to_uuid decode_to_hex decode_to_base10].each do |m|
|
|
75
|
+
add[m, b58]
|
|
76
|
+
add[m, "111#{b58}"]
|
|
77
|
+
end
|
|
78
|
+
add[:encode_from_uuid, uuid_from_int(i)] if i <= max128
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# --- canonical-ish UUIDs ---------------------------------------------
|
|
82
|
+
special = [0, max128, 1, 2**127, 2**64]
|
|
83
|
+
(special + Array.new(random) { rng.rand(2**128) } + Array.new(200) { rng.rand(2**(rng.rand(128) + 1)) }).each do |n|
|
|
84
|
+
u = uuid_from_int(n)
|
|
85
|
+
add[:encode_from_uuid, u]
|
|
86
|
+
add[:encode_from_uuid, u.upcase] if rng.rand(4).zero?
|
|
87
|
+
add[:encode_from_uuid, u.delete("-")] if rng.rand(8).zero?
|
|
88
|
+
add[:decode_to_uuid, Base58Native::Fallback.encode_from_uuid(u)]
|
|
89
|
+
end
|
|
90
|
+
200.times { add[:encode_from_uuid, SecureRandom.uuid] }
|
|
91
|
+
|
|
92
|
+
# --- hex oddities (Integer(hex, 16) leniency) ------------------------
|
|
93
|
+
hex_odd = ["", "-", "----", "0x", "0x1f", "0X1F", "0b1", "0o7", "0d9", "+1f", "-1f", " 1f", "1f ", "\n1f\n",
|
|
94
|
+
"1_f", "_1f", "1f_", "1__f", "g", "1g", "ff\0", "é", "1", "0x_ab", "-0", "+0", "00", "0"]
|
|
95
|
+
hex_odd.each do |h|
|
|
96
|
+
add[:encode_from_hex, h]
|
|
97
|
+
add[:encode_from_uuid, h]
|
|
98
|
+
add[:encode_from_uuid, "#{h}-#{h}"]
|
|
99
|
+
end
|
|
100
|
+
["550e8400-e29b-41d4-a716-44665544000", "550e8400-e29b-41d4-a716-4466554400000",
|
|
101
|
+
"550e8400e29b-41d4-a716-446655440000-", "-550e8400-e29b-41d4-a716-446655440000",
|
|
102
|
+
"550e8400--e29b-41d4-a716-446655440000", "550e8400-e29b-41d4-a716-44665544000g",
|
|
103
|
+
"{550e8400-e29b-41d4-a716-446655440000}", "550e8400-e29b-41d4-a716-446655440000\n",
|
|
104
|
+
" 550e8400-e29b-41d4-a716-446655440000", "550E8400-E29B-41D4-A716-446655440000",
|
|
105
|
+
"f" * 32, "f" * 33, "0" * 40 + "1", "-" * 36].each { |u| add[:encode_from_uuid, u]; add[:encode_from_hex, u] }
|
|
106
|
+
|
|
107
|
+
# --- random strings over mixed alphabets -----------------------------
|
|
108
|
+
pools = [ALPHABET, "#{ALPHABET}0OIl+/ ", HEX, "#{HEX}-", "#{HEX}-_xX +", "1", "z"]
|
|
109
|
+
3000.times do
|
|
110
|
+
pool = pools[rng.rand(pools.size)]
|
|
111
|
+
s = rand_str(rng, pool, rng.rand(45))
|
|
112
|
+
STRING_METHODS.each { |m| add[m, s] }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# --- every single byte, as UTF-8 and binary --------------------------
|
|
116
|
+
256.times do |b|
|
|
117
|
+
s = b.chr
|
|
118
|
+
STRING_METHODS.each do |m|
|
|
119
|
+
add[m, s.dup.force_encoding(Encoding::UTF_8)]
|
|
120
|
+
add[m, s.dup.force_encoding(Encoding::BINARY)]
|
|
121
|
+
add[m, "Ab#{s}cd".force_encoding(Encoding::BINARY)]
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# --- encodings, multibyte, invalid UTF-8 -----------------------------
|
|
126
|
+
good = "BWBeN28Vb7cMEx7Ym8AUzs"
|
|
127
|
+
uuid = "550e8400-e29b-41d4-a716-446655440000"
|
|
128
|
+
[
|
|
129
|
+
good.encode(Encoding::US_ASCII), good.b, good.encode(Encoding::UTF_16LE), good.encode(Encoding::UTF_16BE),
|
|
130
|
+
good.encode(Encoding::UTF_32LE), good.encode(Encoding::ISO_8859_1), good.encode(Encoding::Shift_JIS),
|
|
131
|
+
"AB".encode(Encoding::UTF_16LE), "AB".b.force_encoding(Encoding::UTF_16LE), "\xFF\xFE".b,
|
|
132
|
+
"Bé", "é", "日本", "ab ", "\xC3".dup.force_encoding("UTF-8"), "a\xFFb".dup.force_encoding("UTF-8"),
|
|
133
|
+
"#{good}\u0000", "\u{1F600}", good.dup.freeze
|
|
134
|
+
].each do |s|
|
|
135
|
+
STRING_METHODS.each { |m| add[m, s] }
|
|
136
|
+
end
|
|
137
|
+
[uuid.encode(Encoding::UTF_16LE), uuid.b, uuid.encode(Encoding::US_ASCII), uuid.encode(Encoding::ISO_8859_1)].each do |s|
|
|
138
|
+
add[:encode_from_uuid, s]
|
|
139
|
+
add[:encode_from_hex, s.encode("UTF-8").delete("-").encode(s.encoding)]
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# --- wrong types -----------------------------------------------------
|
|
143
|
+
[nil, 123, 1.5, -2.5, 2**130, :abc, :"550e8400-e29b-41d4-a716-446655440000", [], {}, Object.new, true].each do |v|
|
|
144
|
+
STRING_METHODS.each { |m| add[m, v] }
|
|
145
|
+
end
|
|
146
|
+
[nil, 1.5, 58.9, -0.5, "123", :a, Rational(7, 2), true, Object.new].each { |v| add[:encode_from_base10, v] }
|
|
147
|
+
|
|
148
|
+
# String subclass
|
|
149
|
+
sub = Class.new(String)
|
|
150
|
+
add[:decode_to_uuid, sub.new(good)]
|
|
151
|
+
add[:encode_from_uuid, sub.new(uuid)]
|
|
152
|
+
|
|
153
|
+
out
|
|
154
|
+
end
|
|
155
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "base58_native/version"
|
|
4
|
+
|
|
5
|
+
# Fast Base58 encoding/decoding of UUIDs, hex strings and integers, backed by
|
|
6
|
+
# a Rust extension. API-compatible with Pocketflows' original Base58 class:
|
|
7
|
+
#
|
|
8
|
+
# Base58Native.encode_from_uuid("550e8400-e29b-41d4-a716-446655440000") # => "BWBeN28Vb7cMEx7Ym8AUzs"
|
|
9
|
+
# Base58Native.decode_to_uuid("BWBeN28Vb7cMEx7Ym8AUzs")
|
|
10
|
+
# Base58Native.encode_from_hex / decode_to_hex
|
|
11
|
+
# Base58Native.encode_from_base10 / decode_to_base10
|
|
12
|
+
#
|
|
13
|
+
# Errors: Base58Native::DecodeError, Base58Native::InvalidUUIDError (both
|
|
14
|
+
# subclasses of Base58Native::Error < StandardError), plus whatever the
|
|
15
|
+
# reference implementation raises for malformed arguments (e.g. ArgumentError
|
|
16
|
+
# from Integer()).
|
|
17
|
+
module Base58Native
|
|
18
|
+
class Error < StandardError; end
|
|
19
|
+
class DecodeError < Error; end
|
|
20
|
+
class InvalidUUIDError < Error; end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
require_relative "base58_native/fallback"
|
|
24
|
+
|
|
25
|
+
module Base58Native
|
|
26
|
+
METHODS = %i[
|
|
27
|
+
encode_from_uuid decode_to_uuid
|
|
28
|
+
encode_from_hex decode_to_hex
|
|
29
|
+
encode_from_base10 decode_to_base10
|
|
30
|
+
].freeze
|
|
31
|
+
|
|
32
|
+
begin
|
|
33
|
+
# Precompiled (fat) gems ship one binary per Ruby minor version.
|
|
34
|
+
ruby_minor = RUBY_VERSION[/\A\d+\.\d+/]
|
|
35
|
+
begin
|
|
36
|
+
require_relative "base58_native/#{ruby_minor}/base58_native"
|
|
37
|
+
rescue LoadError
|
|
38
|
+
require_relative "base58_native/base58_native"
|
|
39
|
+
end
|
|
40
|
+
NATIVE = true
|
|
41
|
+
rescue LoadError => e
|
|
42
|
+
warn "[base58_native] native extension unavailable (#{e.message}); using pure-Ruby fallback"
|
|
43
|
+
NATIVE = false
|
|
44
|
+
METHODS.each do |name|
|
|
45
|
+
define_singleton_method(name) { |arg| Fallback.public_send(name, arg) }
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# True when the Rust extension is loaded.
|
|
50
|
+
def self.native?
|
|
51
|
+
NATIVE
|
|
52
|
+
end
|
|
53
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: base58_native
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Pocketflows
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: rb_sys
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - "~>"
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '0.9'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '0.9'
|
|
26
|
+
description: |
|
|
27
|
+
Drop-in, behaviour-identical native replacement for Pocketflows' pure-Ruby
|
|
28
|
+
Base58 (UUID <-> Base58 short ids). Written in safe Rust (no unsafe) with a
|
|
29
|
+
reference Ruby fallback for edge cases. Precompiled for common platforms,
|
|
30
|
+
so no Rust toolchain is needed to install.
|
|
31
|
+
executables: []
|
|
32
|
+
extensions:
|
|
33
|
+
- ext/base58_native/extconf.rb
|
|
34
|
+
extra_rdoc_files: []
|
|
35
|
+
files:
|
|
36
|
+
- Cargo.lock
|
|
37
|
+
- Cargo.toml
|
|
38
|
+
- LICENSE.txt
|
|
39
|
+
- README.md
|
|
40
|
+
- ext/base58_codec/Cargo.toml
|
|
41
|
+
- ext/base58_codec/examples/micro.rs
|
|
42
|
+
- ext/base58_codec/src/lib.rs
|
|
43
|
+
- ext/base58_native/Cargo.toml
|
|
44
|
+
- ext/base58_native/extconf.rb
|
|
45
|
+
- ext/base58_native/src/lib.rs
|
|
46
|
+
- lib/base58_native.rb
|
|
47
|
+
- lib/base58_native/fallback.rb
|
|
48
|
+
- lib/base58_native/parity.rb
|
|
49
|
+
- lib/base58_native/version.rb
|
|
50
|
+
homepage: https://github.com/pocketflows/base58_native
|
|
51
|
+
licenses:
|
|
52
|
+
- MIT
|
|
53
|
+
metadata:
|
|
54
|
+
source_code_uri: https://github.com/pocketflows/base58_native
|
|
55
|
+
rubygems_mfa_required: 'true'
|
|
56
|
+
rdoc_options: []
|
|
57
|
+
require_paths:
|
|
58
|
+
- lib
|
|
59
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
60
|
+
requirements:
|
|
61
|
+
- - ">="
|
|
62
|
+
- !ruby/object:Gem::Version
|
|
63
|
+
version: '3.3'
|
|
64
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
65
|
+
requirements:
|
|
66
|
+
- - ">="
|
|
67
|
+
- !ruby/object:Gem::Version
|
|
68
|
+
version: '0'
|
|
69
|
+
requirements: []
|
|
70
|
+
rubygems_version: 3.6.9
|
|
71
|
+
specification_version: 4
|
|
72
|
+
summary: Fast Base58 encoding of UUIDs, hex and integers via a Rust extension
|
|
73
|
+
test_files: []
|