Use the same large buffer as a smaller one

Is it possible to read from a TCP socket at most n bytes? bytes_read = socket.read(buffer) reads at most buffer.size bytes, but that’s just too much in certain cases. #read unfortunately does not accept any max-size param.

If this is not possible, can I have a buffer (something like Bytes.new(4096)) and limit it’s size with a cast-like method? Something like buffer.as(... a 512 bytes long buffer...), buffer.first_slice_of(512) or buffer.shrinked_to(512) or something like this, that is essentially the same memory, but looks like a smaller sized buffer to read?

Sure: buffer[0, size] changes the available buffer size.

2 Likes

@bsanyi I don’t know about your use case, but I’ve never had to consume a buffer populated by IO#read. Are you unable to use the socket as a stream?