1

I'd like to parse some binary data. In Java I would use ByteBuffer class, which has really nifty methods like getInt(), getChar(), etc. which will return you the correct length of data, and advance the (internal) "read head".

The closest I could find in Swift is NSInputStream, which requires you manually manage a buffer, set the number of bytes to read, ensure the correct amount was read, etc. It's quite clunky. Are there any better APIs I'm overlooking?

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • What are you using this for? Would NSCoding suit your needs? – jtbandes Dec 31 '16 at 06:33
  • @jtbandes I'm trying to parse `.ani` files. As far as I know, `NSCoder` only deals with decoding data encoded with `NSCoder` – Alexander Dec 31 '16 at 06:40
  • So are you using NSData at all, or NSFileHandle? It would be pretty simple to make a couple extensions on NSFileHandle to do what you want. – jtbandes Dec 31 '16 at 06:41
  • @jtbandes Currently, `NSData`, but it's flexible. `NSFileHandle` looks promising – Alexander Dec 31 '16 at 06:43
  • For testability you could abstract over them with a protocol e.g. `ContiguouslyReadable`. Then you could make a simple struct which wraps an NSData along with a "read head", so you don't have to actually use a file handle if you don't want to open a file. – jtbandes Dec 31 '16 at 06:45
  • @jtbandes How would you read from the `NSData`? `func getBytes(UnsafeMutableRawPointer, range: NSRange)`? – Alexander Dec 31 '16 at 06:50
  • @MartinR As I mention in my question, I'm aware of `(NS)InputStream`. But manually reading into a buffer, managing the size of the buffer, and the amount actually read, etc. is quite annoying. Ideally, having something with simple functions like `getInt`, `getBool`, etc. would be really convenient. – Alexander Dec 31 '16 at 07:06
  • Yes I realized that and deleted my previous comment. I am not aware of existing methods like that. If you want to add them as extensions, a generic approach as in http://stackoverflow.com/questions/33356178/read-integertype-from-nsinputstream might help. – Martin R Dec 31 '16 at 07:16
  • @MartinR Oh that's pretty nice, I'll check it out! – Alexander Dec 31 '16 at 07:21
  • @MartinR Am I missing something? I can't `InputStream` to serve me any bytes, even though the file is certainly available and non empty. http://i.imgur.com/bCkl41l.png – Alexander Dec 31 '16 at 07:26
  • You have to `open()` a stream ... – Martin R Dec 31 '16 at 07:27
  • @MartinR Hahahaha I didn't see it! It's tucked away in the super class. Thanks! – Alexander Dec 31 '16 at 07:28

0 Answers0