Skip to content

Instantly share code, notes, and snippets.

@cgaebel
Created November 22, 2014 06:47
Show Gist options
  • Select an option

  • Save cgaebel/8ddab3ab62c07a516f10 to your computer and use it in GitHub Desktop.

Select an option

Save cgaebel/8ddab3ab62c07a516f10 to your computer and use it in GitHub Desktop.
commit 8280d46c5b815cdb979c37e4b725fe4d28e9ae5c
Author: Clark Gaebel <[email protected]>
Date: Fri Nov 21 12:47:28 2014 -0800
fixed undefined behavior in u8 peeking
diff --git a/src/bufspan.rs b/src/bufspan.rs
index 7788949..b517e71 100644
--- a/src/bufspan.rs
+++ b/src/bufspan.rs
@@ -140,7 +140,7 @@ impl<Buf: Iobuf> BufSpan<Buf> {
///
/// Returns `None` if the fast path was taken and nothing more needs to be
/// done. Returns `Some` if we need to do a slow push.
- #[inline]
+ #[inline(always)]
fn try_to_extend(&mut self, b: Buf) -> Option<Buf> {
if b.len() == 0 { return None; }
@@ -197,7 +197,7 @@ impl<Buf: Iobuf> BufSpan<Buf> {
/// assert_eq!(s.count_bytes() as uint, "hello world".len());
/// assert_eq!(s.iter().count(), 3);
/// ```
- #[inline]
+ #[inline(always)]
pub fn push(&mut self, b: Buf) {
match self.try_to_extend(b) {
None => {},
diff --git a/src/raw.rs b/src/raw.rs
index 1b736a7..d85c2c1 100644
--- a/src/raw.rs
+++ b/src/raw.rs
@@ -791,8 +791,13 @@ impl<'a> RawIobuf<'a> {
let mut x: T = FromPrimitive::from_u8(0).unwrap();
- for i in iter::range(0, bytes) {
- x = self.get_at::<T>(pos+i) | (x << 8);
+ // Left shift by 8 is undefined for u8.
+ if bytes == 1 {
+ x = self.get_at::<T>(pos);
+ } else {
+ for i in iter::range(0, bytes) {
+ x = self.get_at::<T>(pos+i) | (x << 8);
+ }
}
x
@@ -1008,3 +1013,13 @@ fn poke_le() {
let expected = [ 4,3,2,1 ];
unsafe { assert_eq!(b.as_window_slice(), expected.as_slice()); }
}
+
+
+#[test]
+fn peek_be_u8() {
+ use iobuf::Iobuf;
+ use impls::ROIobuf;
+
+ let b = ROIobuf::from_str("abc");
+ assert_eq!(b.peek_be(0), Ok(b'a'));
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment