title: What is the correct way to fill a C string pointer from Rust?
body: <p>I have a FFI signature I need to implement:</p>
  
  <pre><code>pub unsafe extern fn f(header_size: u32, header_ptr: *mut u8) -&gt; i32;
  </code></pre>
  
  <p>A FFI caller is expected to provide a buffer <code>header_ptr</code> and the size of that buffer <code>header_size</code>. Rust is expected to fill a string into that buffer up to <code>header_size</code>, and return <code>0</code> if successful. The FFI caller is expected to interpret the string as ASCII.</p>
  
  <p>How can I fill that buffer the most idiomatic way, given I have a <code>headers: &amp;str</code> with the content I want to provide?</p>
  
  <p>Right now I have:</p>
  
  <pre><code>let header_bytes = slice::from_raw_parts_mut(header_ptr, header_size as usize);
  
  if header_bytes.len() &lt; headers.len() { return Errors::IndexOutOfBounds as i32; }
  
  for (i, byte) in headers.as_bytes().iter().enumerate() {
      header_bytes[i] = *byte;
  }
  </code></pre>
  
  <p>But that feels wrong.</p>
  
  <p><strong>Edit</strong>, I think this is not an exact duplicate to <a href="https://stackoverflow.com/questions/28219231/how-to-idiomatically-copy-a-slice">this</a> because my question relates to strings, and IIRC there were special considerations when converting &amp;str to CStrings. </p>