title: Is there any hope to cast ForeignPtr to ByteArray# (for a function :: ByteString -> Vector)
body: <p>For performance reasons I would like a zero-copy cast of <code>ByteString</code> (strict, for now) to a <code>Vector</code>.  Since <code>Vector</code> is just a <code>ByteArray#</code> under the hood, and <code>ByteString</code> is a <code>ForeignPtr</code> this might look something like:</p>
  
  <pre><code>caseBStoVector :: ByteString -&gt; Vector a
  caseBStoVector (BS fptr off len) =
      withForeignPtr fptr $ \ptr -&gt; do
          let ptr' = plusPtr ptr off
              p = alignPtr ptr' (alignment (undefined :: a))
              barr = ptrToByteArray# p len  -- I want this function, or something similar 
              barr' = ByteArray barr
              alignI = minusPtr p ptr
              size = (len-alignI) `div` sizeOf (undefined :: a)
          return (Vector 0 size barr')
  </code></pre>
  
  <p>That certainly isn't right.  Even with the missing function <code>ptrToByteArray#</code> this seems to need to escape the <code>ptr</code> outside of the <code>withForeignPtr</code> scope.  So my quesetions are:</p>
  
  <ol>
  <li><p>This post probably advertises my primitive understanding of <code>ByteArray#</code>, if anyone can talk a bit about <code>ByteArray#</code>, it's representation, how it is managed (GCed), etc I'd be grateful.</p></li>
  <li><p>The fact that <code>ByteArray#</code> lives on the GCed heap and <code>ForeignPtr</code> is external seems to be a fundamental issue - all the access operations are different.  Perhaps I should look at redefining <code>Vector</code> from <code>= ByteArray !Int !Int</code> to something with another indirection?  Someing like <code>= Location !Int !Int</code> where <code>data Location = LocBA ByteArray | LocFPtr ForeignPtr</code> and provide wrapping operations for both those types?  This indirection might hurt performance too much though.</p></li>
  <li><p>Failing to marry these two together, maybe I can just access arbitrary element types in a <code>ForeignPtr</code> in a more efficient manner.  Does anyone know of a library that treats <code>ForeignPtr</code> (or <code>ByteString</code>) as an array of arbitrary <code>Storable</code> or <code>Primitive</code> types?  This would still lose me the stream fusion and tuning from the Vector package.</p></li>
  </ol>