When serializing long JSON strings, sonic-rs implements a copy and find algorithm using SIMD.
Instead of checking every character for escaping, the library copies large chunks (e.g., 32 bytes) of the string into the destination buffer using SIMD. It then uses a mask to check if any characters in that chunk require escaping. If no escaped characters are found in the chunk, it moves to the next block immediately. If an escaped character is detected, it falls back to a manual escape routine for that specific segment.
while nb >= LANS {
// copy from the JSON string
let v = {
let raw = std::slice::from_raw_parts(sptr, LANS);
u8x32::from_slice_unaligned_unchecked(raw)
};
v.write_to_slice_unaligned_unchecked(std::slice::from_raw_parts_mut(dptr, LANS));
// if find the escaped character, then deal with it
let mask = escaped_mask(v);
if mask == 0 {
nb -= LANS;
dptr = dptr.add(LANS);
sptr = sptr.add(LANS);
} else {
let cn = mask.trailing_zeros() as usize;
nb -= cn;
dptr = dptr.add(cn);
sptr = sptr.add(cn);
escape_unchecked(&mut sptr, &mut nb, &mut dptr);
}
}