tango.io.Buffer

License:

BSD style: see license.txt

Version:

Mar 2004: Initial release Dec 2006: Outback release

Authors:

Kris
class Buffer : IBuffer #
Buffer is central concept in Tango I/O. Each buffer acts as a queue (line) where items are removed from the front and new items are added to the back. Buffers are modeled by tango.io.model.IBuffer, and a concrete implementation is provided by this class.
Buffer can be read from and written to directly, though various data-converters and filters are often leveraged to apply structure to what might otherwise be simple raw data.

Buffers may also be tokenized by applying an Iterator. This can be handy when one is dealing with text input, and/or the content suits a more fluid format than most typical converters support. Iterator tokens are mapped directly onto buffer content (sliced), making them quite efficient in practice. Like other types of buffer client, multiple iterators can be mapped onto one common buffer and access will be serialized.

Buffers are sometimes memory-only, in which case there is nothing left to do when a client has consumed all the content. Other buffers are themselves bound to an external device called a conduit. When this is the case, a consumer will eventually cause a buffer to reload via its associated conduit and previous buffer content will be lost.

A similar approach is applied to clients which populate a buffer, whereby the content of a full buffer will be flushed to a bound conduit before continuing. Another variation is that of a memory-mapped buffer, whereby the buffer content is mapped directly to virtual memory exposed via the OS. This can be used to address large files as an array of content.

Direct buffer manipulation typically involves appending, as in the following example:

1
2
3
4
5
6
7
// create a small buffer
auto buf = new Buffer (256);

auto foo = "to write some D";

// append some text directly to it
buf.append ("now is the time for all good men ").append(foo);

Alternatively, one might use a formatter to append the buffer:

1
2
auto output = new TextOutput (new Buffer(256));
output.format ("now is the time for {} good men {}", 3, foo);

A slice() method will return all valid content within a buffer. GrowBuffer can be used instead, where one wishes to append beyond a specified limit.

A common usage of a buffer is in conjunction with a conduit, such as FileConduit. Each conduit exposes a preferred-size for its associated buffers, utilized during buffer construction:

1
2
auto file = new File ("name");
auto buf = new Buffer (file);

However, this is typically hidden by higher level constructors such as those exposed via the stream wrappers. For example:

1
auto input = new DataInput (new File ("name"));

There is indeed a buffer between the resultant stream and the file, but explicit buffer construction is unecessary in common cases.

An Iterator is constructed in a similar manner, where you provide it an input stream to operate upon. There's a variety of iterators available in the tango.io.stream package, and they are templated for each of utf8, utf16, and utf32. This example uses a line-iterator derivative to sweep a text file:

1
2
3
4
auto lines = new TextInput (new File ("name"));
foreach (line; lines)
         Cout(line).newline;
lines.close;

Buffers are useful for many purposes within Tango, but there are times when it may be more appropriate to sidestep them. For such cases, all conduit derivations (such as File) support array-based I/O via a pair of read() and write() methods.

invariant #
Ensure the buffer remains valid between method calls
this(IConduit conduit) #
Construct a buffer

Params:

conduitthe conduit to buffer

Remarks:

Construct a Buffer upon the provided conduit. A relevant buffer size is supplied via the provided conduit.
this(InputStream stream, size_t capacity) #
Construct a buffer

Params:

streaman input stream
capacitydesired buffer capacity

Remarks:

Construct a Buffer upon the provided input stream.
this(OutputStream stream, size_t capacity) #
Construct a buffer

Params:

streaman output stream
capacitydesired buffer capacity

Remarks:

Construct a Buffer upon the provided output stream.
this(size_t capacity = 0) #
Construct a buffer

Params:

capacitythe number of bytes to make available

Remarks:

Construct a Buffer with the specified number of bytes.
this(void[] data) #
Construct a buffer

Params:

datathe backing array to buffer within

Remarks:

Prime a buffer with an application-supplied array. All content is considered valid for reading, and thus there is no writable space initially available.
this(void[] data, size_t readable) #
Construct a buffer

Params:

datathe backing array to buffer within
readablethe number of bytes initially made readable

Remarks:

Prime buffer with an application-supplied array, and indicate how much readable data is already there. A write operation will begin writing immediately after the existing readable content.

This is commonly used to attach a Buffer instance to a local array.

IBuffer share(InputStream stream, size_t size = size_t.max) [static] #
Attempt to share an upstream Buffer, and create an instance where there not one available.

Params:

streaman input stream
sizea hint of the desired buffer size. Defaults to the conduit-defined size

Remarks:

If an upstream Buffer instances is visible, it will be shared. Otherwise, a new instance is created based upon the bufferSize exposed by the stream endpoint (conduit).
IBuffer share(OutputStream stream, size_t size = size_t.max) [static] #
Attempt to share an upstream Buffer, and create an instance where there not one available.

Params:

streaman output stream
sizea hint of the desired buffer size. Defaults to the conduit-defined size

Remarks:

If an upstream Buffer instances is visible, it will be shared. Otherwise, a new instance is created based upon the bufferSize exposed by the stream endpoint (conduit).
IBuffer setContent(void[] data) #
Reset the buffer content

Params:

datathe backing array to buffer within. All content is considered valid

Returns:

the buffer instance

Remarks:

Set the backing array with all content readable. Writing to this will either flush it to an associated conduit, or raise an Eof condition. Use clear() to reset the content (make it all writable).
IBuffer setContent(void[] data, size_t readable) #
Reset the buffer content

Params:

datathe backing array to buffer within
readablethe number of bytes within data considered valid

Returns:

the buffer instance

Remarks:

Set the backing array with some content readable. Writing to this will either flush it to an associated conduit, or raise an Eof condition. Use clear() to reset the content (make it all writable).
void[] slice() #
Retrieve the valid content

Returns:

a void[] slice of the buffer

Remarks:

Return a void[] slice of the buffer, from the current position up to the limit of valid content. The content remains in the buffer for future extraction.
void[] opSlice(size_t start, size_t end) [final] #
Return a void[] slice of the buffer from start to end, where end is exclusive
void[] slice(size_t size, bool eat = true) #
Access buffer content

Params:

sizenumber of bytes to access
eatwhether to consume the content or not

Returns:

the corresponding buffer slice when successful, or null if there's not enough data available (Eof; Eob).

Remarks:

Read a slice of data from the buffer, loading from the conduit as necessary. The specified number of bytes is sliced from the buffer, and marked as having been read when the 'eat' parameter is set true. When 'eat' is set false, the read position is not adjusted.

Note that the slice cannot be larger than the size of the buffer ~ use method fill(void[]) instead where you simply want the content copied, or use conduit.read() to extract directly from an attached conduit. Also note that if you need to retain the slice, then it should be .dup'd before the buffer is compressed or repopulated.

Examples:

1
2
3
4
5
// create a buffer with some content
auto buffer = new Buffer ("hello world");

// consume everything unread
auto slice = buffer.slice (buffer.readable);
size_t fill(void[] dst) #
Fill the provided buffer. Returns the number of bytes actually read, which will be less that dst.length when Eof has been reached and IConduit.Eof thereafter
void[] readExact(void* dst, size_t bytes) #
Copy buffer content into the provided dst

Params:

dstdestination of the content
bytessize of dst

Returns:

A reference to the populated content

Remarks:

Fill the provided array with content. We try to satisfy the request from the buffer content, and read directly from an attached conduit where more is required.
IBuffer append(void[] src) #
Append content

Params:

srcthe content to _append

Returns a chaining reference if all content was written. Throws an IOException indicating eof or eob if not.

Remarks:

Append an array to this buffer, and flush to the conduit as necessary. This is often used in lieu of a Writer.
IBuffer append(void* src, size_t length) #
Append content

Params:

srcthe content to _append
lengththe number of bytes in src

Returns a chaining reference if all content was written. Throws an IOException indicating eof or eob if not.

Remarks:

Append an array to this buffer, and flush to the conduit as necessary. This is often used in lieu of a Writer.
IBuffer append(IBuffer other) #
Append content

Params:

othera buffer with content available

Returns:

Returns a chaining reference if all content was written. Throws an IOException indicating eof or eob if not.

Remarks:

Append another buffer to this one, and flush to the conduit as necessary. This is often used in lieu of a Writer.
void consume(void[] x) #
Consume content from a producer

Params:

rawThe content to consume. This is consumed verbatim, and in raw binary format ~ no implicit conversions are performed.

Remarks:

This is often used in lieu of a Writer, and enables simple classes, such as FilePath and Uri, to emit content directly into a buffer (thus avoiding potential heap activity)

Examples:

1
2
3
auto path = new FilePath (somepath);

path.produce (&buffer.consume);
bool skip(int size) #
Move the current read location

Params:

sizethe number of bytes to move

Returns:

Returns true if successful, false otherwise.

Remarks:

Skip ahead by the specified number of bytes, streaming from the associated conduit as necessary.

Can also reverse the read position by 'size' bytes, when size is negative. This may be used to support lookahead operations. Note that a negative size will fail where there is not sufficient content available in the buffer (can't _skip beyond the beginning).

bool next(size_t delegate (void[]) scan) #
Iterator support

Params:

scanthe delagate to invoke with the current content

Returns:

Returns true if a token was isolated, false otherwise.

Remarks:

Upon success, the delegate should return the byte-based index of the consumed pattern (tail end of it). Failure to match a pattern should be indicated by returning an IConduit.Eof

Each pattern is expected to be stripped of the delimiter. An end-of-file condition causes trailing content to be placed into the token. Requests made beyond Eof result in empty matches (length is zero).

Note that additional iterator and/or reader instances will operate in lockstep when bound to a common buffer.

bool compress(bool yes) [final] #
Configure the compression strategy for iterators

Remarks:

Iterators will tend to compress the buffered content in order to maximize space for new data. You can disable this behaviour by setting this boolean to false
size_t readable() #
Available content

Remarks:

Return count of _readable bytes remaining in buffer. This is calculated simply as limit() - position()
size_t writable() #
Available space

Remarks:

Return count of _writable bytes available in buffer. This is calculated simply as capacity() - limit()
size_t reserve(size_t space) [final] #
Reserve the specified space within the buffer, compressing existing content as necessary to make room
Returns the current read point, after compression if that was required
size_t writer(size_t delegate (void[]) dg) #
Write into this buffer

Params:

dgthe callback to provide buffer access to

Returns:

Returns whatever the delegate returns.

Remarks:

Exposes the raw data buffer at the current _write position, The delegate is provided with a void[] representing space available within the buffer at the current _write position.

The delegate should return the appropriate number of bytes if it writes valid content, or IConduit.Eof on error.

size_t reader(size_t delegate (void[]) dg) #
Read directly from this buffer

Params:

dgcallback to provide buffer access to

Returns:

Returns whatever the delegate returns.

Remarks:

Exposes the raw data buffer at the current _read position. The delegate is provided with a void[] representing the available data, and should return zero to leave the current _read position intact.

If the delegate consumes data, it should return the number of bytes consumed; or IConduit.Eof to indicate an error.

IBuffer compress() #
Compress buffer space

Returns:

the buffer instance

Remarks:

If we have some data left after an export, move it to front-of-buffer and set position to be just after the remains. This is for supporting certain conduits which choose to write just the initial portion of a request.

Limit is set to the amount of data remaining. Position is always reset to zero.

size_t fill(InputStream src) #
Fill buffer from the specific conduit

Returns:

Returns the number of bytes read, or Conduit.Eof

Remarks:

Try to _fill the available buffer with content from the specified conduit. We try to read as much as possible by clearing the buffer when all current content has been eaten. If there is no space available, nothing will be read.
size_t drain(OutputStream dst) [final] #
Drain buffer content to the specific conduit

Returns:

Returns the number of bytes written

Remarks:

Write as much of the buffer that the associated conduit can consume. The conduit is not obliged to consume all content, so some may remain within the buffer.

Throws an IOException on premature Eof.

bool truncate(size_t length) #
Truncate buffer content

Remarks:

Truncate the buffer within its extent. Returns true if the new length is valid, false otherwise.
size_t limit() #
Access buffer limit

Returns:

Returns the limit of readable content within this buffer.

Remarks:

Each buffer has a capacity, a limit, and a position. The capacity is the maximum content a buffer can contain, limit represents the extent of valid content, and position marks the current read location.
size_t capacity() #
Access buffer capacity

Returns:

Returns the maximum capacity of this buffer

Remarks:

Each buffer has a capacity, a limit, and a position. The capacity is the maximum content a buffer can contain, limit represents the extent of valid content, and position marks the current read location.
size_t position() #
Access buffer read position

Returns:

Returns the current read-position within this buffer

Remarks:

Each buffer has a capacity, a limit, and a position. The capacity is the maximum content a buffer can contain, limit represents the extent of valid content, and position marks the current read location.
IBuffer setConduit(IConduit conduit) #
Set external conduit

Params:

conduitthe conduit to attach to

Remarks:

Sets the external conduit associated with this buffer.

Buffers do not require an external conduit to operate, but it can be convenient to associate one. For example, methods fill() & drain() use it to import/export content as necessary.

IBuffer output(OutputStream boutput) [final] #
Set output stream

Params:

boutputthe stream to attach to

Remarks:

Sets the external output stream associated with this buffer.

Buffers do not require an external stream to operate, but it can be convenient to associate one. For example, methods fill & drain use them to import/export content as necessary.

IBuffer input(InputStream binput) [final] #
Set input stream

Params:

binputthe stream to attach to

Remarks:

Sets the external input stream associated with this buffer.

Buffers do not require an external stream to operate, but it can be convenient to associate one. For example, methods fill & drain use them to import/export content as necessary.

void[] getContent() [protected] #
Access buffer content

Remarks:

Return the entire backing array. Exposed for subclass usage only
void copy(void * src, size_t size) [protected] #
Copy content into buffer

Params:

srcthe soure of the content
sizethe length of content at src

Remarks:

Bulk _copy of data from 'src'. The new content is made available for reading. This is exposed for subclass use only
size_t expand(size_t size) [protected] #
Expand existing buffer space

Returns:

Available space, without any expansion

Remarks:

Make some additional room in the buffer, of at least the given size. This can be used by subclasses as appropriate
T[] convert(T)(void[] x) [static] #
Cast to a target type without invoking the wrath of the runtime checks for misalignment. Instead, we truncate the array length
IBuffer buffer() #
Buffered Interface
InputBuffer bin() #
Return a buffered output, or null if there's not one already available.
OutputBuffer bout() #
Return a buffered output, or null if there's not one already available.
char[] toString() [override] #
Stream & Conduit Interfaces
Return the name of this conduit
void error(char[] msg) [final] #
Generic IOException thrower

Params:

msga text message describing the exception reason

Remarks:

Throw an IOException with the provided message
OutputStream flush() [override] #
Flush all buffer content to the specific conduit

Remarks:

Flush the contents of this buffer. This will block until all content is actually flushed via the associated conduit, whereas drain() will not.

Do nothing where a conduit is not attached, enabling memory buffers to treat flush as a noop.

Throws an IOException on premature Eof.

InputStream clear() [override] #
Clear buffer content

Remarks:

Reset 'position' and 'limit' to zero. This effectively clears all content from the buffer.
OutputStream copy(InputStream src, size_t max = -1) [override] #
Copy content via this buffer from the provided src conduit.

Remarks:

The src conduit has its content transferred through this buffer via a series of fill & drain operations, until there is no more content available. The buffer content should be explicitly flushed by the caller.

Throws an IOException on premature eof

void[] load(size_t max = -1) #
Load the bits from a stream, and return them all in an array. The dst array can be provided as an option, which will be expanded as necessary to consume the input.
Returns an array representing the content, and throws IOException on error
size_t read(void[] dst) [override] #
Transfer content into the provided dst

Params:

dstdestination of the content

Returns:

return the number of bytes read, which may be less than dst.length. Eof is returned when no further content is available.

Remarks:

Populates the provided array with content. We try to satisfy the request from the buffer content, and read directly from an attached conduit when the buffer is empty.
size_t write(void[] src) [override] #
Emulate OutputStream.write()

Params:

srcthe content to write

Returns:

return the number of bytes written, which may be less than provided (conceptually).

Remarks:

Appends src content to the buffer, flushing to an attached conduit as necessary. An IOException is thrown upon write failure.
IConduit conduit() [override, final] #
Access configured conduit

Returns:

Returns the conduit associated with this buffer. Returns null if the buffer is purely memory based; that is, it's not backed by some external medium.

Remarks:

Buffers do not require an external conduit to operate, but it can be convenient to associate one. For example, methods fill() & drain() use it to import/export content as necessary.
size_t bufferSize() [override, final] #
Return a preferred size for buffering conduit I/O
bool isAlive() [override, final] #
Is the conduit alive?
OutputStream output() [final] #
Exposes configured output stream

Returns:

Returns the OutputStream associated with this buffer. Returns null if the buffer is not attached to an output; that is, it's not backed by some external medium.

Remarks:

Buffers do not require an external stream to operate, but it can be convenient to associate them. For example, methods fill & drain use them to import/export content as necessary.
InputStream input() [final] #
Exposes configured input stream

Returns:

Returns the InputStream associated with this buffer. Returns null if the buffer is not attached to an input; that is, it's not backed by some external medium.

Remarks:

Buffers do not require an external stream to operate, but it can be convenient to associate them. For example, methods fill & drain use them to import/export content as necessary.
void detach() [override, final] #
Release external rebinputs
void close() [override] #
Close the stream

Remarks:

Propagate request to an attached OutputStream (this is a requirement for the OutputStream interface)
class GrowBuffer : Buffer #
Subclass to provide support for content growth. This is handy when you want to keep a buffer around as a scratchpad.
this(size_t size = 1024, size_t increment = 1024) #
Create a GrowBuffer with the specified initial size.
this(IConduit conduit, size_t size = 1024) #
Create a GrowBuffer with the specified initial size.
void[] slice(size_t size, bool eat = true) [override] #
Read a chunk of data from the buffer, loading from the conduit as necessary. The specified number of bytes is loaded into the buffer, and marked as having been read when the 'eat' parameter is set true. When 'eat' is set false, the read position is not adjusted.
Returns the corresponding buffer slice when successful.
IBuffer append(void * src, size_t length) [override] #
Append an array of data to this buffer. This is often used in lieu of a Writer.
size_t fill(InputStream src) [override] #
Try to fill the available buffer with content from the specified conduit.
Returns the number of bytes read, or IConduit.Eof
size_t fill(size_t size = size_t.max) #
Expand and consume the conduit content, up to the maximum size indicated by the argument or until conduit.Eof
Returns the number of bytes in the buffer
size_t expand(size_t size) [override] #
Expand existing buffer space

Returns:

Available space after adjustment

Remarks:

Make some additional room in the buffer, of at least the given size. This can be used by subclasses as appropriate