Can NSInputStream.read(_:maxLength:) read less than maxLength even if more is available?

Can NSInputStream.read(_:maxLength:) return less bytes read even when more data available? I haven't found it in the docs

Use-case: we pass maxLength = 512, but actual reading of 512 bytes will do in 2 rounds: 256 in first round + 256 in second.

It's important for my use-case (encryption/decryption) not to have intermediate partial readings unless it's last "tail" part. Otherwise I might end-up encrypting different-length blocks & decryption will fail assuming different buffer length.

Accepted Reply

In general, don’t assume anything that isn’t guaranteed in the documentation. It would be perfectly legal for the next OS release to cap the read chunk at a maximum of (say) 42 bytes. If this would break your app logic, then you should program defensively to handle it.

Replies

In general, don’t assume anything that isn’t guaranteed in the documentation. It would be perfectly legal for the next OS release to cap the read chunk at a maximum of (say) 42 bytes. If this would break your app logic, then you should program defensively to handle it.

Scott J is correct here; you have to program to the API as it’s documented. Everything else is just implementation details.

As to those implementation details, they vary by stream type:

  • For a file system stream it’s very likely that you’ll get everything you ask for (except on the last call).

  • That’s definitely not the case for other types of streams, most notably network streams.

If you know that you’re working with a file, you could use an alternative API that’s document to avoid short reads, for example, read(upToCount:).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"