pub struct Offsets { /* private fields */ }Expand description
Turns offsets into a decoded page into offsets into its bytes, and back, for the spans and parse errors of a document parsed from bytes.
use parsec_encoding::{Offsets, encoding_rs::SHIFT_JIS};
let page = b"<meta charset=shift_jis><p>\x93\xfa\x96\x7b<b>!</b>";
let (text, _, _) = SHIFT_JIS.decode(page);
let b = text.find("<b>").unwrap();
// 日本 is six bytes decoded, four in Shift_JIS.
assert_eq!(b, 33);
let offsets = Offsets::new(page, SHIFT_JIS);
let (start, end) = (offsets.to_source(b), offsets.to_source(b + 3));
assert_eq!(&page[start..end], b"<b>");With the default parse feature, the spans and errors of a document
from parse_bytes are offsets into the decoded
page in the same way.
It’s built by decoding the bytes again, noting where each character’s bytes started (UTF-8 and the single-byte encodings in one pass, the others a byte at a time, which takes two or three times as long as the parse), and keeps only the places where the two stop moving together: after the byte order mark, at each character whose length differs between the two (each Shift_JIS kanji, say), and after each run of bytes the decoding replaced with U+FFFD. ASCII costs nothing; text that’s all non-ASCII costs 8 bytes a character.
Implementations§
Source§impl Offsets
impl Offsets
Sourcepub fn new(bytes: &[u8], encoding: &'static Encoding) -> Offsets
pub fn new(bytes: &[u8], encoding: &'static Encoding) -> Offsets
The offsets for bytes decoded as parse_bytes
and ByteParser decode them in encoding:
with the encoding’s own byte order mark removed.
Sourcepub fn lossy_utf8(bytes: &[u8]) -> Offsets
pub fn lossy_utf8(bytes: &[u8]) -> Offsets
The offsets for bytes decoded as String::from_utf8_lossy
decodes them: a byte order mark kept, as text, and each run of
bytes that isn’t UTF-8 one U+FFFD. Parsing such a string, the
parser counts offsets into it.
Sourcepub fn is_identity(&self) -> bool
pub fn is_identity(&self) -> bool
Whether every offset is the same in both: ASCII, or UTF-8 with no byte order mark and nothing replaced.
Sourcepub fn to_source(&self, decoded: usize) -> usize
pub fn to_source(&self, decoded: usize) -> usize
The offset into the bytes of offset decoded into the decoded text.
An offset past the end maps past the end, saturating at usize::MAX.
Sourcepub fn to_decoded(&self, source: usize) -> usize
pub fn to_decoded(&self, source: usize) -> usize
The offset into the decoded text of offset source into the bytes.
One inside a character’s bytes gives one inside its decoding, never
past it. An offset past the end maps past the end, saturating at
usize::MAX.