lexer_kit 0.6.1 → 0.7.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 +4 -4
- data/Cargo.lock +265 -0
- data/Cargo.toml +37 -0
- data/README.md +7 -3
- data/crates/lexer_kit_core/Cargo.toml +17 -0
- data/crates/lexer_kit_core/src/dfa.rs +437 -0
- data/crates/lexer_kit_core/src/format.rs +599 -0
- data/crates/lexer_kit_core/src/lib.rs +18 -0
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/opcodes.rs +375 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/safety_test.rs +21 -16
- data/crates/lexer_kit_core/src/token_buffer.rs +130 -0
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/trie.rs +37 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/types.rs +1 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/vm.rs +165 -2
- data/ext/lexer_kit_rust/Cargo.toml +7 -3
- data/ext/lexer_kit_rust/src/fast_stream.rs +101 -438
- data/ext/lexer_kit_rust/src/lib.rs +200 -215
- data/lib/lexer_kit/builder/compiler.rb +50 -15
- data/lib/lexer_kit/builder/conflict_detector.rb +18 -20
- data/lib/lexer_kit/builder/validator.rb +45 -0
- data/lib/lexer_kit/builder.rb +34 -7
- data/lib/lexer_kit/cli/commands.rb +17 -7
- data/lib/lexer_kit/core/source.rb +3 -2
- data/lib/lexer_kit/debug/disassembler.rb +0 -2
- data/lib/lexer_kit/dfa/dfa_builder.rb +1 -1
- data/lib/lexer_kit/dfa/dfa_minimizer.rb +2 -2
- data/lib/lexer_kit/dfa/regex_ast.rb +4 -0
- data/lib/lexer_kit/dfa/regex_parser.rb +41 -8
- data/lib/lexer_kit/errors.rb +2 -2
- data/lib/lexer_kit/format/lkb1.rb +3 -3
- data/lib/lexer_kit/format/lkt1.rb +3 -1
- data/lib/lexer_kit/format.rb +4 -4
- data/lib/lexer_kit/ir/compiled_program.rb +39 -26
- data/lib/lexer_kit/ir/constant_pool.rb +33 -11
- data/lib/lexer_kit/ir/dfa_table.rb +9 -19
- data/lib/lexer_kit/ir/instruction.rb +3 -0
- data/lib/lexer_kit/ir/jump_table.rb +3 -13
- data/lib/lexer_kit/ir/keyword_table.rb +0 -9
- data/lib/lexer_kit/ir/limits.rb +48 -0
- data/lib/lexer_kit/ir/serializer.rb +69 -30
- data/lib/lexer_kit/ir.rb +1 -0
- data/lib/lexer_kit/version.rb +1 -1
- data/lib/lexer_kit.rb +15 -2
- data/vendor/nupur/Cargo.toml +24 -0
- data/vendor/nupur/LICENSE +176 -0
- data/vendor/nupur/NOTICE +64 -0
- data/vendor/nupur/README.ja.md +150 -0
- data/vendor/nupur/README.md +257 -0
- data/vendor/nupur/src/abi.rs +143 -0
- data/vendor/nupur/src/args.rs +318 -0
- data/vendor/nupur/src/build.rs +101 -0
- data/vendor/nupur/src/caught.rs +171 -0
- data/vendor/nupur/src/cname.rs +37 -0
- data/vendor/nupur/src/describe.rs +175 -0
- data/vendor/nupur/src/encoding.rs +240 -0
- data/vendor/nupur/src/gvl.rs +181 -0
- data/vendor/nupur/src/hash.rs +52 -0
- data/vendor/nupur/src/inject.rs +20 -0
- data/vendor/nupur/src/lib.rs +280 -0
- data/vendor/nupur/src/lint_probe.rs +142 -0
- data/vendor/nupur/src/msg.rs +193 -0
- data/vendor/nupur/src/no_unwind.rs +39 -0
- data/vendor/nupur/src/raw/check.rs +71 -0
- data/vendor/nupur/src/raw/data.rs +28 -0
- data/vendor/nupur/src/raw/define.rs +215 -0
- data/vendor/nupur/src/raw/exception.rs +69 -0
- data/vendor/nupur/src/raw/iterate.rs +115 -0
- data/vendor/nupur/src/raw/mod.rs +105 -0
- data/vendor/nupur/src/raw/protect.rs +144 -0
- data/vendor/nupur/src/raw/string.rs +148 -0
- data/vendor/nupur/src/raw/symbol.rs +38 -0
- data/vendor/nupur/src/raw/values.rs +293 -0
- data/vendor/nupur/src/rb/call.rs +118 -0
- data/vendor/nupur/src/rb/class.rs +170 -0
- data/vendor/nupur/src/rb/convert.rs +134 -0
- data/vendor/nupur/src/rb/error.rs +355 -0
- data/vendor/nupur/src/rb/global.rs +141 -0
- data/vendor/nupur/src/rb/kept.rs +55 -0
- data/vendor/nupur/src/rb/method/frame.rs +81 -0
- data/vendor/nupur/src/rb/method.rs +468 -0
- data/vendor/nupur/src/rb/mod.rs +40 -0
- data/vendor/nupur/src/rb/object.rs +66 -0
- data/vendor/nupur/src/rb/ruby.rs +107 -0
- data/vendor/nupur/src/rb/value/header.rs +65 -0
- data/vendor/nupur/src/rb/value/id.rs +61 -0
- data/vendor/nupur/src/rb/value/integer.rs +132 -0
- data/vendor/nupur/src/rb/value.rs +454 -0
- data/vendor/nupur/src/stack.rs +32 -0
- data/vendor/nupur/src/string/make.rs +234 -0
- data/vendor/nupur/src/string/mod.rs +24 -0
- data/vendor/nupur/src/string/read.rs +411 -0
- data/vendor/nupur/src/table.rs +58 -0
- data/vendor/nupur/src/typed/callbacks.rs +125 -0
- data/vendor/nupur/src/typed/data_type.rs +132 -0
- data/vendor/nupur/src/typed/embedded.rs +103 -0
- data/vendor/nupur/src/typed/external.rs +76 -0
- data/vendor/nupur/src/typed/hidden.rs +95 -0
- data/vendor/nupur/src/typed/mod.rs +373 -0
- data/vendor/nupur/src/utf8_copy.rs +262 -0
- data/vendor/nupur/sys/Cargo.toml +29 -0
- data/vendor/nupur/sys/src/data_type.rs +213 -0
- data/vendor/nupur/sys/src/int.rs +248 -0
- data/vendor/nupur/sys/src/lib.rs +61 -0
- data/vendor/nupur/sys/src/lint_probe.rs +93 -0
- data/vendor/nupur/sys/src/no_unwind.rs +99 -0
- data/vendor/nupur/sys/src/non_raising.rs +585 -0
- data/vendor/nupur/sys/src/protect.rs +349 -0
- data/vendor/nupur/sys/src/raising.rs +257 -0
- data/vendor/nupur/sys/src/value.rs +279 -0
- data/vendor/nupur.sha256 +68 -0
- metadata +92 -12
- data/ext/lexer_kit_rust/src/deserializer.rs +0 -213
- data/ext/lexer_kit_rust/src/dfa.rs +0 -217
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
//! Making a Ruby String: a copy of some text ([`utf8_str`]) or of bytes
|
|
2
|
+
//! the caller holds to be UTF-8 ([`utf8_str_trusting`]), one written
|
|
3
|
+
//! in place front to back ([`utf8_str_filled`]) - from several slices at once
|
|
4
|
+
//! ([`utf8_str_from_slices`]) - and a frozen, interned name
|
|
5
|
+
//! ([`interned_utf8_trusting`]).
|
|
6
|
+
|
|
7
|
+
#![allow(unsafe_code)]
|
|
8
|
+
|
|
9
|
+
use crate::rb::value::AsSys;
|
|
10
|
+
use crate::rb::{Error, RString, Ruby};
|
|
11
|
+
|
|
12
|
+
/// A UTF-8 String holding a copy of `text`; a failed allocation is `Err`
|
|
13
|
+
/// (`NoMemoryError`).
|
|
14
|
+
///
|
|
15
|
+
/// A `&str` is UTF-8 by its type, so the String is marked so (its coderange
|
|
16
|
+
/// `7BIT` or `VALID`): Ruby never scans it to find out. A reader with bytes
|
|
17
|
+
/// it has checked has a `&str` of them ([`crate::utf8_copy::Utf8Copy`]'s
|
|
18
|
+
/// `as_str`, `core::str::from_utf8`); bytes it has not are
|
|
19
|
+
/// [`utf8_str_trusting`]'s.
|
|
20
|
+
pub fn utf8_str(ruby: &Ruby, text: &str) -> Result<RString, Error> {
|
|
21
|
+
let s = crate::raw::utf8_str_new(ruby, text.as_bytes())?;
|
|
22
|
+
// SAFETY: `s` was made just now from `text`'s bytes and is referenced
|
|
23
|
+
// only from this frame; a `&str` is valid UTF-8, all ASCII when
|
|
24
|
+
// `is_ascii` says so.
|
|
25
|
+
unsafe { nupur_sys::non_raising::str_mark_coderange(s.as_sys(), text.is_ascii()) };
|
|
26
|
+
Ok(s)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// A UTF-8 String holding a copy of `bytes`, which the caller holds to be
|
|
30
|
+
/// UTF-8 by some invariant of its own and does not check (the name says
|
|
31
|
+
/// so, as [`nupur_sys::non_raising`]'s names say their preconditions). A
|
|
32
|
+
/// failed allocation is `Err` (`NoMemoryError`).
|
|
33
|
+
///
|
|
34
|
+
/// The String is tagged UTF-8 and its coderange left unknown, so Ruby
|
|
35
|
+
/// scans it when it first needs to know: bytes that were not UTF-8 make a
|
|
36
|
+
/// String Ruby reports broken (`valid_encoding?` false), never a memory
|
|
37
|
+
/// error and never a String marked valid that is not.
|
|
38
|
+
pub fn utf8_str_trusting(ruby: &Ruby, bytes: &[u8]) -> Result<RString, Error> {
|
|
39
|
+
crate::raw::utf8_str_new(ruby, bytes)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// An ASCII-8BIT String holding a copy of `bytes` - a hash, a key, bytes
|
|
43
|
+
/// that are not text; a failed allocation is `Err` (`NoMemoryError`). Any
|
|
44
|
+
/// bytes are valid in it, so nothing is checked.
|
|
45
|
+
pub fn binary_str(ruby: &Ruby, bytes: &[u8]) -> Result<RString, Error> {
|
|
46
|
+
crate::raw::binary_str_new(ruby, bytes)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// A UTF-8 String of exactly `len` bytes, written by `fill` straight into
|
|
50
|
+
/// the new String's buffer - one allocation, no intermediate copy. The
|
|
51
|
+
/// String's allocation raises `NoMemoryError`; `fill`'s `Err` is returned in
|
|
52
|
+
/// its place, as is a `fill` that wrote fewer than `len` bytes - an internal
|
|
53
|
+
/// error, since the bytes left would be whatever the allocation held - and
|
|
54
|
+
/// the String is emptied and left to the GC, hidden.
|
|
55
|
+
///
|
|
56
|
+
/// `fill` writes through an [`Unwritten`], front to back, so every byte the
|
|
57
|
+
/// String holds was written and none past its end can be. The String is
|
|
58
|
+
/// HIDDEN (`rb_obj_hide`) from its allocation until it is whole, so no Ruby
|
|
59
|
+
/// code `fill` runs can find it through `ObjectSpace` - to read the bytes not
|
|
60
|
+
/// yet written, or to grow it and move the buffer `fill` writes into - and
|
|
61
|
+
/// this frame keeps it alive and in place meanwhile (the GC's stack scan pins
|
|
62
|
+
/// it). Shown, as a String, only once it is whole.
|
|
63
|
+
///
|
|
64
|
+
/// The bytes are tagged UTF-8 without a check; bytes that were not would make
|
|
65
|
+
/// a wrong String, never a memory error.
|
|
66
|
+
pub fn utf8_str_filled(
|
|
67
|
+
ruby: &Ruby,
|
|
68
|
+
len: usize,
|
|
69
|
+
fill: impl FnOnce(&mut Unwritten<'_>) -> Result<(), Error>,
|
|
70
|
+
) -> Result<RString, Error> {
|
|
71
|
+
// SAFETY: filled below, or emptied by `EmptyUnlessFilled` on every other
|
|
72
|
+
// way out, before Ruby code can see it.
|
|
73
|
+
let str = unsafe { crate::raw::utf8_str_unwritten(ruby, len) }?;
|
|
74
|
+
// SAFETY: `str` is the String just made, of `len` bytes (`rstring_ptr`
|
|
75
|
+
// is its buffer, the room `rb_str_new` allocated), referenced only from
|
|
76
|
+
// this frame. Seen as `MaybeUninit`, so nothing reads it unwritten.
|
|
77
|
+
let buf: &mut [core::mem::MaybeUninit<u8>] = unsafe {
|
|
78
|
+
let dst =
|
|
79
|
+
nupur_sys::non_raising::rstring_ptr(str.as_sys()) as *mut core::mem::MaybeUninit<u8>;
|
|
80
|
+
if len == 0 || dst.is_null() {
|
|
81
|
+
&mut []
|
|
82
|
+
} else {
|
|
83
|
+
core::slice::from_raw_parts_mut(dst, len)
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/* Armed before `fill` runs, so whatever ends it early - an `Err`, or a
|
|
87
|
+
* panic unwinding through this frame to the trampoline - empties the
|
|
88
|
+
* String on the way out; disarmed only once the String is whole. */
|
|
89
|
+
// SAFETY: the String just made, referenced only from this frame; hiding
|
|
90
|
+
// writes only its class field, which the reveal below restores.
|
|
91
|
+
unsafe { crate::rb::object::obj_hide(crate::rb::ReprValue::as_value(str)) };
|
|
92
|
+
let unfilled = EmptyUnlessFilled(str);
|
|
93
|
+
let mut w = Unwritten { buf, at: 0 };
|
|
94
|
+
let filled = fill(&mut w).and_then(|()| {
|
|
95
|
+
if w.at == len {
|
|
96
|
+
Ok(())
|
|
97
|
+
} else {
|
|
98
|
+
Err(crate::rb::error::internal_error(
|
|
99
|
+
"a String was left part-written",
|
|
100
|
+
))
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
filled?;
|
|
104
|
+
core::mem::forget(unfilled);
|
|
105
|
+
/* Whole now: shown as a String. A refusal (out of memory) leaves it
|
|
106
|
+
* hidden and filled, for the GC. */
|
|
107
|
+
crate::raw::obj_reveal(
|
|
108
|
+
crate::rb::ReprValue::as_value(str),
|
|
109
|
+
crate::rb::ReprValue::as_value(ruby.class_string()),
|
|
110
|
+
)?;
|
|
111
|
+
Ok(str)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Empties, when dropped, a String [`utf8_str_filled`] has not finished
|
|
115
|
+
/// filling: the String is left to the GC, but `ObjectSpace` can still hand it
|
|
116
|
+
/// to Ruby code until then, so it must not carry the bytes it was never
|
|
117
|
+
/// given - whatever its allocation held before. Empty, it holds none. A
|
|
118
|
+
/// `Drop`, so a panic out of `fill` empties it as an `Err` does; forgotten
|
|
119
|
+
/// once the String is whole.
|
|
120
|
+
struct EmptyUnlessFilled(RString);
|
|
121
|
+
|
|
122
|
+
impl Drop for EmptyUnlessFilled {
|
|
123
|
+
#[cfg_attr(
|
|
124
|
+
dylint_lib = "nupur_lints",
|
|
125
|
+
allow(
|
|
126
|
+
ffi_without_gvl_proof,
|
|
127
|
+
reason = "it guards the String `utf8_str_filled` made, with its token, and lives only in that frame"
|
|
128
|
+
)
|
|
129
|
+
)]
|
|
130
|
+
fn drop(&mut self) {
|
|
131
|
+
/* Run while a panic unwinds, too, where a second panic aborts. */
|
|
132
|
+
crate::no_unwind::must_not_unwind::<crate::no_unwind::DropUnfilled, _>(|| {
|
|
133
|
+
// SAFETY: the String just made, unfrozen and referenced only
|
|
134
|
+
// from `utf8_str_filled`'s frame.
|
|
135
|
+
unsafe { nupur_sys::non_raising::str_empty_unfrozen(self.0.as_sys()) };
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// The buffer of a String [`utf8_str_filled`] is making, written front to
|
|
141
|
+
/// back: the bytes before `at` are written, the rest are not and cannot be
|
|
142
|
+
/// read.
|
|
143
|
+
pub struct Unwritten<'a> {
|
|
144
|
+
buf: &'a mut [core::mem::MaybeUninit<u8>],
|
|
145
|
+
at: usize,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
impl Unwritten<'_> {
|
|
149
|
+
/// Append `src`; `false`, with nothing written, when it does not fit.
|
|
150
|
+
#[inline]
|
|
151
|
+
pub fn push(&mut self, src: &[u8]) -> bool {
|
|
152
|
+
let Some(dst) = self
|
|
153
|
+
.at
|
|
154
|
+
.checked_add(src.len())
|
|
155
|
+
.and_then(|end| self.buf.get_mut(self.at..end))
|
|
156
|
+
else {
|
|
157
|
+
return false;
|
|
158
|
+
};
|
|
159
|
+
// SAFETY: `u8` and `MaybeUninit<u8>` have one layout, and every `u8`
|
|
160
|
+
// is a valid `MaybeUninit<u8>`; the view is only read.
|
|
161
|
+
let src: &[core::mem::MaybeUninit<u8>] =
|
|
162
|
+
unsafe { &*(src as *const [u8] as *const [core::mem::MaybeUninit<u8>]) };
|
|
163
|
+
copy_small(dst, src);
|
|
164
|
+
self.at += src.len();
|
|
165
|
+
true
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/// `dst.copy_from_slice(src)` for slices of one length, with no `memcpy`
|
|
170
|
+
/// call for 16 elements or fewer: two fixed-size copies that overlap. Text
|
|
171
|
+
/// slices are mostly a few bytes, and a `memcpy` call each measured
|
|
172
|
+
/// `doc.text` ~50% slower. The extension's `ceiling_buf::copy_small`, token for
|
|
173
|
+
/// token, which Verus proves (`verus/ceiling_buf.rs`); `rake verus:sync` holds this
|
|
174
|
+
/// copy to it too, since this crate cannot depend on the extension.
|
|
175
|
+
#[inline(always)]
|
|
176
|
+
#[allow(
|
|
177
|
+
clippy::indexing_slicing,
|
|
178
|
+
reason = "dst and src are one length, at least K"
|
|
179
|
+
)]
|
|
180
|
+
fn copy_small<T: Copy>(dst: &mut [T], src: &[T]) {
|
|
181
|
+
#[inline(always)]
|
|
182
|
+
fn two<const K: usize, T: Copy>(dst: &mut [T], src: &[T]) {
|
|
183
|
+
let n = src.len();
|
|
184
|
+
dst[..K].copy_from_slice(&src[..K]);
|
|
185
|
+
dst[n - K..n].copy_from_slice(&src[n - K..]);
|
|
186
|
+
}
|
|
187
|
+
match src.len() {
|
|
188
|
+
0 => {}
|
|
189
|
+
1 => dst[0] = src[0],
|
|
190
|
+
2..=3 => two::<2, T>(dst, src),
|
|
191
|
+
4..=7 => two::<4, T>(dst, src),
|
|
192
|
+
8..=16 => two::<8, T>(dst, src),
|
|
193
|
+
_ => dst.copy_from_slice(src),
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// Join `slices`, totalling `total` bytes, into one UTF-8 String: one
|
|
198
|
+
/// allocation of exactly `total` and one copy run into it
|
|
199
|
+
/// ([`utf8_str_filled`]), with no intermediate buffer.
|
|
200
|
+
///
|
|
201
|
+
/// `total` is the caller's bookkeeping, and is held to it both ways: a slice
|
|
202
|
+
/// that would run past it, and a sum that falls short of it, are an internal
|
|
203
|
+
/// error rather than a String past or short of its allocation. The bytes are
|
|
204
|
+
/// tagged UTF-8 without a check; bytes that were not would make a wrong
|
|
205
|
+
/// String, never a memory error.
|
|
206
|
+
pub fn utf8_str_from_slices<'a>(
|
|
207
|
+
ruby: &Ruby,
|
|
208
|
+
slices: impl Iterator<Item = &'a [u8]>,
|
|
209
|
+
total: usize,
|
|
210
|
+
) -> Result<RString, Error> {
|
|
211
|
+
utf8_str_filled(ruby, total, |out| {
|
|
212
|
+
for s in slices {
|
|
213
|
+
/* `push` writes nothing past the String's end. */
|
|
214
|
+
if !out.push(s) {
|
|
215
|
+
return Err(crate::rb::error::internal_error(
|
|
216
|
+
"a String's slices ran past their total",
|
|
217
|
+
));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/* A short sum is `utf8_str_filled`'s to refuse. */
|
|
221
|
+
Ok(())
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// A frozen, deduplicated UTF-8 String of `bytes` - Ruby's own `-"name"`
|
|
226
|
+
/// (`rb_enc_interned_str`), so every read of one name answers the same
|
|
227
|
+
/// object and allocates nothing once Ruby has it. For names, never for
|
|
228
|
+
/// character data a caller may expect to edit. `bytes` are the caller's to
|
|
229
|
+
/// hold UTF-8 (the name says so, as [`utf8_str_trusting`]'s does): they are
|
|
230
|
+
/// copied unchecked, and bytes that were not would make a wrong String,
|
|
231
|
+
/// never a memory error.
|
|
232
|
+
pub fn interned_utf8_trusting(ruby: &Ruby, bytes: &[u8]) -> Result<RString, Error> {
|
|
233
|
+
crate::raw::enc_interned_str(bytes, crate::encoding::Encoding::utf8(ruby))
|
|
234
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//! A Ruby String's bytes, read and written by copying - but for two loans
|
|
2
|
+
//! of its bytes while nothing can change them.
|
|
3
|
+
//!
|
|
4
|
+
//! Reading (`read`) is [`RString::copy_to`](crate::rb::RString::copy_to)
|
|
5
|
+
//! and [`RString::append_to`](crate::rb::RString::append_to), each a read and
|
|
6
|
+
//! a copy with nothing run between, so nothing Ruby does afterwards - a GC,
|
|
7
|
+
//! the String rewritten or grown - reaches what the caller holds; as text,
|
|
8
|
+
//! [`read_utf8`], as bytes whatever the encoding, [`read_bytes`]. The loans
|
|
9
|
+
//! hand a slice to a closure for the length of its call: `with_bytes`'s
|
|
10
|
+
//! closure can touch no Ruby at all, and `with_locked_bytes`'s String is
|
|
11
|
+
//! frozen or locked until it returns. Making one
|
|
12
|
+
//! (`make`) is a copy - of text, marked valid ([`utf8_str`]), of bytes the
|
|
13
|
+
//! caller holds to be UTF-8 ([`utf8_str_trusting`]), or ASCII-8BIT
|
|
14
|
+
//! ([`binary_str`]) - or a String written in place front to back through an
|
|
15
|
+
//! [`Unwritten`].
|
|
16
|
+
|
|
17
|
+
mod make;
|
|
18
|
+
mod read;
|
|
19
|
+
|
|
20
|
+
pub use make::{
|
|
21
|
+
binary_str, interned_utf8_trusting, utf8_str, utf8_str_filled, utf8_str_from_slices,
|
|
22
|
+
utf8_str_trusting, Unwritten,
|
|
23
|
+
};
|
|
24
|
+
pub use read::{read_bytes, read_utf8, read_utf8_within, to_utf8, NoRoom, ReadError, Transcode};
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
//! Reading a Ruby String: by copying ([`RString::copy_to`],
|
|
2
|
+
//! [`RString::append_to`]), and as text - in its own encoding, transcoded to
|
|
3
|
+
//! UTF-8 where it is not read as UTF-8 bytes already, and checked to be UTF-8
|
|
4
|
+
//! on a copy ([`read_utf8`]). A slice of a String is handed out only on loan,
|
|
5
|
+
//! to a closure, while nothing can change it ([`RString::with_bytes`],
|
|
6
|
+
//! [`RString::with_locked_bytes`]).
|
|
7
|
+
|
|
8
|
+
#![allow(unsafe_code)]
|
|
9
|
+
|
|
10
|
+
use crate::encoding::{Encoding, Unconvertible};
|
|
11
|
+
use crate::rb::value::AsSys;
|
|
12
|
+
use crate::rb::{Error, RString, Ruby};
|
|
13
|
+
|
|
14
|
+
/// [`RString::append_to`]'s refusal: the buffer had too little spare room.
|
|
15
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
16
|
+
pub struct NoRoom;
|
|
17
|
+
|
|
18
|
+
/* ---- copying a String's bytes out ---- */
|
|
19
|
+
|
|
20
|
+
impl RString {
|
|
21
|
+
/// Copy the bytes from `offset` (none past the end) into `dst`, as many
|
|
22
|
+
/// as both hold, and say how many.
|
|
23
|
+
///
|
|
24
|
+
/// The String's buffer is read and copied out of in one step, with
|
|
25
|
+
/// nothing run in between, and no slice of it is handed out: a caller
|
|
26
|
+
/// owns what it reads, so nothing Ruby does afterwards - a GC, the String
|
|
27
|
+
/// rewritten or grown - can reach it.
|
|
28
|
+
#[inline]
|
|
29
|
+
pub fn copy_to(self, offset: usize, dst: &mut [u8]) -> usize {
|
|
30
|
+
// SAFETY: read and copied out at once; nothing runs while it is held.
|
|
31
|
+
let src = unsafe { self.as_slice() }.get(offset..).unwrap_or(&[]);
|
|
32
|
+
let n = src.len().min(dst.len());
|
|
33
|
+
if let (Some(d), Some(s)) = (dst.get_mut(..n), src.get(..n)) {
|
|
34
|
+
d.copy_from_slice(s);
|
|
35
|
+
}
|
|
36
|
+
n
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Append the bytes from `offset` (none past the end) to `v`, whose spare
|
|
40
|
+
/// capacity must already hold them - the caller reserved it, fallibly -
|
|
41
|
+
/// and say how many. Nothing is allocated here: when the room is short,
|
|
42
|
+
/// `v` is left as it was and the answer is [`NoRoom`]. The read is
|
|
43
|
+
/// [`copy_to`](Self::copy_to)'s, in one step after the room is checked.
|
|
44
|
+
#[inline]
|
|
45
|
+
pub fn append_to(self, offset: usize, v: &mut Vec<u8>) -> Result<usize, NoRoom> {
|
|
46
|
+
// SAFETY: as `copy_to` - read and copied out at once.
|
|
47
|
+
let src = unsafe { self.as_slice() }.get(offset..).unwrap_or(&[]);
|
|
48
|
+
if v.capacity() - v.len() < src.len() {
|
|
49
|
+
return Err(NoRoom);
|
|
50
|
+
}
|
|
51
|
+
#[allow(
|
|
52
|
+
clippy::disallowed_methods,
|
|
53
|
+
reason = "the room was checked above, so it cannot grow"
|
|
54
|
+
)]
|
|
55
|
+
v.extend_from_slice(src);
|
|
56
|
+
Ok(src.len())
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/* ---- the String's encoding, as a reader takes it ---- */
|
|
60
|
+
|
|
61
|
+
/// Whether this String's text is read as UTF-8 bytes with no transcode -
|
|
62
|
+
/// its encoding UTF-8, US-ASCII or ASCII-8BIT
|
|
63
|
+
/// (`Encoding::is_utf8_ascii_or_binary`) - asked of the String itself, by
|
|
64
|
+
/// index and with no call on the common path: the index is read from the String's
|
|
65
|
+
/// flags, where Ruby keeps it inline for every encoding below
|
|
66
|
+
/// `RUBY_ENCODING_INLINE_MAX` (the builtin three are 0-2), and compared
|
|
67
|
+
/// with the builtin indices (`encoding`'s one table of them). Every strict read asks, so it
|
|
68
|
+
/// is on the hot path: `rb_enc_get` + `rb_utf8_encoding` cost Makiri's
|
|
69
|
+
/// `Node#[]` ~13%.
|
|
70
|
+
#[inline]
|
|
71
|
+
pub fn reads_as_utf8_bytes(self) -> bool {
|
|
72
|
+
crate::encoding::reads_as_utf8_index(self.encoding_index())
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// Whether this String is ASCII-8BIT, asked as
|
|
76
|
+
/// [`reads_as_utf8_bytes`](Self::reads_as_utf8_bytes) asks: from its
|
|
77
|
+
/// flags, with no call. A reader that takes UTF-8 and US-ASCII as text
|
|
78
|
+
/// but binary only when it is ASCII tells the two apart with it.
|
|
79
|
+
#[inline]
|
|
80
|
+
pub fn is_binary(self) -> bool {
|
|
81
|
+
crate::encoding::is_ascii8bit_index(self.encoding_index())
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// Whether Ruby has already found this String valid UTF-8, from its
|
|
85
|
+
/// cached coderange: a read of its flags, which never scans and never
|
|
86
|
+
/// allocates - a String not scanned yet answers `false`, which
|
|
87
|
+
/// [`scanned_utf8`](Self::scanned_utf8) would scan to answer. Only a hint - for code that stays safe whatever it says (a
|
|
88
|
+
/// reader that would otherwise repair or check the bytes itself). A wrong
|
|
89
|
+
/// coderange (another C extension's, a Ruby bug) must never decide what a
|
|
90
|
+
/// `&str` holds: that is [`crate::utf8_copy::Utf8Copy`]'s own check.
|
|
91
|
+
#[inline]
|
|
92
|
+
pub fn cached_utf8(self) -> bool {
|
|
93
|
+
match self.enc_coderange() {
|
|
94
|
+
/* Every byte < 0x80 in an ASCII-compatible encoding. */
|
|
95
|
+
crate::rb::value::Coderange::SevenBit => true,
|
|
96
|
+
/* Valid for its own encoding, which has to be UTF-8 for that to
|
|
97
|
+
* mean valid UTF-8 - asked by index, from the flags. */
|
|
98
|
+
crate::rb::value::Coderange::Valid => {
|
|
99
|
+
crate::encoding::is_utf8_index(self.encoding_index())
|
|
100
|
+
}
|
|
101
|
+
_ => false,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/* ---- lending a String's bytes while nothing can change them ---- */
|
|
107
|
+
|
|
108
|
+
impl RString {
|
|
109
|
+
/// The String's bytes, lent to `f` for the length of the call: one of
|
|
110
|
+
/// the two ways the layer hands out a slice of a String, for a reader that must
|
|
111
|
+
/// not pay for a copy (a JSON generator escaping as it reads).
|
|
112
|
+
///
|
|
113
|
+
/// `f` is `Send`, so it can hold no Ruby value and no GVL token - neither
|
|
114
|
+
/// is `Send` - and so it can run no Ruby code, make no Ruby object and
|
|
115
|
+
/// reach no Ruby value, this String included: nothing can grow, shrink,
|
|
116
|
+
/// move or free the buffer while it is lent. The String itself is kept
|
|
117
|
+
/// alive, and in place, by this frame, which holds it until `f` returns.
|
|
118
|
+
/// What `f` answers cannot borrow the slice. `rake dylint` holds `f`'s
|
|
119
|
+
/// body as it holds a GVL-released one (`ruby_in_gvl_released_body`).
|
|
120
|
+
#[inline]
|
|
121
|
+
pub fn with_bytes<R>(self, f: impl FnOnce(&[u8]) -> R + Send) -> R {
|
|
122
|
+
// SAFETY: the slice lives for `f`'s call alone, and nothing that runs
|
|
123
|
+
// meanwhile can touch Ruby (above); `self` is a live String.
|
|
124
|
+
let r = f(unsafe { self.as_slice() });
|
|
125
|
+
nupur_sys::value::keep_alive(self.as_sys());
|
|
126
|
+
r
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
impl RString {
|
|
131
|
+
/// The String's bytes, lent to `f` while the String cannot change: the
|
|
132
|
+
/// other way a slice is handed out, for
|
|
133
|
+
/// a reader that makes Ruby objects as it goes (a JSON parser), and so
|
|
134
|
+
/// cannot take [`with_bytes`](Self::with_bytes), whose closure may not
|
|
135
|
+
/// touch Ruby.
|
|
136
|
+
///
|
|
137
|
+
/// A frozen String cannot change: Ruby refuses every change to it, so
|
|
138
|
+
/// it is lent as it is. That is also the only kind another Ractor can
|
|
139
|
+
/// hold - a String shareable between Ractors is frozen - and so the
|
|
140
|
+
/// only kind two Ractors may read at once; nothing is written to it,
|
|
141
|
+
/// so they race on nothing. An unfrozen String, which only its own
|
|
142
|
+
/// Ractor can reach, is locked (`rb_str_locktmp`) for the loan: Ruby
|
|
143
|
+
/// then refuses every change to it (`String#<<`, `replace`, `clear`, ...
|
|
144
|
+
/// raise), whoever asks. Either way the String is kept alive, and in
|
|
145
|
+
/// place, by this frame, which the GC's stack scan sees, until `f`
|
|
146
|
+
/// returns; a lock is released on every way out, a panic included. An
|
|
147
|
+
/// unfrozen String already locked - by another reader, or by `f`
|
|
148
|
+
/// reading it again - is Ruby's `RuntimeError`, returned.
|
|
149
|
+
pub fn with_locked_bytes<R>(self, f: impl FnOnce(&[u8]) -> R) -> Result<R, Error> {
|
|
150
|
+
use crate::rb::ReprValue;
|
|
151
|
+
if self.is_frozen() {
|
|
152
|
+
// SAFETY: a frozen String's bytes never change, and this frame
|
|
153
|
+
// keeps it alive and in place until `f` returns.
|
|
154
|
+
let r = f(unsafe { self.as_slice() });
|
|
155
|
+
nupur_sys::value::keep_alive(self.as_sys());
|
|
156
|
+
return Ok(r);
|
|
157
|
+
}
|
|
158
|
+
crate::raw::str_locktmp(self)?;
|
|
159
|
+
let unlock = Unlock(self);
|
|
160
|
+
// SAFETY: the String is locked until `unlock` drops, after `f`, and
|
|
161
|
+
// live and in place on this frame meanwhile (above).
|
|
162
|
+
let r = f(unsafe { unlock.0.as_slice() });
|
|
163
|
+
drop(unlock);
|
|
164
|
+
Ok(r)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// Unlocks a String [`RString::with_locked_bytes`] locked, when dropped.
|
|
169
|
+
struct Unlock(RString);
|
|
170
|
+
|
|
171
|
+
impl Drop for Unlock {
|
|
172
|
+
#[cfg_attr(
|
|
173
|
+
dylint_lib = "nupur_lints",
|
|
174
|
+
allow(
|
|
175
|
+
ffi_without_gvl_proof,
|
|
176
|
+
reason = "it guards the String `with_locked_bytes` locked, with the String as its proof, and lives only in that frame"
|
|
177
|
+
)
|
|
178
|
+
)]
|
|
179
|
+
fn drop(&mut self) {
|
|
180
|
+
/* Run while a panic unwinds, too, where a second panic aborts. Not
|
|
181
|
+
* a protected call, which refuses to run while an exit is pending
|
|
182
|
+
* and would leave the String locked: unlocking a String that is
|
|
183
|
+
* locked raises nothing (`str_unlocktmp_of_locked`). */
|
|
184
|
+
crate::no_unwind::must_not_unwind::<crate::no_unwind::DropUnlock, _>(|| {
|
|
185
|
+
// SAFETY: `Unlock` is made only right after the lock succeeded,
|
|
186
|
+
// and only this drop unlocks.
|
|
187
|
+
unsafe { nupur_sys::non_raising::str_unlocktmp_of_locked(self.0.as_sys()) };
|
|
188
|
+
nupur_sys::value::keep_alive(self.0.as_sys());
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/* ---- the String's UTF-8, as Ruby holds it ---- */
|
|
194
|
+
|
|
195
|
+
impl RString {
|
|
196
|
+
/// Whether Ruby holds this String to be valid UTF-8 (or ASCII in an
|
|
197
|
+
/// ASCII-compatible encoding): its cached coderange
|
|
198
|
+
/// ([`cached_utf8`](Self::cached_utf8)), and where none is cached yet,
|
|
199
|
+
/// Ruby's own scan - which can raise, hence the `Result` - whose answer Ruby then keeps in the
|
|
200
|
+
/// String - so a String is scanned once, however often it is asked
|
|
201
|
+
/// about. This trusts Ruby's validator and cache rather than checking
|
|
202
|
+
/// the bytes with std's: right for a writer whose output keeps the
|
|
203
|
+
/// String's bytes as they are (a JSON generator), never for making a
|
|
204
|
+
/// `&str`, which is `utf8_copy`'s.
|
|
205
|
+
#[inline]
|
|
206
|
+
pub fn scanned_utf8(self) -> Result<bool, Error> {
|
|
207
|
+
if self.cached_utf8() {
|
|
208
|
+
return Ok(true);
|
|
209
|
+
}
|
|
210
|
+
if !matches!(self.enc_coderange(), crate::rb::value::Coderange::Unknown) {
|
|
211
|
+
return Ok(false);
|
|
212
|
+
}
|
|
213
|
+
crate::raw::enc_str_coderange(self)?;
|
|
214
|
+
Ok(self.cached_utf8())
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/// What [`to_utf8`] made of a String.
|
|
219
|
+
#[allow(
|
|
220
|
+
clippy::large_enum_variant,
|
|
221
|
+
reason = "an Error holds its message inline (`crate::msg::Msg`), so it is never boxed"
|
|
222
|
+
)]
|
|
223
|
+
pub enum Transcode {
|
|
224
|
+
/// The String itself: its bytes are read as UTF-8 bytes already, and are
|
|
225
|
+
/// whatever they are - checking them is the reader's.
|
|
226
|
+
AsIs(RString),
|
|
227
|
+
/// The new String the transcode made (on this frame, where the GC keeps
|
|
228
|
+
/// it). Under [`Unconvertible::Replace`] it is valid UTF-8, every
|
|
229
|
+
/// invalid or unmappable sequence replaced.
|
|
230
|
+
Transcoded(RString),
|
|
231
|
+
/// The String's own fault: the transcode raised an `EncodingError` - no
|
|
232
|
+
/// converter, an invalid byte sequence, a character with no UTF-8 form
|
|
233
|
+
/// under [`Unconvertible::Raise`]. Handled: the caller's `$!` is as it
|
|
234
|
+
/// was, and the exception is Ruby's own, to word another error with, to
|
|
235
|
+
/// raise as it is, or to drop - it is an exception the String caused,
|
|
236
|
+
/// never an exit, so dropping it loses nothing.
|
|
237
|
+
Fault(Error),
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/// `s` as UTF-8 text, read as `read_as`'s bytes - the String's own encoding
|
|
241
|
+
/// for `None` - and transcoded by Ruby where that encoding is not read as
|
|
242
|
+
/// UTF-8 bytes already (UTF-8, US-ASCII, ASCII-8BIT), `on` deciding what an
|
|
243
|
+
/// unconvertible sequence becomes.
|
|
244
|
+
///
|
|
245
|
+
/// The one place a String's transcode is classified: an `EncodingError` is
|
|
246
|
+
/// the String's fault ([`Transcode::Fault`]), handled here with the caller's
|
|
247
|
+
/// `$!` put back; anything else - `NoMemoryError`, an interrupt, every exit,
|
|
248
|
+
/// which no class names - is `Err`, to be passed on. A String already read as
|
|
249
|
+
/// UTF-8 bytes costs a read of its flags (`read_as` `None`) or one encoding
|
|
250
|
+
/// comparison: no protected call, no call into libruby at all.
|
|
251
|
+
pub fn to_utf8(
|
|
252
|
+
ruby: &Ruby,
|
|
253
|
+
s: RString,
|
|
254
|
+
read_as: Option<Encoding>,
|
|
255
|
+
on: Unconvertible,
|
|
256
|
+
) -> Result<Transcode, Error> {
|
|
257
|
+
let as_utf8 = match read_as {
|
|
258
|
+
None => s.reads_as_utf8_bytes(),
|
|
259
|
+
Some(enc) => enc.is_utf8_ascii_or_binary(),
|
|
260
|
+
};
|
|
261
|
+
if as_utf8 {
|
|
262
|
+
return Ok(Transcode::AsIs(s));
|
|
263
|
+
}
|
|
264
|
+
/* `$!` is read and put back only here, where a transcode runs: it costs
|
|
265
|
+
* a call into libruby, and a raise that is passed on replaces it anyway. */
|
|
266
|
+
let made = crate::raw::keeping_errinfo(|| {
|
|
267
|
+
let input = match read_as {
|
|
268
|
+
Some(enc) if enc != Encoding::of(s) => enc.relabel(s)?,
|
|
269
|
+
_ => s,
|
|
270
|
+
};
|
|
271
|
+
Encoding::utf8(ruby).encode(input, on)
|
|
272
|
+
});
|
|
273
|
+
match made {
|
|
274
|
+
Ok(utf8) => Ok(Transcode::Transcoded(utf8)),
|
|
275
|
+
Err(e) if e.is_kind_of(ruby, crate::rb::Builtin::EncodingError) => Ok(Transcode::Fault(e)),
|
|
276
|
+
Err(e) => Err(e),
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/* ---- reading a String's bytes as they are ---- */
|
|
281
|
+
|
|
282
|
+
/// `s`'s bytes, copied out as they are, whatever the String's encoding - a
|
|
283
|
+
/// password, a key, a blob: bytes that are not text and are not checked as
|
|
284
|
+
/// any. The one allocation is fallible (`NoMemoryError`, which the OOM sweep
|
|
285
|
+
/// can inject), and the copy is [`RString::append_to`]'s, so nothing Ruby
|
|
286
|
+
/// does afterwards reaches it. The caller owns the `Vec`, and so decides
|
|
287
|
+
/// what becomes of a secret in it (zeroing it, say).
|
|
288
|
+
pub fn read_bytes(s: RString) -> Result<Vec<u8>, Error> {
|
|
289
|
+
let len = s.len();
|
|
290
|
+
let mut v = Vec::new();
|
|
291
|
+
if !crate::utf8_copy::reserve_exact(&mut v, len) {
|
|
292
|
+
return Err(Error::new(
|
|
293
|
+
crate::rb::Builtin::NoMemoryError,
|
|
294
|
+
"failed to allocate memory",
|
|
295
|
+
));
|
|
296
|
+
}
|
|
297
|
+
/* Nothing ran between the length read and the copy, so the room holds
|
|
298
|
+
* the String; a copy that fell short would hand back a truncated secret,
|
|
299
|
+
* which is an invariant broken, never a shorter answer. */
|
|
300
|
+
match s.append_to(0, &mut v) {
|
|
301
|
+
Ok(n) if n == len => Ok(v),
|
|
302
|
+
_ => Err(crate::rb::error::internal_error(
|
|
303
|
+
"a String's length changed under a copy",
|
|
304
|
+
)),
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* ---- reading a String as checked UTF-8 ---- */
|
|
309
|
+
|
|
310
|
+
/// Why [`read_utf8`] gave no copy.
|
|
311
|
+
#[allow(
|
|
312
|
+
clippy::large_enum_variant,
|
|
313
|
+
reason = "an Error holds its message inline (`crate::msg::Msg`), so it is never boxed"
|
|
314
|
+
)]
|
|
315
|
+
pub enum ReadError<P> {
|
|
316
|
+
/// The caller's own check turned the bytes down (a NUL).
|
|
317
|
+
Refused(P),
|
|
318
|
+
/// The UTF-8 is longer than the reader's cap ([`read_utf8_within`]).
|
|
319
|
+
TooLong,
|
|
320
|
+
/// The bytes are not UTF-8.
|
|
321
|
+
NotUtf8,
|
|
322
|
+
/// The String's encoding has no UTF-8 form for it: Ruby's transcode
|
|
323
|
+
/// raised an `EncodingError`.
|
|
324
|
+
NoUtf8Form,
|
|
325
|
+
/// The copy could not be allocated.
|
|
326
|
+
Oom,
|
|
327
|
+
/// Something not about the String cut the transcode short
|
|
328
|
+
/// (`NoMemoryError`, an interrupt, a `throw`), passed on as it was.
|
|
329
|
+
Raised(Error),
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/// `s`, read in its own encoding and copied as checked UTF-8: a String in
|
|
333
|
+
/// another encoding is transcoded first with no replacement ([`to_utf8`]),
|
|
334
|
+
/// the copy of what it became is put
|
|
335
|
+
/// to `check` - a reader's own rules, reported ahead of invalid UTF-8 - and
|
|
336
|
+
/// then checked to be UTF-8 by std's validator over the copy itself, never by
|
|
337
|
+
/// the String's cached coderange. Nothing Ruby does afterwards reaches the
|
|
338
|
+
/// copy.
|
|
339
|
+
pub fn read_utf8<P>(
|
|
340
|
+
ruby: &Ruby,
|
|
341
|
+
s: RString,
|
|
342
|
+
check: impl FnOnce(&[u8]) -> Option<P>,
|
|
343
|
+
) -> Result<crate::utf8_copy::Utf8Copy, ReadError<P>> {
|
|
344
|
+
read_utf8_within(ruby, s, usize::MAX, check)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/// [`read_utf8`] under a cap of `max_bytes` on the UTF-8 the String becomes
|
|
348
|
+
/// (a UTF-16 String is about twice its UTF-8 length, so the cap is measured
|
|
349
|
+
/// after the transcode). An over-long String is refused before it is copied,
|
|
350
|
+
/// and the copy is held to the cap again, ahead of `check`.
|
|
351
|
+
pub fn read_utf8_within<P>(
|
|
352
|
+
ruby: &Ruby,
|
|
353
|
+
s: RString,
|
|
354
|
+
max_bytes: usize,
|
|
355
|
+
check: impl FnOnce(&[u8]) -> Option<P>,
|
|
356
|
+
) -> Result<crate::utf8_copy::Utf8Copy, ReadError<P>> {
|
|
357
|
+
use crate::utf8_copy::{CopyError, FillError, Utf8Copy};
|
|
358
|
+
/* A transcode's UTF-8 is at least a quarter of its source - no encoding
|
|
359
|
+
* takes more than four bytes a character, nor UTF-8 fewer than one - so a
|
|
360
|
+
* String that cannot fit is refused before it is transcoded, whatever
|
|
361
|
+
* its size. (A stateful encoding's escapes make no character, so one
|
|
362
|
+
* padded with them past four times the cap is refused even so: the
|
|
363
|
+
* closed direction.) */
|
|
364
|
+
if s.len() / 4 > max_bytes {
|
|
365
|
+
return Err(ReadError::TooLong);
|
|
366
|
+
}
|
|
367
|
+
/* The common case, a String already read as UTF-8 bytes, asks its flags
|
|
368
|
+
* here and skips `to_utf8`'s `Result`, whose `Err` (an `Error`, its
|
|
369
|
+
* message inline) is a few hundred bytes to move on every read. */
|
|
370
|
+
let s = if s.reads_as_utf8_bytes() {
|
|
371
|
+
s
|
|
372
|
+
} else {
|
|
373
|
+
match to_utf8(ruby, s, None, Unconvertible::Raise).map_err(ReadError::Raised)? {
|
|
374
|
+
Transcode::AsIs(s) | Transcode::Transcoded(s) => s,
|
|
375
|
+
Transcode::Fault(_handled) => return Err(ReadError::NoUtf8Form),
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
if s.len() > max_bytes {
|
|
379
|
+
return Err(ReadError::TooLong);
|
|
380
|
+
}
|
|
381
|
+
let checks = |b: &[u8]| {
|
|
382
|
+
if b.len() > max_bytes {
|
|
383
|
+
Some(ReadError::TooLong)
|
|
384
|
+
} else {
|
|
385
|
+
check(b).map(ReadError::Refused)
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
Utf8Copy::from_source(&StrSource(s), checks).map_err(|e| match e {
|
|
389
|
+
FillError::Refused(r) => r,
|
|
390
|
+
FillError::Copy(CopyError::NotUtf8) => ReadError::NotUtf8,
|
|
391
|
+
FillError::Copy(CopyError::Oom) => ReadError::Oom,
|
|
392
|
+
})
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/// A live String as what a [`Utf8Copy`](crate::utf8_copy::Utf8Copy) copies
|
|
396
|
+
/// from: the copying reads, which hand no slice of the String out.
|
|
397
|
+
struct StrSource(RString);
|
|
398
|
+
|
|
399
|
+
impl crate::utf8_copy::Source for StrSource {
|
|
400
|
+
fn byte_len(&self) -> usize {
|
|
401
|
+
self.0.len()
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
fn copy_into(&self, dst: &mut [u8]) -> usize {
|
|
405
|
+
self.0.copy_to(0, dst)
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
fn append_into(&self, v: &mut Vec<u8>) -> bool {
|
|
409
|
+
self.0.append_to(0, v).is_ok()
|
|
410
|
+
}
|
|
411
|
+
}
|