Skip to content

Commit 7420620

Browse files
committed
refactor(codegen): add CodeBuffer::as_bytes method (#6498)
`as_bytes` is clearer than `as_ref` (what kind of ref?)
1 parent d816b0b commit 7420620

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

crates/oxc_codegen/src/code_buffer.rs

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,20 @@ impl CodeBuffer {
311311
self.buf.extend(bytes);
312312
}
313313

314+
/// Get contents of `CodeBuffer` as a byte slice.
315+
///
316+
/// # Examples
317+
/// ```
318+
/// use oxc_codegen::CodeBuffer;
319+
/// let mut code = CodeBuffer::new();
320+
/// code.print_str("foo");
321+
/// assert_eq!(code.as_bytes(), &[b'f', b'o', b'o']);
322+
/// ```
323+
#[inline]
324+
pub fn as_bytes(&self) -> &[u8] {
325+
&self.buf
326+
}
327+
314328
/// Convert a `CodeBuffer` into a string of source code, leaving its
315329
/// internal buffer empty and finalizing the codegen process.
316330
///
@@ -344,7 +358,7 @@ impl CodeBuffer {
344358

345359
impl AsRef<[u8]> for CodeBuffer {
346360
fn as_ref(&self) -> &[u8] {
347-
&self.buf
361+
self.as_bytes()
348362
}
349363
}
350364

@@ -394,7 +408,7 @@ mod test {
394408
assert!(code.is_empty());
395409
assert_eq!(code.len(), 0);
396410
let empty_slice: &[u8] = &[];
397-
assert_eq!(code.as_ref(), empty_slice);
411+
assert_eq!(code.as_bytes(), empty_slice);
398412
assert_eq!(String::from(code), "");
399413
}
400414

@@ -407,7 +421,7 @@ mod test {
407421
code.print_ascii_byte(b'o');
408422

409423
assert_eq!(code.len(), 3);
410-
assert_eq!(code.as_ref(), &[b'f', b'o', b'o']);
424+
assert_eq!(code.as_bytes(), &[b'f', b'o', b'o']);
411425
assert_eq!(String::from(code), "foo");
412426
}
413427

@@ -423,7 +437,7 @@ mod test {
423437
}
424438

425439
assert_eq!(code.len(), 3);
426-
assert_eq!(code.as_ref(), &[b'f', b'o', b'o']);
440+
assert_eq!(code.as_bytes(), &[b'f', b'o', b'o']);
427441
assert_eq!(String::from(code), "foo");
428442
}
429443

crates/oxc_codegen/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,13 +556,13 @@ impl<'a> Codegen<'a> {
556556

557557
fn add_source_mapping(&mut self, position: u32) {
558558
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut() {
559-
sourcemap_builder.add_source_mapping(self.code.as_ref(), position, None);
559+
sourcemap_builder.add_source_mapping(self.code.as_bytes(), position, None);
560560
}
561561
}
562562

563563
fn add_source_mapping_for_name(&mut self, span: Span, name: &str) {
564564
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut() {
565-
sourcemap_builder.add_source_mapping_for_name(self.code.as_ref(), span, name);
565+
sourcemap_builder.add_source_mapping_for_name(self.code.as_bytes(), span, name);
566566
}
567567
}
568568
}

0 commit comments

Comments
 (0)