An idiomatic way to take a substring of a byte string

I need to use widely:

slice :: Int -> Int -> ByteString -> ByteString slice start len = take len . drop start 

Question with two parts:

  • Does it already have a name? I can't find anything looking for this type in Hoogle, but it looks like it should be a really general need. I also tried to find (Int, Int) -> ByteString -> ByteString and some versions of flip 'd. I also tried to find versions of [a] to see if there was a common name.
  • Is there a better way to write this?

I'm suspicious that I am doing something wrong, because I strongly expected to find many people who went the same way, but my google-fu did not find anything.

+7
source share
2 answers

The idiomatic way is through take and drop , which has O (1) complexity with strict bytes.

slice not provided to discourage the use of unsafe indexing operations.

+6
source

According to the documentation, there is no such function. Currently strict ByteStrings are presented as a pointer to the beginning of the pinned memory , offset, and length. So your implementation is the best way to do splice. However, you should be careful with splices, because bytestrings splicing takes up the same space as the original bytestring value. To avoid this, you can copy byte splicing, but this is not always necessary.

+1
source

All Articles