Skip to content

Commit

Permalink
optimize node_to_stream() for small int
Browse files Browse the repository at this point in the history
  • Loading branch information
arvidn committed Feb 5, 2024
1 parent ed2f13e commit e1913d8
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/serde/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::io::ErrorKind;
use std::io::Write;

use super::write_atom::write_atom;
use crate::allocator::{Allocator, NodePtr, SExp};
use crate::allocator::{len_for_value, Allocator, NodePtr, NodeVisitor};

const CONS_BOX_MARKER: u8 = 0xff;

Expand Down Expand Up @@ -41,17 +41,22 @@ impl<W: io::Write> Write for LimitedWriter<W> {
pub fn node_to_stream<W: io::Write>(a: &Allocator, node: NodePtr, f: &mut W) -> io::Result<()> {
let mut values: Vec<NodePtr> = vec![node];
while let Some(v) = values.pop() {
let n = a.sexp(v);
match n {
SExp::Atom => {
write_atom(f, a.atom(v))?;
a.visit_node(v, |node| -> io::Result<()> {
match node {
NodeVisitor::Buffer(buf) => write_atom(f, buf),
NodeVisitor::U32(val) => {
let buf = val.to_be_bytes();
let len = len_for_value(*val);
write_atom(f, &buf[4 - len..])
}
NodeVisitor::Pair(left, right) => {
f.write_all(&[CONS_BOX_MARKER])?;
values.push(*right);
values.push(*left);
Ok(())
}
}
SExp::Pair(left, right) => {
f.write_all(&[CONS_BOX_MARKER])?;
values.push(right);
values.push(left);
}
}
})?;
}
Ok(())
}
Expand Down

0 comments on commit e1913d8

Please sign in to comment.