Skip to content

Commit 9be4c96

Browse files
committed
Merge pull request 2001 from saethlin/optimize-ipaddr
2 parents 5a8dcac + 4114e90 commit 9be4c96

2 files changed

Lines changed: 44 additions & 2 deletions

File tree

‎serde/src/lib.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,6 @@
139139
)
140140
)]
141141
// Rustc lints.
142-
#![forbid(unsafe_code)]
143142
#![deny(missing_docs, unused_imports)]
144143

145144
////////////////////////////////////////////////////////////////////////////////

‎serde/src/ser/impls.rs‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,42 @@ impl Serialize for net::IpAddr {
674674
}
675675
}
676676

677+
const DEC_DIGITS_LUT: &'static [u8] = b"\
678+
0001020304050607080910111213141516171819\
679+
2021222324252627282930313233343536373839\
680+
4041424344454647484950515253545556575859\
681+
6061626364656667686970717273747576777879\
682+
8081828384858687888990919293949596979899";
683+
684+
#[inline]
685+
fn format_u8(mut n: u8, out: &mut [u8]) -> usize {
686+
if n >= 100 {
687+
let d1 = ((n % 100) << 1) as usize;
688+
n /= 100;
689+
out[0] = b'0' + n;
690+
out[1] = DEC_DIGITS_LUT[d1];
691+
out[2] = DEC_DIGITS_LUT[d1 + 1];
692+
3
693+
} else if n >= 10 {
694+
let d1 = (n << 1) as usize;
695+
out[0] = DEC_DIGITS_LUT[d1];
696+
out[1] = DEC_DIGITS_LUT[d1 + 1];
697+
2
698+
} else {
699+
out[0] = b'0' + n;
700+
1
701+
}
702+
}
703+
704+
#[test]
705+
fn test_format_u8() {
706+
for i in 0..(u8::MAX as u16) {
707+
let mut buf = [0u8; 3];
708+
let written = format_u8(i as u8, &mut buf);
709+
assert_eq!(i.to_string().as_bytes(), &buf[..written]);
710+
}
711+
}
712+
677713
#[cfg(feature = "std")]
678714
impl Serialize for net::Ipv4Addr {
679715
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
@@ -683,7 +719,14 @@ impl Serialize for net::Ipv4Addr {
683719
if serializer.is_human_readable() {
684720
const MAX_LEN: usize = 15;
685721
debug_assert_eq!(MAX_LEN, "101.102.103.104".len());
686-
serialize_display_bounded_length!(self, MAX_LEN, serializer)
722+
let mut buf = [b'.'; MAX_LEN];
723+
let mut written = format_u8(self.octets()[0], &mut buf);
724+
for oct in &self.octets()[1..] {
725+
// Skip over delimiters that we initialized buf with
726+
written += format_u8(*oct, &mut buf[written + 1..]) + 1;
727+
}
728+
// We've only written ASCII bytes to the buffer, so it is valid UTF-8
729+
serializer.serialize_str(unsafe { str::from_utf8_unchecked(&buf[..written]) })
687730
} else {
688731
self.octets().serialize(serializer)
689732
}

0 commit comments

Comments
 (0)