ws protocol: don't heap-allocate in serialize_20_bytes

This commit is contained in:
Joakim Frostegård 2024-02-04 00:14:13 +01:00
parent 7f883a9433
commit d1426d3ac5
2 changed files with 13 additions and 7 deletions

View file

@ -43,11 +43,6 @@
* move additional request sending to for each received response, maybe * move additional request sending to for each received response, maybe
with probability 0.2 with probability 0.2
* aquatic_ws
* large amount of temporary allocations in serialize_20_bytes, pretty many in deserialize_20_bytes
* 20 byte parsing: consider using something like ArrayString<80> to avoid
heap allocations
# Not important # Not important
* aquatic_http: * aquatic_http:

View file

@ -84,9 +84,20 @@ fn serialize_20_bytes<S>(data: &[u8; 20], serializer: S) -> Result<S::Ok, S::Err
where where
S: Serializer, S: Serializer,
{ {
let text: String = data.iter().map(|byte| char::from(*byte)).collect(); // Length of 40 is enough since each char created from a byte will
// utf-8-encode to max 2 bytes
let mut str_buffer = [0u8; 40];
let mut offset = 0;
serializer.serialize_str(&text) for byte in data {
offset += char::from(*byte)
.encode_utf8(&mut str_buffer[offset..])
.len();
}
let text = ::std::str::from_utf8(&str_buffer[..offset]).unwrap();
serializer.serialize_str(text)
} }
struct TwentyByteVisitor; struct TwentyByteVisitor;