Restart NSInput based on NSData

I have an NSData that I would like to read as NSInputStream. That way, I can have a consistent API for processing both files and data in memory. As part of the processing, I would like to make sure that the stream starts with some set of bytes (if it is not, I need to process it differently). I would like to avoid reading the whole file into memory if it is of the wrong type.

So, I'm looking for either a way to rewind the stream, or a way to "peek" into the next bytes without moving the read pointer. If it's an NSInputStream created using a URL, I can use setProperty: forKey: on NSStreamFileCurrentOffsetKey, but it fancyly doesn't work on NSInputStream created from NSData (even if you would have thought it would be even easier to implement than the file version ) I cannot close and reopen the steam to reset the input pointer (this is not explicitly permitted by NSStream).

I can rework this problem using the NSData interface and -initWithContentsOfMappedFile, but I would prefer to stay with the NSStream approach if I can.

+4
source share
2 answers

I think I don’t understand anything. NSInputStream can receive data from three places: a socket, an NSData object, or a file. You did not say that you want to use a socket that leaves the other two as data sources. In addition, documents for NSStream say only file-based streams are available. (NSStream review, third paragraph)

Given this, I think an NSData object would be a better choice. An NSData object will process both files and bytes (which, I think, is what you mean by data in memory).

But you consider it and say that you prefer to adhere to flows. Is there any other consideration here?

(Edit) Sorry, I had to make this a real answer. My answer to the question you described is that using NSData is indeed the right solution.

If you prefer a different answer, please give more details.

+1
source

You can really search in NSInputStream that reads the file:

BOOL samplePositionAccepted = [iStream setProperty: [NSNumber numberWithUnsignedLong: samplePosition] forKey: NSStreamFileCurrentOffsetKey];

I am not sure if this works for NSData. (Sorry, I don’t have enough points to write a comment yet ...)

(Unfortunately, I did not see that you have already tried this ...)

+1
source

Source: https://habr.com/ru/post/1300768/


All Articles