Skip to content

Commit 26c5e6d

Browse files
committed
Use the itoa crate to serialize integers.
1 parent 9889d19 commit 26c5e6d

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ encoding_rs = "0.7"
2222
cssparser-macros = {path = "./macros", version = "0.3"}
2323
dtoa-short = "0.3"
2424
heapsize = {version = ">= 0.3, < 0.5", optional = true}
25+
itoa = "0.3"
2526
matches = "0.1"
2627
phf = "0.7"
2728
procedural-masquerade = {path = "./procedural-masquerade", version = "0.1"}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ fn parse_border_spacing(_context: &ParserContext, input: &mut Parser)
6969
#![recursion_limit="200"] // For color::parse_color_keyword
7070

7171
extern crate dtoa_short;
72+
extern crate itoa;
7273
#[macro_use] extern crate cssparser_macros;
7374
#[macro_use] extern crate matches;
7475
#[macro_use] extern crate procedural_masquerade;

src/serializer.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
44

55
use dtoa_short::{self, Notation};
6+
use itoa;
67
use std::ascii::AsciiExt;
78
use std::fmt::{self, Write};
9+
use std::io;
810
use std::str;
911

1012
use super::Token;
@@ -258,7 +260,32 @@ macro_rules! impl_tocss_for_int {
258260
($T: ty) => {
259261
impl<'a> ToCss for $T {
260262
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
261-
write!(dest, "{}", *self)
263+
struct AssumeUtf8<W: fmt::Write>(W);
264+
265+
impl<W: fmt::Write> io::Write for AssumeUtf8<W> {
266+
#[inline]
267+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
268+
// Safety: itoa only emits ASCII
269+
self.0.write_str(unsafe { str::from_utf8_unchecked(buf) })
270+
.map_err(|_| io::ErrorKind::Other.into())
271+
}
272+
273+
#[inline]
274+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
275+
self.write_all(buf)?;
276+
Ok(buf.len())
277+
}
278+
279+
#[inline]
280+
fn flush(&mut self) -> io::Result<()> {
281+
Ok(())
282+
}
283+
}
284+
285+
match itoa::write(AssumeUtf8(dest), *self) {
286+
Ok(_) => Ok(()),
287+
Err(_) => Err(fmt::Error)
288+
}
262289
}
263290
}
264291
}

0 commit comments

Comments
 (0)