title: How to safely get an immutable byte slice from a `&mut [u32]`?
body: <p>In a rather low level part of a project of mine, a function receives a mutable slice of primitive data (<code>&amp;mut [u32]</code> in this case). This data should be written to a writer in little endian. </p>
  
  <p>Now, this alone wouldn't be a problem, but all of this has to be fast. I measured my application and identified this as one of the critical paths. In particular, if the endianness doesn't need to be changed (since we're already on a little endian system), there shouldn't be any overhead.</p>
  
  <p>This is my code (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=8c87ec453e0a255c723f7a20fab1e290" rel="noreferrer">Playground</a>):</p>
  
  <pre class="lang-rust prettyprint-override"><code>use std::{io, mem, slice};
  
  fn write_data(mut w: impl io::Write, data: &amp;mut [u32]) -&gt; Result&lt;(), io::Error&gt; {
      adjust_endianness(data);
  
      // Is this safe?
      let bytes = unsafe {
          let len = data.len() * mem::size_of::&lt;u32&gt;();
          let ptr = data.as_ptr() as *const u8;
          slice::from_raw_parts(ptr, len)
      };
  
      w.write_all(bytes)
  }
  
  fn adjust_endianness(_: &amp;mut [u32]) {
      // implementation omitted
  }
  </code></pre>
  
  <p><code>adjust_endianness</code> changes the endianness in place (which is fine, since a wrong-endian <code>u32</code> is garbage, but still a valid <code>u32</code>).</p>
  
  <p>This code works, but the critical question is: <strong>Is this safe?</strong> In particular, at some point, <code>data</code> and <code>bytes</code> both exist, being one mutable and one immutable slice to the same data. That sounds very bad, right? </p>
  
  <p>On the other hand, I can do this:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let bytes = &amp;data[..];
  </code></pre>
  
  <p>That way, I also have those two slices. The difference is just that <code>data</code> is now borrowed. </p>
  
  <p><strong>Is my code safe or does it exhibit UB? Why? If it's not safe, how to safely do what I want to do?</strong></p>