Feature #17833
Updated by dsisnero (Dominic Sisneros) over 3 years ago
``` ruby f ba = File.open(FILENAME,'rb') bytearray = ByteArray.new(File.size(FILENAME)) ByteArray.new(8) # ByteArray implements memoryview f.readinto(bytearray) ``` First, a ByteaArray is created and pre-allocated to mv_at_4 = Fiddle::MemoryView.new(ba)[4..-1] f = File.open('/dev/urandom', 'rb'){|s| s.readinto(mv_at_4) # write the size content of the data we're going /dev/urandom from offset 4 to read into it. The pre-allocation is important - since readinto directly accesses the internal buffer end of the bytearray, it won't write more than has been allocated. Next, the file.readinto method is used to read the data directly into the bytearray's internal storage, without going via temporary buffers. effectively reading only 4 bytes ``` # Related #17834 #17831