Skip to content

Commit 671dd09

Browse files
authored
Rollup merge of rust-lang#60656 - petertodd:2019-inline-cursor-over-slice, r=sfackler
Inline some Cursor calls for slices (Partially) brings back rust-lang#33921 I've noticed in some serialization code I was writing that writes to slices produce much, much, worse code than you'd expect even with optimizations turned on. For example, you'd expect something like this to be zero cost: ``` use std::io::{self, Cursor, Write}; pub fn serialize((a, b): (u64, u64)) -> [u8;8+8] { let mut r = [0u8;16]; { let mut w = Cursor::new(&mut r[..]); w.write(&a.to_le_bytes()).unwrap(); w.write(&b.to_le_bytes()).unwrap(); } r } ``` ...but it compiles down to [dozens of instructions](https://rust.godbolt.org/z/bdwDzb) because the `slice_write()` calls aren't inlined, which in turn means `unwrap()` can't be optimized away, and so on. To be clear, this pull-req isn't sufficient by itself: if we want to go down that path we also need to add `#[inline]`'s to the default implementations for functions like `write_all()` in the `Write` trait and so on, or implement them separately in the `Cursor` impls. But I figured I'd start a conversation about what tradeoffs we're expecting here.
2 parents 26a7544 + b9c4301 commit 671dd09

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

src/libstd/io/cursor.rs

+6
Original file line numberDiff line numberDiff line change
@@ -265,13 +265,15 @@ impl<T> BufRead for Cursor<T> where T: AsRef<[u8]> {
265265
}
266266

267267
// Non-resizing write implementation
268+
#[inline]
268269
fn slice_write(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> io::Result<usize> {
269270
let pos = cmp::min(*pos_mut, slice.len() as u64);
270271
let amt = (&mut slice[(pos as usize)..]).write(buf)?;
271272
*pos_mut += amt as u64;
272273
Ok(amt)
273274
}
274275

276+
#[inline]
275277
fn slice_write_vectored(
276278
pos_mut: &mut u64,
277279
slice: &mut [u8],
@@ -341,6 +343,7 @@ impl Write for Cursor<&mut [u8]> {
341343
slice_write_vectored(&mut self.pos, self.inner, bufs)
342344
}
343345

346+
#[inline]
344347
fn flush(&mut self) -> io::Result<()> { Ok(()) }
345348
}
346349

@@ -354,6 +357,7 @@ impl Write for Cursor<&mut Vec<u8>> {
354357
vec_write_vectored(&mut self.pos, self.inner, bufs)
355358
}
356359

360+
#[inline]
357361
fn flush(&mut self) -> io::Result<()> { Ok(()) }
358362
}
359363

@@ -367,6 +371,7 @@ impl Write for Cursor<Vec<u8>> {
367371
vec_write_vectored(&mut self.pos, &mut self.inner, bufs)
368372
}
369373

374+
#[inline]
370375
fn flush(&mut self) -> io::Result<()> { Ok(()) }
371376
}
372377

@@ -382,6 +387,7 @@ impl Write for Cursor<Box<[u8]>> {
382387
slice_write_vectored(&mut self.pos, &mut self.inner, bufs)
383388
}
384389

390+
#[inline]
385391
fn flush(&mut self) -> io::Result<()> { Ok(()) }
386392
}
387393

0 commit comments

Comments
 (0)