Buffered File Writer
DatadogPhone screenMedium
A file accepts writes, and every write to it is slow. You implement a writer that sits in front of the file and collects characters in an in-memory buffer, so the file receives fewer, larger writes. The buffer holds at most capacity characters, and every character counts as one byte. When the buffer holds exactly capacity characters, its contents go to the file as a single write and the buffer is emptied. Characters reach the file in the order they were written; none are lost or sent twice. Each test creates one writer and checks the return value of every operation.
Part 1: Buffered writes and flush
Implement a writer that batches characters before they reach a slow file.
__init__(capacity) sets the buffer limit capacity.
write(data) appends the characters of data to the buffer. Each time the buffer reaches capacity characters, its contents are sent to the file as one string and the buffer is emptied; the rest of data then keeps filling the buffer, so one call may send several strings. Return the list of strings sent during this call, in order.
flush() sends whatever the buffer currently holds as one string and empties it, returning that string in a list. Flushing an empty buffer sends nothing and returns an empty list.
Both methods return an empty list when nothing was sent.
- Example 1
- init
[8]- operations
[["write",["abc"]],["write",["defgh"]],["write",["ij"]],["flush",[]],["flush",[]]]- Output
[[],["abcdefgh"],[],["ij"],[]]
Why:
abcleaves 5 free slots, so the next write fills the buffer exactly andabcdefghgoes out as one write.ijwaits in the buffer untilflushsends it; the secondflushfinds the buffer empty and sends nothing.
Constraints
1 <= capacity <= 10^41 <= len(data) <= 10^5datacontains only printable ASCII characters1 <= len(operations) <= 10^4