From 944bea7f2f3c70c358d8eb5654a382d2b83c4a92 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Thu, 26 Nov 2026 17:00:37 +0100 Subject: [PATCH 1/9] Create better API --- src/errors.rs | 3 + src/vlq.rs | 184 +++++++++++++++++++++++++++++++++++--------------- 2 files changed, 134 insertions(+), 53 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 7a42afc..7c955f3 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -25,6 +25,8 @@ pub enum Error { VlqNoValues, /// Overflow in Vlq handling VlqOverflow, + /// Encoded VLQ data ended in a number that should have continued. + VlqTruncated, /// a mapping segment had an unsupported size BadSegmentSize(u32), /// a reference to a non existing source was encountered @@ -114,6 +116,7 @@ impl fmt::Display for Error { Error::VlqLeftover => write!(f, "leftover cur/shift in vlq decode"), Error::VlqNoValues => write!(f, "vlq decode did not produce any values"), Error::VlqOverflow => write!(f, "vlq decode caused an overflow"), + Error::VlqTruncated => write!(f, "vlq decode encountered a truncated number"), Error::BadSegmentSize(size) => write!(f, "got {size} segments, expected 4 or 5"), Error::BadSourceReference(id) => write!(f, "bad reference to source #{id}"), Error::BadNameReference(id) => write!(f, "bad reference to name #{id}"), diff --git a/src/vlq.rs b/src/vlq.rs index 305c10d..f9bb314 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -1,4 +1,5 @@ //! Implements utilities for dealing with the sourcemap vlq encoding. + use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -261,6 +262,130 @@ const B64: [i8; 256] = [ -1, ]; +#[derive(Debug, Clone, Copy)] +pub struct Vlq(u32); + +impl Vlq { + pub fn unsigned(&self) -> u32 { + self.0 + } + + pub fn signed(&self) -> i32 { + let neg = (self.0 & 1) != 0; + let out = (self.0 >> 1) as i32; + if neg && out == 0 { + i32::MIN + } else if neg { + -out + } else { + out + } + } + + pub fn from_unsigned(value: u32) -> Self { + Self(value) + } + + pub fn from_signed(value: i32) -> Self { + if value == i32::MIN { + Self(1) + } else if value < 0 { + Self((((-value) << 1) + 1) as u32) + } else { + Self((value << 1) as u32) + } + } + + pub fn encode(&self) -> VlqDigitIter { + VlqDigitIter { + current: self.0, + finished: false, + } + } + + pub fn decode(segment: &str) -> Result<(Self, &str)> { + if segment.is_empty() { + return Err(Error::VlqNoValues); + } + let mut cur = 0; + let mut shift = 0; + + let mut chars = segment.chars(); + for c in &mut chars { + if !c.is_ascii() { + return Err(Error::InvalidBase64(c)); + } + let enc = B64[c as usize]; + if enc < 0 { + return Err(Error::InvalidBase64(c)); + } + let val = (enc & 0b11111) as u32; + let finished = (enc >> 5) == 0; + cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; + shift += 5; + + if finished { + return Ok((Self(cur), chars.as_str())); + } + } + + // We're out of bytes, but the continuation bit is set. + // This means a malformed VLQ. + Err(Error::VlqTruncated) + } +} + +#[derive(Debug, Clone)] +pub struct VlqDigitIter { + current: u32, + finished: bool, +} + +impl Iterator for VlqDigitIter { + type Item = char; + + fn next(&mut self) -> Option { + if self.finished { + return None; + } + + let mut digit = self.current & 0b11111; + self.current >>= 5; + + if self.current > 0 { + digit |= 1 << 5; + } else { + self.finished = true; + } + + Some(B64_CHARS[digit as usize] as char) + } +} + +#[derive(Debug, Clone)] +pub struct DecodeVlqs<'a> { + current: &'a str, +} + +impl Iterator for DecodeVlqs<'_> { + type Item = Result; + + fn next(&mut self) -> Option { + match Vlq::decode(self.current) { + Ok((val, rest)) => { + self.current = rest; + Some(Ok(val)) + } + Err(Error::VlqNoValues) => None, + Err(e) => Some(Err(e)), + } + } +} + +pub fn decode_vlqs(segment: &str) -> DecodeVlqs<'_> { + DecodeVlqs { current: segment } +} + /// Parses a VLQ segment into a vector. pub fn parse_vlq_segment(segment: &str) -> Result> { let mut rv = vec![]; @@ -272,40 +397,11 @@ pub fn parse_vlq_segment(segment: &str) -> Result> { /// Parses a VLQ segment into a pre-allocated `Vec` instead of returning a new allocation. pub(crate) fn parse_vlq_segment_into(segment: &str, rv: &mut Vec) -> Result<()> { - let mut cur = 0; - let mut shift = 0; - - for c in segment.bytes() { - let enc = i64::from(B64[c as usize]); - let val = enc & 0b11111; - let cont = enc >> 5; - cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; - shift += 5; - - if cont == 0 { - let sign = cur & 1; - cur >>= 1; - if sign != 0 { - // See , point 5. - if cur == 0 { - cur = i32::MIN as i64; - } else { - cur = -cur; - } - } - rv.push(cur); - cur = 0; - shift = 0; - } - } - - if cur != 0 || shift != 0 { - Err(Error::VlqLeftover) - } else if rv.is_empty() { - Err(Error::VlqNoValues) - } else { - Ok(()) + for vlq in decode_vlqs(segment) { + let vlq = vlq?; + rv.push(vlq.signed() as i64); } + Ok(()) } /// Encodes a VLQ segment from a slice. @@ -318,25 +414,7 @@ pub fn generate_vlq_segment(nums: &[i64]) -> Result { } pub(crate) fn encode_vlq(out: &mut String, num: i64) { - let mut num = if num == i32::MIN as i64 { - 1 - } else if num < 0 { - ((-num) << 1) + 1 - } else { - num << 1 - }; - - loop { - let mut digit = num & 0b11111; - num >>= 5; - if num > 0 { - digit |= 1 << 5; - } - out.push(B64_CHARS[digit as usize] as char); - if num == 0 { - break; - } - } + out.extend(Vlq::from_signed(num as i32).encode()) } #[cfg(test)] @@ -368,7 +446,7 @@ mod tests { match parse_vlq_segment("00000000000000") { Err(Error::VlqOverflow) => {} e => { - panic!("Unexpeted result: {:?}", e); + panic!("Unexpected result: {:?}", e); } } } From 30bc2a46b86becb17cc9963f7b91fb9cc6f1618e Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 13:47:34 +0100 Subject: [PATCH 2/9] WIP --- Cargo.toml | 1 + src/decoder/mod.rs | 51 +++++++++++++------------- src/decoder/scope.rs | 68 ++++++++++------------------------- src/hermes.rs | 32 ++++++++++------- src/vlq.rs | 85 +++++++++++++++++++++++--------------------- 5 files changed, 109 insertions(+), 128 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3d6c389..8a33282 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ debugid = {version = "0.8.0", features = ["serde"] } base64-simd = { version = "0.8" } bitvec = "1.0.1" rustc-hash = "2.1.1" +fallible-iterator = "0.3.0" [features] ram_bundle = ["scroll"] diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index e27ee17..ec84551 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -5,13 +5,14 @@ use std::io::{BufReader, Read}; use bitvec::field::BitField; use bitvec::order::Lsb0; use bitvec::vec::BitVec; +use fallible_iterator::FallibleIterator; use serde_json::Value; use crate::errors::{Error, Result}; use crate::hermes::decode_hermes; use crate::jsontypes::RawSourceMap; use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection}; -use crate::vlq::parse_vlq_segment_into; +use crate::vlq; mod scope; @@ -152,10 +153,10 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { // Source IDs, lines, columns, and names are "running" values. // Each token (except the first) contains the delta from the previous value. - let mut running_src_id = 0; - let mut running_src_line = 0; - let mut running_src_col = 0; - let mut running_name_id = 0; + let mut running_src_id: u32 = 0; + let mut running_src_line: u32 = 0; + let mut running_src_col: u32 = 0; + let mut running_name_id: u32 = 0; let names = rsm.names.unwrap_or_default(); let sources = rsm.sources.unwrap_or_default(); @@ -164,7 +165,6 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { let allocation_size = mappings.matches(&[',', ';'][..]).count() + 10; let mut tokens = Vec::with_capacity(allocation_size); - let mut nums = Vec::with_capacity(6); let mut rmi = BitVec::new(); for (dst_line, (line, rmi_str)) in mappings @@ -176,7 +176,7 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { continue; } - dst_col = 0; + dst_col = 0u32; decode_rmi(rmi_str, &mut rmi)?; @@ -185,14 +185,10 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { continue; } - nums.clear(); - parse_vlq_segment_into(segment, &mut nums)?; - match nums.len() { - 1 | 4 | 5 => {} - _ => return Err(Error::BadSegmentSize(nums.len() as u32)), - } + let mut vlqs = vlq::decode_vlqs(segment); - dst_col = (i64::from(dst_col) + nums[0]) as u32; + // The `dst_col` must always exist. + dst_col = dst_col.saturating_add_signed(vlqs.next_required()?.signed()); // The source file , source line, source column, and name // may not be present in the current token. We use `u32::MAX` @@ -202,27 +198,32 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { let mut current_src_col = !0; let mut current_name_id = !0; - if nums.len() > 1 { - running_src_id = (i64::from(running_src_id) + nums[1]) as u32; + if let Some(running_src_id_incr) = vlqs.next()? { + // If he `running_src_id` exists, so must the `running_src_line` and the `running_src_col`. + running_src_id = running_src_id.saturating_add_signed(running_src_id_incr.signed()); + running_src_line = + running_src_line.saturating_add_signed(vlqs.next_required()?.signed()); + running_src_col = + running_src_col.saturating_add_signed(vlqs.next_required()?.signed()); if running_src_id >= sources.len() as u32 { return Err(Error::BadSourceReference(running_src_id)); } - running_src_line = (i64::from(running_src_line) + nums[2]) as u32; - running_src_col = (i64::from(running_src_col) + nums[3]) as u32; - current_src_id = running_src_id; current_src_line = running_src_line; current_src_col = running_src_col; + } - if nums.len() > 4 { - running_name_id = (i64::from(running_name_id) + nums[4]) as u32; - if running_name_id >= names.len() as u32 { - return Err(Error::BadNameReference(running_name_id)); - } - current_name_id = running_name_id; + if let Some(running_name_id_incr) = vlqs.next()? { + running_name_id = + running_name_id.saturating_add_signed(running_name_id_incr.signed()); + + if running_name_id >= names.len() as u32 { + return Err(Error::BadNameReference(running_name_id)); } + + current_name_id = running_name_id; } let is_range = rmi.get(line_index).map(|v| *v).unwrap_or_default(); diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index 21ea03a..8984ff0 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -1,5 +1,6 @@ use crate::types::{OriginalScopes, RawOriginalScope}; -use crate::{vlq, Error, Result}; +use crate::vlq::{self, Vlq}; +use crate::{Error, Result}; #[derive(Debug, Clone, Default)] struct PositionAccumulator { @@ -31,20 +32,20 @@ impl IndexAccumulator { } #[derive(Debug, Clone, Default)] -struct VlqBuffer(Vec); +struct VlqBuffer(Vec); impl VlqBuffer { - fn inner_mut(&mut self) -> &mut Vec { + fn inner_mut(&mut self) -> &mut Vec { self.0.clear(); &mut self.0 } - fn get(&self, index: usize) -> Result { + fn get(&self, index: usize) -> Result { let n = self .0 .get(index) .ok_or(Error::BadSegmentSize(self.0.len() as u32))?; - Ok(*n as i32) + Ok(*n) } } @@ -57,15 +58,6 @@ struct DecodeScopeState { name_idx: IndexAccumulator, /// The running kind index. kind_idx: IndexAccumulator, - /// Buffer for decoding VLQs. - vlq_buffer: VlqBuffer, -} - -impl DecodeScopeState { - fn decode_vlq(&mut self, segment: &str) -> Result<&VlqBuffer> { - vlq::parse_vlq_segment_into(segment, self.vlq_buffer.inner_mut())?; - Ok(&self.vlq_buffer) - } } /// Scope start entries are of the form @@ -87,11 +79,11 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result 0; let has_kind = (flags & KIND_FLAG) > 0; @@ -99,14 +91,14 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result (None, None), - (true, false) => (Some(nums.get(3)?), None), - (false, true) => (None, Some(nums.get(3)?)), - (true, true) => (Some(nums.get(3)?), Some(nums.get(4)?)), + (true, false) => (Some(vlqs.next_required()?), None), + (false, true) => (None, Some(vlqs.next_required()?)), + (true, true) => (Some(vlqs.next_required()?), Some(vlqs.next_required()?)), }; let (start_line, start_col) = state.position.advance(line, column); - let name_id = name_id.map_or(u32::MAX, |name_incr| state.name_idx.add(name_incr)); - let kind_id = kind_id.map_or(u32::MAX, |kind_incr| state.kind_idx.add(kind_incr)); + let name_id = name_id.map_or(u32::MAX, |name_incr| state.name_idx.add(name_incr.signed())); + let kind_id = kind_id.map_or(u32::MAX, |kind_incr| state.kind_idx.add(kind_incr.signed())); Ok(RawOriginalScope { start_line, @@ -130,9 +122,9 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result Result<(u32, u32)> { - let nums = state.decode_vlq(item)?; - let line = unsigned(nums.get(0)?); - let column = unsigned(nums.get(1)?); + let mut vlqs = vlq::decode_vlqs(item); + let line = vlqs.next_required()?.unsigned(); + let column = vlqs.next_required()?.unsigned(); Ok(state.position.advance(line, column)) } @@ -217,27 +209,3 @@ pub fn decode_scopes(items: &str) -> Result { Ok(out) } - -/// Reinterprets a signed VLQ as an unsigned number. -/// -/// This reverts the operation described in -/// . -fn unsigned(mut vlq: i32) -> u32 { - if vlq == i32::MIN { - return 1; - } - - let neg = vlq < 0; - - if neg { - vlq = -vlq; - } - - vlq <<= 1; - - if neg { - vlq |= 1; - } - - vlq as u32 -} diff --git a/src/hermes.rs b/src/hermes.rs index e43eedc..71b56f6 100644 --- a/src/hermes.rs +++ b/src/hermes.rs @@ -4,11 +4,13 @@ use crate::errors::{Error, Result}; use crate::jsontypes::{FacebookScopeMapping, FacebookSources, RawSourceMap}; use crate::types::{DecodedMap, RewriteOptions, SourceMap}; use crate::utils::greatest_lower_bound; -use crate::vlq::parse_vlq_segment_into; -use crate::Token; +use crate::{vlq, Token}; + use std::io::{Read, Write}; use std::ops::{Deref, DerefMut}; +use fallible_iterator::FallibleIterator; + /// These are starting locations of scopes. /// The `name_index` represents the index into the `HermesFunctionMap.names` vec, /// which represents the function names/scopes. @@ -164,8 +166,6 @@ pub fn decode_hermes(mut rsm: RawSourceMap) -> Result { // This is basically the logic from here: // https://github.com/facebook/metro/blob/63b523eb20e7bdf62018aeaf195bb5a3a1a67f36/packages/metro-symbolicate/src/SourceMetadataMapConsumer.js#L182-L202 - let mut nums = Vec::with_capacity(4); - let function_maps = x_facebook_sources .iter() .map(|v| { @@ -175,28 +175,34 @@ pub fn decode_hermes(mut rsm: RawSourceMap) -> Result { } = v.as_ref()?.iter().next()?; let mut mappings = vec![]; - let mut line = 1; - let mut name_index = 0; + let mut line: u32 = 1; + let mut name_index: u32 = 0; for line_mapping in raw_mappings.split(';') { if line_mapping.is_empty() { continue; } - let mut column = 0; + let mut column: u32 = 0; for mapping in line_mapping.split(',') { if mapping.is_empty() { continue; } - nums.clear(); - parse_vlq_segment_into(mapping, &mut nums).ok()?; - let mut nums = nums.iter().copied(); + let mut vlqs = vlq::decode_vlqs(mapping); + + // `column_incr` must exist, `name_index_incr` and `line_incr` + // are assumed zero if they're missing. + let column_incr = vlqs.next().ok().flatten()?.signed(); + let name_index_incr = + vlqs.next().ok().flatten().map(|n| n.signed()).unwrap_or(0); + let line_incr = vlqs.next().ok().flatten().map(|n| n.signed()).unwrap_or(0); + + column = column.saturating_add_signed(column_incr); + name_index = name_index.saturating_add_signed(name_index_incr); + line = line.saturating_add_signed(line_incr); - column = (i64::from(column) + nums.next()?) as u32; - name_index = (i64::from(name_index) + nums.next().unwrap_or(0)) as u32; - line = (i64::from(line) + nums.next().unwrap_or(0)) as u32; mappings.push(HermesScopeOffset { column, line, diff --git a/src/vlq.rs b/src/vlq.rs index f9bb314..c003634 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -1,5 +1,7 @@ //! Implements utilities for dealing with the sourcemap vlq encoding. +use fallible_iterator::FallibleIterator; + use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -262,7 +264,7 @@ const B64: [i8; 256] = [ -1, ]; -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Vlq(u32); impl Vlq { @@ -364,53 +366,38 @@ impl Iterator for VlqDigitIter { #[derive(Debug, Clone)] pub struct DecodeVlqs<'a> { + returned: u32, current: &'a str, } -impl Iterator for DecodeVlqs<'_> { - type Item = Result; +impl<'a> DecodeVlqs<'a> { + pub fn next_required(&mut self) -> Result { + self.next()?.ok_or(Error::BadSegmentSize(self.returned)) + } +} + +impl FallibleIterator for DecodeVlqs<'_> { + type Item = Vlq; + type Error = Error; - fn next(&mut self) -> Option { + fn next(&mut self) -> std::result::Result, Self::Error> { match Vlq::decode(self.current) { Ok((val, rest)) => { self.current = rest; - Some(Ok(val)) + self.returned += 1; + Ok(Some(val)) } - Err(Error::VlqNoValues) => None, - Err(e) => Some(Err(e)), + Err(Error::VlqNoValues) => Ok(None), + Err(e) => Err(e), } } } pub fn decode_vlqs(segment: &str) -> DecodeVlqs<'_> { - DecodeVlqs { current: segment } -} - -/// Parses a VLQ segment into a vector. -pub fn parse_vlq_segment(segment: &str) -> Result> { - let mut rv = vec![]; - - parse_vlq_segment_into(segment, &mut rv)?; - - Ok(rv) -} - -/// Parses a VLQ segment into a pre-allocated `Vec` instead of returning a new allocation. -pub(crate) fn parse_vlq_segment_into(segment: &str, rv: &mut Vec) -> Result<()> { - for vlq in decode_vlqs(segment) { - let vlq = vlq?; - rv.push(vlq.signed() as i64); + DecodeVlqs { + current: segment, + returned: 0, } - Ok(()) -} - -/// Encodes a VLQ segment from a slice. -pub fn generate_vlq_segment(nums: &[i64]) -> Result { - let mut rv = String::new(); - for &num in nums { - encode_vlq(&mut rv, num); - } - Ok(rv) } pub(crate) fn encode_vlq(out: &mut String, num: i64) { @@ -421,14 +408,32 @@ pub(crate) fn encode_vlq(out: &mut String, num: i64) { mod tests { use super::*; + fn parse_vlq_segment_signed(segment: &str) -> Result> { + let mut out = Vec::new(); + let mut vlqs = decode_vlqs(segment); + while let Some(vlq) = vlqs.next()? { + out.push(vlq.signed()); + } + + Ok(out) + } + + fn generate_vlq_segment(nums: &[i64]) -> Result { + let mut rv = String::new(); + for &num in nums { + encode_vlq(&mut rv, num); + } + Ok(rv) + } + #[test] fn test_vlq_decode() { - let rv = parse_vlq_segment("AAAA").unwrap(); - assert_eq!(rv, vec![0, 0, 0, 0]); - let rv = parse_vlq_segment("GAAIA").unwrap(); + let rv = parse_vlq_segment_signed("AAAA").unwrap(); + assert_eq!(rv, [0, 0, 0, 0]); + let rv = parse_vlq_segment_signed("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); - let rv = parse_vlq_segment("B").unwrap(); - assert_eq!(rv, vec![i32::MIN as i64]); + let rv = parse_vlq_segment_signed("B").unwrap(); + assert_eq!(rv, vec![i32::MIN]); } #[test] @@ -443,7 +448,7 @@ mod tests { #[test] fn test_overflow() { - match parse_vlq_segment("00000000000000") { + match parse_vlq_segment_signed("00000000000000") { Err(Error::VlqOverflow) => {} e => { panic!("Unexpected result: {:?}", e); From f35f2fa8dee22023bd6fce0b385b3d3d8979f5a3 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 13:56:22 +0100 Subject: [PATCH 3/9] Shorten B64 array --- src/vlq.rs | 264 ++--------------------------------------------------- 1 file changed, 7 insertions(+), 257 deletions(-) diff --git a/src/vlq.rs b/src/vlq.rs index c003634..51043af 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -5,263 +5,13 @@ use fallible_iterator::FallibleIterator; use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -const B64: [i8; 256] = [ - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 62, - -1, - -1, - -1, - 63, - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - -1, - -1, - -1, - -1, - -1, - -1, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51, - -1, - -1, - -1, - -1, - -1 - 1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, +const B64: [i8; 128] = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, + 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, -1, -1, -1, -1, -1, ]; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] From e40e8f5edc6a349faece381ac2bd64b4518c1e5c Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 14:01:00 +0100 Subject: [PATCH 4/9] WIP --- src/decoder/mod.rs | 6 +-- src/decoder/scope.rs | 20 +--------- src/encoder.rs | 12 +++--- src/vlq.rs | 88 +++++++++++++++++++++++++------------------- 4 files changed, 62 insertions(+), 64 deletions(-) diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index ec84551..2389333 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -149,7 +149,7 @@ fn decode_rmi(rmi_str: &str, val: &mut BitVec) -> Result<()> { } pub fn decode_regular(rsm: RawSourceMap) -> Result { - let mut dst_col; + let mut dst_col: u32; // Source IDs, lines, columns, and names are "running" values. // Each token (except the first) contains the delta from the previous value. @@ -176,7 +176,7 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { continue; } - dst_col = 0u32; + dst_col = 0; decode_rmi(rmi_str, &mut rmi)?; @@ -199,7 +199,7 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { let mut current_name_id = !0; if let Some(running_src_id_incr) = vlqs.next()? { - // If he `running_src_id` exists, so must the `running_src_line` and the `running_src_col`. + // If the `running_src_id` exists, so must the `running_src_line` and the `running_src_col`. running_src_id = running_src_id.saturating_add_signed(running_src_id_incr.signed()); running_src_line = running_src_line.saturating_add_signed(vlqs.next_required()?.signed()); diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index 8984ff0..290df00 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -1,5 +1,5 @@ use crate::types::{OriginalScopes, RawOriginalScope}; -use crate::vlq::{self, Vlq}; +use crate::vlq; use crate::{Error, Result}; #[derive(Debug, Clone, Default)] @@ -31,24 +31,6 @@ impl IndexAccumulator { } } -#[derive(Debug, Clone, Default)] -struct VlqBuffer(Vec); - -impl VlqBuffer { - fn inner_mut(&mut self) -> &mut Vec { - self.0.clear(); - &mut self.0 - } - - fn get(&self, index: usize) -> Result { - let n = self - .0 - .get(index) - .ok_or(Error::BadSegmentSize(self.0.len() as u32))?; - Ok(*n) - } -} - /// Running state for decoding the scopes for a source. #[derive(Debug, Clone, Default)] struct DecodeScopeState { diff --git a/src/encoder.rs b/src/encoder.rs index 52427f9..c79c0d8 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -1,3 +1,4 @@ +use std::fmt::Write as _; use std::io::Write; use bitvec::field::BitField; @@ -8,7 +9,7 @@ use serde_json::Value; use crate::errors::Result; use crate::jsontypes::{RawSection, RawSectionOffset, RawSourceMap}; use crate::types::{DecodedMap, SourceMap, SourceMapIndex}; -use crate::vlq::encode_vlq; +use crate::vlq::Vlq; pub trait Encodable { fn as_raw_sourcemap(&self) -> RawSourceMap; @@ -20,10 +21,6 @@ pub fn encode(sm: &M, mut w: W) -> Result<()> { Ok(()) } -fn encode_vlq_diff(out: &mut String, a: u32, b: u32) { - encode_vlq(out, i64::from(a) - i64::from(b)) -} - fn encode_rmi(out: &mut Vec, data: &[u8]) { fn encode_byte(b: u8) -> u8 { match b { @@ -102,6 +99,11 @@ fn serialize_range_mappings(sm: &SourceMap) -> Option { Some(String::from_utf8(buf).expect("invalid utf8")) } +fn encode_vlq_diff(out: &mut String, x: u32, y: u32) { + let vlq = Vlq::from_signed((i64::from(x) - i64::from(y)) as i32); + let _ = write!(out, "{vlq}"); +} + fn serialize_mappings(sm: &SourceMap) -> String { let mut rv = String::new(); // dst == minified == generated diff --git a/src/vlq.rs b/src/vlq.rs index 51043af..0b6d6e1 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -1,5 +1,7 @@ //! Implements utilities for dealing with the sourcemap vlq encoding. +use std::fmt::{self, Write}; + use fallible_iterator::FallibleIterator; use crate::errors::{Error, Result}; @@ -14,14 +16,27 @@ const B64: [i8; 128] = [ 51, -1, -1, -1, -1, -1, ]; +/// A BASE64 VLQ (variable-length quantity) number parsed from a sourcemap. +/// +/// These are defined in in the +/// sourcemap spec. +/// +/// This type can be encoded back into a BASE64 string representation +/// via its `Display` impl. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Vlq(u32); impl Vlq { + /// Interprets the VLQ as an unsigned 32-bit number. pub fn unsigned(&self) -> u32 { self.0 } + /// Interprets the VLQ as a signed 32-bit number. + /// + /// NB: This is _not_ equivalent to `Self::unsigned() as i32`. + /// See for how + /// an unsigned value is converted to a signed one. pub fn signed(&self) -> i32 { let neg = (self.0 & 1) != 0; let out = (self.0 >> 1) as i32; @@ -34,10 +49,12 @@ impl Vlq { } } + /// Constructs a `Self` from an unsinged 32-bit number. pub fn from_unsigned(value: u32) -> Self { Self(value) } + /// Constructs a `Self` from a signed 32-bit number. pub fn from_signed(value: i32) -> Self { if value == i32::MIN { Self(1) @@ -48,13 +65,9 @@ impl Vlq { } } - pub fn encode(&self) -> VlqDigitIter { - VlqDigitIter { - current: self.0, - finished: false, - } - } - + /// Decodes one `Self` from the front of a string slice, + /// returning the decoded VLQ and the rest of the string + /// slice if successful. pub fn decode(segment: &str) -> Result<(Self, &str)> { if segment.is_empty() { return Err(Error::VlqNoValues); @@ -87,33 +100,30 @@ impl Vlq { } } -#[derive(Debug, Clone)] -pub struct VlqDigitIter { - current: u32, - finished: bool, -} - -impl Iterator for VlqDigitIter { - type Item = char; +impl fmt::Display for Vlq { + /// Formats a VLQ as BASE64. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut current = self.0; + loop { + let mut digit = current & 0b11111; + current >>= 5; - fn next(&mut self) -> Option { - if self.finished { - return None; - } + if current > 0 { + digit |= 1 << 5; + } - let mut digit = self.current & 0b11111; - self.current >>= 5; + f.write_char(B64_CHARS[digit as usize] as char)?; - if self.current > 0 { - digit |= 1 << 5; - } else { - self.finished = true; + if current == 0 { + break; + } } - Some(B64_CHARS[digit as usize] as char) + Ok(()) } } +/// The iterator returned by [`decode_vlqs`]. #[derive(Debug, Clone)] pub struct DecodeVlqs<'a> { returned: u32, @@ -121,6 +131,11 @@ pub struct DecodeVlqs<'a> { } impl<'a> DecodeVlqs<'a> { + /// Returns the next decoded VLQ. + /// + /// Unlike [`next`](::next), this returns + /// an error if no VLQs are left in the segment. Use this in + /// situations where the absence of the next VLQ is an error. pub fn next_required(&mut self) -> Result { self.next()?.ok_or(Error::BadSegmentSize(self.returned)) } @@ -143,6 +158,8 @@ impl FallibleIterator for DecodeVlqs<'_> { } } +/// Returns a [`FallibleIterator`] over the VLQs encoded in +/// the provided string slice. pub fn decode_vlqs(segment: &str) -> DecodeVlqs<'_> { DecodeVlqs { current: segment, @@ -150,10 +167,6 @@ pub fn decode_vlqs(segment: &str) -> DecodeVlqs<'_> { } } -pub(crate) fn encode_vlq(out: &mut String, num: i64) { - out.extend(Vlq::from_signed(num as i32).encode()) -} - #[cfg(test)] mod tests { use super::*; @@ -168,12 +181,13 @@ mod tests { Ok(out) } - fn generate_vlq_segment(nums: &[i64]) -> Result { + fn generate_vlq_segment_signed(nums: &[i32]) -> String { let mut rv = String::new(); - for &num in nums { - encode_vlq(&mut rv, num); + for &n in nums { + write!(&mut rv, "{}", Vlq::from_signed(n)).unwrap(); } - Ok(rv) + + rv } #[test] @@ -188,11 +202,11 @@ mod tests { #[test] fn test_vlq_encode() { - let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap(); + let rv = generate_vlq_segment_signed(&[0, 0, 0, 0]); assert_eq!(rv.as_str(), "AAAA"); - let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap(); + let rv = generate_vlq_segment_signed(&[3, 0, 0, 4, 0]); assert_eq!(rv.as_str(), "GAAIA"); - let rv = generate_vlq_segment(&[i32::MIN as i64]).unwrap(); + let rv = generate_vlq_segment_signed(&[i32::MIN]); assert_eq!(rv.as_str(), "B"); } From 7f90cc06d1c6026b757167d940328128d5d1fdde Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 14:51:18 +0100 Subject: [PATCH 5/9] Make module private --- src/lib.rs | 2 +- src/vlq.rs | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ea0fabc..aa491c9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,4 +75,4 @@ mod utils; #[cfg(feature = "ram_bundle")] pub mod ram_bundle; -pub mod vlq; +mod vlq; diff --git a/src/vlq.rs b/src/vlq.rs index 0b6d6e1..aaa27d3 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -49,11 +49,6 @@ impl Vlq { } } - /// Constructs a `Self` from an unsinged 32-bit number. - pub fn from_unsigned(value: u32) -> Self { - Self(value) - } - /// Constructs a `Self` from a signed 32-bit number. pub fn from_signed(value: i32) -> Self { if value == i32::MIN { @@ -133,7 +128,7 @@ pub struct DecodeVlqs<'a> { impl<'a> DecodeVlqs<'a> { /// Returns the next decoded VLQ. /// - /// Unlike [`next`](::next), this returns + /// Unlike [`next`](Self::next), this returns /// an error if no VLQs are left in the segment. Use this in /// situations where the absence of the next VLQ is an error. pub fn next_required(&mut self) -> Result { From a35a870a747cedc5bdf65b34a1283e82cc567528 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 15:26:32 +0100 Subject: [PATCH 6/9] Fix shift logic --- src/vlq.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/vlq.rs b/src/vlq.rs index aaa27d3..eaac860 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -67,7 +67,7 @@ impl Vlq { if segment.is_empty() { return Err(Error::VlqNoValues); } - let mut cur = 0; + let mut cur: u32 = 0; let mut shift = 0; let mut chars = segment.chars(); @@ -81,7 +81,13 @@ impl Vlq { } let val = (enc & 0b11111) as u32; let finished = (enc >> 5) == 0; - cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; + + // Return an error if shifting left would discard digits + if val.highest_one().is_some_and(|idx| idx + shift >= 32) { + return Err(Error::VlqOverflow); + } + + cur = cur.checked_add(val << shift).ok_or(Error::VlqOverflow)?; shift += 5; if finished { From 81815ec526656573c99c61388a1d1ae49ffd0bd5 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 15:28:19 +0100 Subject: [PATCH 7/9] Fix hermes missing values logic --- src/hermes.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/hermes.rs b/src/hermes.rs index 71b56f6..74697fe 100644 --- a/src/hermes.rs +++ b/src/hermes.rs @@ -194,10 +194,9 @@ pub fn decode_hermes(mut rsm: RawSourceMap) -> Result { // `column_incr` must exist, `name_index_incr` and `line_incr` // are assumed zero if they're missing. - let column_incr = vlqs.next().ok().flatten()?.signed(); - let name_index_incr = - vlqs.next().ok().flatten().map(|n| n.signed()).unwrap_or(0); - let line_incr = vlqs.next().ok().flatten().map(|n| n.signed()).unwrap_or(0); + let column_incr = vlqs.next_required().ok()?.signed(); + let name_index_incr = vlqs.next().ok()?.map(|n| n.signed()).unwrap_or(0); + let line_incr = vlqs.next().ok()?.map(|n| n.signed()).unwrap_or(0); column = column.saturating_add_signed(column_incr); name_index = name_index.saturating_add_signed(name_index_incr); From ba0394aa63a0420f41bd77cf75a834c908da1f27 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 15:41:49 +0100 Subject: [PATCH 8/9] Add `DecodeVlqs::finished` --- src/decoder/mod.rs | 2 ++ src/vlq.rs | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index 2389333..33e7efb 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -226,6 +226,8 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { current_name_id = running_name_id; } + vlqs.finished()?; + let is_range = rmi.get(line_index).map(|v| *v).unwrap_or_default(); tokens.push(RawToken { diff --git a/src/vlq.rs b/src/vlq.rs index eaac860..2af2800 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -140,6 +140,15 @@ impl<'a> DecodeVlqs<'a> { pub fn next_required(&mut self) -> Result { self.next()?.ok_or(Error::BadSegmentSize(self.returned)) } + + /// Returns an error if there is anything left in the segment. + pub fn finished(self) -> Result<()> { + let returned = self.returned; + match self.count()? { + 0 => Ok(()), + n => Err(Error::BadSegmentSize(returned + n as u32)), + } + } } impl FallibleIterator for DecodeVlqs<'_> { From feb06487d175413a8f5ac8d9ccef2fa4a33e01d5 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Fri, 27 Nov 2026 15:53:51 +0100 Subject: [PATCH 9/9] Refine shift check --- src/vlq.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/vlq.rs b/src/vlq.rs index 2af2800..3730253 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -82,8 +82,9 @@ impl Vlq { let val = (enc & 0b11111) as u32; let finished = (enc >> 5) == 0; - // Return an error if shifting left would discard digits - if val.highest_one().is_some_and(|idx| idx + shift >= 32) { + // Return an error if shifting left would discard 1s or + // exceed 32 bits + if val.highest_one().unwrap_or(0) + shift >= 32 { return Err(Error::VlqOverflow); }