2

I'm trying to write a simple function to transform ByteStrings with given ratio. Quantity of xored bits depends on the length and ratio.

rr <- randomRIO (0, BL.length bs)
let howMuch = floor $ (ratio args) * (fromIntegral rr)
transformIndexes <- replicateM howMuch $ randomRange (0, BL.length w)

What is the most efficient way to transform the ByteString value bs?

My first idea was to build another zero-filled ByteString of the same length with xored bits on random positions and then use BL.zipWith xor, but I'm afraid it's not the most efficient way because input bs can be pretty big.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • 1
    Any specific reason why bytestring, rather than a mutable array or an unboxed vector or something? – MathematicalOrchid Sep 22 '15 at 15:35
  • I'm working with multiple data structures which contains lazy ByteString, so I'm trying to generalize mutation of their parts. It will be pretty difficult to rewrite all of them. – Kirill Nesterov Sep 22 '15 at 15:43
  • 5
    If you are using lazy bytestrings, trust the garbage collector on this one. The chunks of the lazy bytestring will be deallocated if you don't need them anymore because they aren't referenced elsewhere, which is exactly when mutating them would be safe. Just be sure to avoid hanging on to references to the entire original bytestring or structures that hold the entire original bytestrings. – Cirdec Sep 22 '15 at 15:54
  • `ByteString` isn't really designed for mutation. There are tricks you can play with [unsafe bytestring operations](https://hackage.haskell.org/package/bytestring/docs/Data-ByteString-Unsafe.html) but you probably shouldn't. – dfeuer Sep 22 '15 at 16:23
  • He doesn't appear to actually need mutation, the question talks of computations involving bytestrings. – Thomas M. DuBuisson Sep 22 '15 at 16:47
  • 1
    I've gone ahead and change mutate/mutation to transform. Hopefully this makes the question less ambiguous. If the OP recognizes he actually wants to mutate the values he can re-edit his question or rollback. – Bakuriu Sep 22 '15 at 16:55
  • Yes, that's right. I've used term mutation from fuzz testing, not the mutation of memory or and object. Thanks for fixing question. – Kirill Nesterov Sep 23 '15 at 10:16

0 Answers0