Repository: alex/rust-asn1 (language: rust)

Issue:
Incorrect Serializing of Large Numbers
[In this code, large numbers are improperly handled.](https://github.com/alex/rust-asn1/blame/c042de029a132e6982b91cebfcc6a060d2a9daae/src/types.rs#L598)

This is an example to demonstrate (I just copied the code out for ease of replication):
```
fn main() {
    let mut dest: Vec<u8> = Vec::new();
    
    let number: u64 = 12356915591483590945;
    let s = &number;

    let mut num_bytes = 1;
    let mut v: u64 = *s;
    #[allow(unused_comparisons)]
    while v > 127 || (false && v < (-128i64) as u64) {
        num_bytes += 1;
        v = v.checked_shr(8).unwrap_or(0);
    }
    
    println!("Num Bytes: {}", num_bytes);

    for i in (1..num_bytes + 1).rev() {
        dest.push((s >> ((i - 1) * 8)) as u8);
    }
}
```


Discussion / hints:
Can you explain in a bit more detail why you think this is serialized incorrectly?
My apologies, yes. If you try to run the code, it will crash. The number of bytes will, for large numbers, be 9 instead of 8.
When I attempt to serialize this value, I get `b"\x02\x09\x00\xab\x7c\x95\x42\xbd\xdd\x89\x21"` (which properly round-trips). Can you provide a minimal example, using the rust-asn1 public API that reproduces your issue?
Ah it seems this issue doesn't reproduce anymore, I guess the project I was attempting to run was using an older version of the library (0.8.6 seems to have the issue). Sorry about that! 
Glad it's fixed. I'll add a test case for this and then close. Thanks.

Fix patch:
diff --git a/src/writer.rs b/src/writer.rs
index 1cbceec..a169fb8 100644
--- a/src/writer.rs
+++ b/src/writer.rs
@@ -375,6 +375,14 @@ mod tests {
         ]);
     }
 
+    #[test]
+    fn test_write_u64() {
+        assert_writes::<u64>(&[(
+            12356915591483590945,
+            b"\x02\x09\x00\xab\x7c\x95\x42\xbd\xdd\x89\x21",
+        )]);
+    }
+
     #[test]
     fn test_write_i32() {
         assert_writes::<i32>(&[


Test patch:
diff --git a/tests/roundtrip_tests.rs b/tests/roundtrip_tests.rs
index 556601e..0c496f4 100644
--- a/tests/roundtrip_tests.rs
+++ b/tests/roundtrip_tests.rs
@@ -20,3 +20,10 @@ fn test_i8() {
         assert_roundtrips::<i8>(i);
     }
 }
+
+#[test]
+fn test_u64() {
+    for v in [0, 12356915591483590945, u64::MAX] {
+        assert_roundtrips::<u64>(v);
+    }
+}