title: Idiomatic way to parse binary data into primitive types
body: <p>I've written the following method to parse binary data from a gzipped file using <a href="https://github.com/alexcrichton/flate2-rs" rel="noreferrer">GzDecoder from the Flate2 library</a></p>
  
  <pre><code>fn read_primitive&lt;T: Copy&gt;(reader: &amp;mut GzDecoder&lt;File&gt;) -&gt; std::io::Result&lt;T&gt;
  {
      let sz = mem::size_of::&lt;T&gt;();
      let mut vec =  Vec::&lt;u8&gt;::with_capacity(sz);
      let ret: T;
      unsafe{
          vec.set_len(sz);
          let mut s = &amp;mut vec[..];
          try!(reader.read(&amp;mut s));
  
          let ptr :*const u8 = s.as_ptr();
          ret = *(ptr as *const T)
      }
      Ok(ret)
  }
  </code></pre>
  
  <p>It works, but I'm not particularly happy with the code, especially with using the dummy vector and the temporary variable <code>ptr</code>. It all feels very inelegant to me and I'm sure there's a better way to do this. I'd be happy to hear any suggestions of how to clean up this code. </p>