3 * Copyright 2004--2010, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #ifndef TALK_BASE_STREAM_H_
29 #define TALK_BASE_STREAM_H_
33 #include "talk/base/basictypes.h"
34 #include "talk/base/buffer.h"
35 #include "talk/base/criticalsection.h"
36 #include "talk/base/logging.h"
37 #include "talk/base/messagehandler.h"
38 #include "talk/base/messagequeue.h"
39 #include "talk/base/scoped_ptr.h"
40 #include "talk/base/sigslot.h"
44 ///////////////////////////////////////////////////////////////////////////////
45 // StreamInterface is a generic asynchronous stream interface, supporting read,
46 // write, and close operations, and asynchronous signalling of state changes.
47 // The interface is designed with file, memory, and socket implementations in
48 // mind. Some implementations offer extended operations, such as seeking.
49 ///////////////////////////////////////////////////////////////////////////////
51 // The following enumerations are declared outside of the StreamInterface
52 // class for brevity in use.
54 // The SS_OPENING state indicates that the stream will signal open or closed
56 enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
58 // Stream read/write methods return this value to indicate various success
59 // and failure conditions described below.
60 enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
62 // StreamEvents are used to asynchronously signal state transitionss. The flags
64 // SE_OPEN: The stream has transitioned to the SS_OPEN state
65 // SE_CLOSE: The stream has transitioned to the SS_CLOSED state
66 // SE_READ: Data is available, so Read is likely to not return SR_BLOCK
67 // SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
68 enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
72 struct StreamEventData : public MessageData {
74 StreamEventData(int ev, int er) : events(ev), error(er) { }
77 class StreamInterface : public MessageHandler {
80 MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
83 virtual ~StreamInterface();
85 virtual StreamState GetState() const = 0;
87 // Read attempts to fill buffer of size buffer_len. Write attempts to send
88 // data_len bytes stored in data. The variables read and write are set only
89 // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
90 // Read and Write return a value indicating:
91 // SR_ERROR: an error occurred, which is returned in a non-null error
92 // argument. Interpretation of the error requires knowledge of the
93 // stream's concrete type, which limits its usefulness.
94 // SR_SUCCESS: some number of bytes were successfully written, which is
95 // returned in a non-null read/write argument.
96 // SR_BLOCK: the stream is in non-blocking mode, and the operation would
97 // block, or the stream is in SS_OPENING state.
98 // SR_EOS: the end-of-stream has been reached, or the stream is in the
100 virtual StreamResult Read(void* buffer, size_t buffer_len,
101 size_t* read, int* error) = 0;
102 virtual StreamResult Write(const void* data, size_t data_len,
103 size_t* written, int* error) = 0;
104 // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
105 // signalled as a result of this call.
106 virtual void Close() = 0;
108 // Streams may signal one or more StreamEvents to indicate state changes.
109 // The first argument identifies the stream on which the state change occured.
110 // The second argument is a bit-wise combination of StreamEvents.
111 // If SE_CLOSE is signalled, then the third argument is the associated error
112 // code. Otherwise, the value is undefined.
113 // Note: Not all streams will support asynchronous event signalling. However,
114 // SS_OPENING and SR_BLOCK returned from stream member functions imply that
115 // certain events will be raised in the future.
116 sigslot::signal3<StreamInterface*, int, int> SignalEvent;
118 // Like calling SignalEvent, but posts a message to the specified thread,
119 // which will call SignalEvent. This helps unroll the stack and prevent
121 void PostEvent(Thread* t, int events, int err);
122 // Like the aforementioned method, but posts to the current thread.
123 void PostEvent(int events, int err);
126 // OPTIONAL OPERATIONS
128 // Not all implementations will support the following operations. In general,
129 // a stream will only support an operation if it reasonably efficient to do
130 // so. For example, while a socket could buffer incoming data to support
131 // seeking, it will not do so. Instead, a buffering stream adapter should
134 // Even though several of these operations are related, you should
135 // always use whichever operation is most relevant. For example, you may
136 // be tempted to use GetSize() and GetPosition() to deduce the result of
137 // GetAvailable(). However, a stream which is read-once may support the
138 // latter operation but not the former.
141 // The following four methods are used to avoid copying data multiple times.
143 // GetReadData returns a pointer to a buffer which is owned by the stream.
144 // The buffer contains data_len bytes. NULL is returned if no data is
145 // available, or if the method fails. If the caller processes the data, it
146 // must call ConsumeReadData with the number of processed bytes. GetReadData
147 // does not require a matching call to ConsumeReadData if the data is not
148 // processed. Read and ConsumeReadData invalidate the buffer returned by
150 virtual const void* GetReadData(size_t* data_len) { return NULL; }
151 virtual void ConsumeReadData(size_t used) {}
153 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
154 // The buffer has a capacity of buf_len bytes. NULL is returned if there is
155 // no buffer available, or if the method fails. The call may write data to
156 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
157 // written. GetWriteBuffer does not require a matching call to
158 // ConsumeWriteData if no data is written. Write, ForceWrite, and
159 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
160 // TODO: Allow the caller to specify a minimum buffer size. If the specified
161 // amount of buffer is not yet available, return NULL and Signal SE_WRITE
162 // when it is available. If the requested amount is too large, return an
164 virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; }
165 virtual void ConsumeWriteBuffer(size_t used) {}
167 // Write data_len bytes found in data, circumventing any throttling which
168 // would could cause SR_BLOCK to be returned. Returns true if all the data
169 // was written. Otherwise, the method is unsupported, or an unrecoverable
170 // error occurred, and the error value is set. This method should be used
171 // sparingly to write critical data which should not be throttled. A stream
172 // which cannot circumvent its blocking constraints should not implement this
174 // NOTE: This interface is being considered experimentally at the moment. It
175 // would be used by JUDP and BandwidthStream as a way to circumvent certain
176 // soft limits in writing.
177 //virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
178 // if (error) *error = -1;
182 // Seek to a byte offset from the beginning of the stream. Returns false if
183 // the stream does not support seeking, or cannot seek to the specified
185 virtual bool SetPosition(size_t position) { return false; }
187 // Get the byte offset of the current position from the start of the stream.
188 // Returns false if the position is not known.
189 virtual bool GetPosition(size_t* position) const { return false; }
191 // Get the byte length of the entire stream. Returns false if the length
193 virtual bool GetSize(size_t* size) const { return false; }
195 // Return the number of Read()-able bytes remaining before end-of-stream.
196 // Returns false if not known.
197 virtual bool GetAvailable(size_t* size) const { return false; }
199 // Return the number of Write()-able bytes remaining before end-of-stream.
200 // Returns false if not known.
201 virtual bool GetWriteRemaining(size_t* size) const { return false; }
203 // Return true if flush is successful.
204 virtual bool Flush() { return false; }
206 // Communicates the amount of data which will be written to the stream. The
207 // stream may choose to preallocate memory to accomodate this data. The
208 // stream may return false to indicate that there is not enough room (ie,
209 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
210 // function should not affect the existing state of data in the stream.
211 virtual bool ReserveSize(size_t size) { return true; }
214 // CONVENIENCE METHODS
216 // These methods are implemented in terms of other methods, for convenience.
219 // Seek to the start of the stream.
220 inline bool Rewind() { return SetPosition(0); }
222 // WriteAll is a helper function which repeatedly calls Write until all the
223 // data is written, or something other than SR_SUCCESS is returned. Note that
224 // unlike Write, the argument 'written' is always set, and may be non-zero
225 // on results other than SR_SUCCESS. The remaining arguments have the
226 // same semantics as Write.
227 StreamResult WriteAll(const void* data, size_t data_len,
228 size_t* written, int* error);
230 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
231 // until a non-SR_SUCCESS result is returned. 'read' is always set.
232 StreamResult ReadAll(void* buffer, size_t buffer_len,
233 size_t* read, int* error);
235 // ReadLine is a helper function which repeatedly calls Read until it hits
236 // the end-of-line character, or something other than SR_SUCCESS.
237 // TODO: this is too inefficient to keep here. Break this out into a buffered
238 // readline object or adapter
239 StreamResult ReadLine(std::string* line);
244 // MessageHandler Interface
245 virtual void OnMessage(Message* msg);
248 DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
251 ///////////////////////////////////////////////////////////////////////////////
252 // StreamAdapterInterface is a convenient base-class for adapting a stream.
253 // By default, all operations are pass-through. Override the methods that you
254 // require adaptation. Streams should really be upgraded to reference-counted.
255 // In the meantime, use the owned flag to indicate whether the adapter should
256 // own the adapted stream.
257 ///////////////////////////////////////////////////////////////////////////////
259 class StreamAdapterInterface : public StreamInterface,
260 public sigslot::has_slots<> {
262 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
264 // Core Stream Interface
265 virtual StreamState GetState() const {
266 return stream_->GetState();
268 virtual StreamResult Read(void* buffer, size_t buffer_len,
269 size_t* read, int* error) {
270 return stream_->Read(buffer, buffer_len, read, error);
272 virtual StreamResult Write(const void* data, size_t data_len,
273 size_t* written, int* error) {
274 return stream_->Write(data, data_len, written, error);
276 virtual void Close() {
280 // Optional Stream Interface
281 /* Note: Many stream adapters were implemented prior to this Read/Write
282 interface. Therefore, a simple pass through of data in those cases may
283 be broken. At a later time, we should do a once-over pass of all
284 adapters, and make them compliant with these interfaces, after which this
285 code can be uncommented.
286 virtual const void* GetReadData(size_t* data_len) {
287 return stream_->GetReadData(data_len);
289 virtual void ConsumeReadData(size_t used) {
290 stream_->ConsumeReadData(used);
293 virtual void* GetWriteBuffer(size_t* buf_len) {
294 return stream_->GetWriteBuffer(buf_len);
296 virtual void ConsumeWriteBuffer(size_t used) {
297 stream_->ConsumeWriteBuffer(used);
301 /* Note: This interface is currently undergoing evaluation.
302 virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
303 return stream_->ForceWrite(data, data_len, error);
307 virtual bool SetPosition(size_t position) {
308 return stream_->SetPosition(position);
310 virtual bool GetPosition(size_t* position) const {
311 return stream_->GetPosition(position);
313 virtual bool GetSize(size_t* size) const {
314 return stream_->GetSize(size);
316 virtual bool GetAvailable(size_t* size) const {
317 return stream_->GetAvailable(size);
319 virtual bool GetWriteRemaining(size_t* size) const {
320 return stream_->GetWriteRemaining(size);
322 virtual bool ReserveSize(size_t size) {
323 return stream_->ReserveSize(size);
325 virtual bool Flush() {
326 return stream_->Flush();
329 void Attach(StreamInterface* stream, bool owned = true);
330 StreamInterface* Detach();
333 virtual ~StreamAdapterInterface();
335 // Note that the adapter presents itself as the origin of the stream events,
336 // since users of the adapter may not recognize the adapted object.
337 virtual void OnEvent(StreamInterface* stream, int events, int err) {
338 SignalEvent(this, events, err);
340 StreamInterface* stream() { return stream_; }
343 StreamInterface* stream_;
345 DISALLOW_EVIL_CONSTRUCTORS(StreamAdapterInterface);
348 ///////////////////////////////////////////////////////////////////////////////
349 // StreamTap is a non-modifying, pass-through adapter, which copies all data
350 // in either direction to the tap. Note that errors or blocking on writing to
351 // the tap will prevent further tap writes from occurring.
352 ///////////////////////////////////////////////////////////////////////////////
354 class StreamTap : public StreamAdapterInterface {
356 explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
358 void AttachTap(StreamInterface* tap);
359 StreamInterface* DetachTap();
360 StreamResult GetTapResult(int* error);
362 // StreamAdapterInterface Interface
363 virtual StreamResult Read(void* buffer, size_t buffer_len,
364 size_t* read, int* error);
365 virtual StreamResult Write(const void* data, size_t data_len,
366 size_t* written, int* error);
369 scoped_ptr<StreamInterface> tap_;
370 StreamResult tap_result_;
372 DISALLOW_EVIL_CONSTRUCTORS(StreamTap);
375 ///////////////////////////////////////////////////////////////////////////////
376 // StreamSegment adapts a read stream, to expose a subset of the adapted
377 // stream's data. This is useful for cases where a stream contains multiple
378 // documents concatenated together. StreamSegment can expose a subset of
379 // the data as an independent stream, including support for rewinding and
381 ///////////////////////////////////////////////////////////////////////////////
383 class StreamSegment : public StreamAdapterInterface {
385 // The current position of the adapted stream becomes the beginning of the
386 // segment. If a length is specified, it bounds the length of the segment.
387 explicit StreamSegment(StreamInterface* stream);
388 explicit StreamSegment(StreamInterface* stream, size_t length);
390 // StreamAdapterInterface Interface
391 virtual StreamResult Read(void* buffer, size_t buffer_len,
392 size_t* read, int* error);
393 virtual bool SetPosition(size_t position);
394 virtual bool GetPosition(size_t* position) const;
395 virtual bool GetSize(size_t* size) const;
396 virtual bool GetAvailable(size_t* size) const;
399 size_t start_, pos_, length_;
400 DISALLOW_EVIL_CONSTRUCTORS(StreamSegment);
403 ///////////////////////////////////////////////////////////////////////////////
404 // NullStream gives errors on read, and silently discards all written data.
405 ///////////////////////////////////////////////////////////////////////////////
407 class NullStream : public StreamInterface {
410 virtual ~NullStream();
412 // StreamInterface Interface
413 virtual StreamState GetState() const;
414 virtual StreamResult Read(void* buffer, size_t buffer_len,
415 size_t* read, int* error);
416 virtual StreamResult Write(const void* data, size_t data_len,
417 size_t* written, int* error);
418 virtual void Close();
421 ///////////////////////////////////////////////////////////////////////////////
422 // FileStream is a simple implementation of a StreamInterface, which does not
423 // support asynchronous notification.
424 ///////////////////////////////////////////////////////////////////////////////
426 class FileStream : public StreamInterface {
429 virtual ~FileStream();
431 // The semantics of filename and mode are the same as stdio's fopen
432 virtual bool Open(const std::string& filename, const char* mode, int* error);
433 virtual bool OpenShare(const std::string& filename, const char* mode,
434 int shflag, int* error);
436 // By default, reads and writes are buffered for efficiency. Disabling
437 // buffering causes writes to block until the bytes on disk are updated.
438 virtual bool DisableBuffering();
440 virtual StreamState GetState() const;
441 virtual StreamResult Read(void* buffer, size_t buffer_len,
442 size_t* read, int* error);
443 virtual StreamResult Write(const void* data, size_t data_len,
444 size_t* written, int* error);
445 virtual void Close();
446 virtual bool SetPosition(size_t position);
447 virtual bool GetPosition(size_t* position) const;
448 virtual bool GetSize(size_t* size) const;
449 virtual bool GetAvailable(size_t* size) const;
450 virtual bool ReserveSize(size_t size);
452 virtual bool Flush();
454 #if defined(POSIX) && !defined(__native_client__)
455 // Tries to aquire an exclusive lock on the file.
456 // Use OpenShare(...) on win32 to get similar functionality.
461 // Note: Deprecated in favor of Filesystem::GetFileSize().
462 static bool GetSize(const std::string& filename, size_t* size);
465 virtual void DoClose();
470 DISALLOW_EVIL_CONSTRUCTORS(FileStream);
473 // A stream that caps the output at a certain size, dropping content from the
474 // middle of the logical stream and maintaining equal parts of the start/end of
475 // the logical stream.
476 class CircularFileStream : public FileStream {
478 explicit CircularFileStream(size_t max_size);
480 virtual bool Open(const std::string& filename, const char* mode, int* error);
481 virtual StreamResult Read(void* buffer, size_t buffer_len,
482 size_t* read, int* error);
483 virtual StreamResult Write(const void* data, size_t data_len,
484 size_t* written, int* error);
488 READ_MARKED, // Read 0 .. marked_position_
489 READ_MIDDLE, // Read position_ .. file_size
490 READ_LATEST, // Read marked_position_ .. position_ if the buffer was
491 // overwritten or 0 .. position_ otherwise.
494 size_t max_write_size_;
496 size_t marked_position_;
497 size_t last_write_position_;
498 ReadSegment read_segment_;
499 size_t read_segment_available_;
502 // A stream which pushes writes onto a separate thread and
503 // returns from the write call immediately.
504 class AsyncWriteStream : public StreamInterface {
506 // Takes ownership of the stream, but not the thread.
507 AsyncWriteStream(StreamInterface* stream, talk_base::Thread* write_thread)
509 write_thread_(write_thread),
510 state_(stream ? stream->GetState() : SS_CLOSED) {
513 virtual ~AsyncWriteStream();
515 // StreamInterface Interface
516 virtual StreamState GetState() const { return state_; }
517 // This is needed by some stream writers, such as RtpDumpWriter.
518 virtual bool GetPosition(size_t* position) const;
519 virtual StreamResult Read(void* buffer, size_t buffer_len,
520 size_t* read, int* error);
521 virtual StreamResult Write(const void* data, size_t data_len,
522 size_t* written, int* error);
523 virtual void Close();
524 virtual bool Flush();
527 // From MessageHandler
528 virtual void OnMessage(talk_base::Message* pmsg);
529 virtual void ClearBufferAndWrite();
532 talk_base::scoped_ptr<StreamInterface> stream_;
533 Thread* write_thread_;
536 mutable CriticalSection crit_stream_;
537 CriticalSection crit_buffer_;
539 DISALLOW_EVIL_CONSTRUCTORS(AsyncWriteStream);
543 #if defined(POSIX) && !defined(__native_client__)
544 // A FileStream that is actually not a file, but the output or input of a
545 // sub-command. See "man 3 popen" for documentation of the underlying OS popen()
547 class POpenStream : public FileStream {
549 POpenStream() : wait_status_(-1) {}
550 virtual ~POpenStream();
552 virtual bool Open(const std::string& subcommand, const char* mode,
554 // Same as Open(). shflag is ignored.
555 virtual bool OpenShare(const std::string& subcommand, const char* mode,
556 int shflag, int* error);
558 // Returns the wait status from the last Close() of an Open()'ed stream, or
559 // -1 if no Open()+Close() has been done on this object. Meaning of the number
560 // is documented in "man 2 wait".
561 int GetWaitStatus() const { return wait_status_; }
564 virtual void DoClose();
571 ///////////////////////////////////////////////////////////////////////////////
572 // MemoryStream is a simple implementation of a StreamInterface over in-memory
573 // data. Data is read and written at the current seek position. Reads return
574 // end-of-stream when they reach the end of data. Writes actually extend the
576 ///////////////////////////////////////////////////////////////////////////////
578 class MemoryStreamBase : public StreamInterface {
580 virtual StreamState GetState() const;
581 virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read,
583 virtual StreamResult Write(const void* buffer, size_t bytes,
584 size_t* bytes_written, int* error);
585 virtual void Close();
586 virtual bool SetPosition(size_t position);
587 virtual bool GetPosition(size_t* position) const;
588 virtual bool GetSize(size_t* size) const;
589 virtual bool GetAvailable(size_t* size) const;
590 virtual bool ReserveSize(size_t size);
592 char* GetBuffer() { return buffer_; }
593 const char* GetBuffer() const { return buffer_; }
598 virtual StreamResult DoReserve(size_t size, int* error);
600 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
602 size_t buffer_length_;
604 size_t seek_position_;
607 DISALLOW_EVIL_CONSTRUCTORS(MemoryStreamBase);
610 // MemoryStream dynamically resizes to accomodate written data.
612 class MemoryStream : public MemoryStreamBase {
615 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
616 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
617 virtual ~MemoryStream();
619 void SetData(const void* data, size_t length);
622 virtual StreamResult DoReserve(size_t size, int* error);
623 // Memory Streams are aligned for efficiency.
624 static const int kAlignment = 16;
628 // ExternalMemoryStream adapts an external memory buffer, so writes which would
629 // extend past the end of the buffer will return end-of-stream.
631 class ExternalMemoryStream : public MemoryStreamBase {
633 ExternalMemoryStream();
634 ExternalMemoryStream(void* data, size_t length);
635 virtual ~ExternalMemoryStream();
637 void SetData(void* data, size_t length);
640 // FifoBuffer allows for efficient, thread-safe buffering of data between
641 // writer and reader. As the data can wrap around the end of the buffer,
642 // MemoryStreamBase can't help us here.
644 class FifoBuffer : public StreamInterface {
646 // Creates a FIFO buffer with the specified capacity.
647 explicit FifoBuffer(size_t length);
648 // Creates a FIFO buffer with the specified capacity and owner
649 FifoBuffer(size_t length, Thread* owner);
650 virtual ~FifoBuffer();
651 // Gets the amount of data currently readable from the buffer.
652 bool GetBuffered(size_t* data_len) const;
653 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
654 bool SetCapacity(size_t length);
656 // Read into |buffer| with an offset from the current read position, offset
657 // is specified in number of bytes.
658 // This method doesn't adjust read position nor the number of available
659 // bytes, user has to call ConsumeReadData() to do this.
660 StreamResult ReadOffset(void* buffer, size_t bytes, size_t offset,
663 // Write |buffer| with an offset from the current write position, offset is
664 // specified in number of bytes.
665 // This method doesn't adjust the number of buffered bytes, user has to call
666 // ConsumeWriteBuffer() to do this.
667 StreamResult WriteOffset(const void* buffer, size_t bytes, size_t offset,
668 size_t* bytes_written);
670 // StreamInterface methods
671 virtual StreamState GetState() const;
672 virtual StreamResult Read(void* buffer, size_t bytes,
673 size_t* bytes_read, int* error);
674 virtual StreamResult Write(const void* buffer, size_t bytes,
675 size_t* bytes_written, int* error);
676 virtual void Close();
677 virtual const void* GetReadData(size_t* data_len);
678 virtual void ConsumeReadData(size_t used);
679 virtual void* GetWriteBuffer(size_t* buf_len);
680 virtual void ConsumeWriteBuffer(size_t used);
681 virtual bool GetWriteRemaining(size_t* size) const;
684 // Helper method that implements ReadOffset. Caller must acquire a lock
685 // when calling this method.
686 StreamResult ReadOffsetLocked(void* buffer, size_t bytes, size_t offset,
689 // Helper method that implements WriteOffset. Caller must acquire a lock
690 // when calling this method.
691 StreamResult WriteOffsetLocked(const void* buffer, size_t bytes,
692 size_t offset, size_t* bytes_written);
694 StreamState state_; // keeps the opened/closed state of the stream
695 scoped_ptr<char[]> buffer_; // the allocated buffer
696 size_t buffer_length_; // size of the allocated buffer
697 size_t data_length_; // amount of readable data in the buffer
698 size_t read_position_; // offset to the readable data
699 Thread* owner_; // stream callbacks are dispatched on this thread
700 mutable CriticalSection crit_; // object lock
701 DISALLOW_EVIL_CONSTRUCTORS(FifoBuffer);
704 ///////////////////////////////////////////////////////////////////////////////
706 class LoggingAdapter : public StreamAdapterInterface {
708 LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
709 const std::string& label, bool hex_mode = false);
711 void set_label(const std::string& label);
713 virtual StreamResult Read(void* buffer, size_t buffer_len,
714 size_t* read, int* error);
715 virtual StreamResult Write(const void* data, size_t data_len,
716 size_t* written, int* error);
717 virtual void Close();
720 virtual void OnEvent(StreamInterface* stream, int events, int err);
723 LoggingSeverity level_;
726 LogMultilineState lms_;
728 DISALLOW_EVIL_CONSTRUCTORS(LoggingAdapter);
731 ///////////////////////////////////////////////////////////////////////////////
732 // StringStream - Reads/Writes to an external std::string
733 ///////////////////////////////////////////////////////////////////////////////
735 class StringStream : public StreamInterface {
737 explicit StringStream(std::string& str);
738 explicit StringStream(const std::string& str);
740 virtual StreamState GetState() const;
741 virtual StreamResult Read(void* buffer, size_t buffer_len,
742 size_t* read, int* error);
743 virtual StreamResult Write(const void* data, size_t data_len,
744 size_t* written, int* error);
745 virtual void Close();
746 virtual bool SetPosition(size_t position);
747 virtual bool GetPosition(size_t* position) const;
748 virtual bool GetSize(size_t* size) const;
749 virtual bool GetAvailable(size_t* size) const;
750 virtual bool ReserveSize(size_t size);
758 ///////////////////////////////////////////////////////////////////////////////
759 // StreamReference - A reference counting stream adapter
760 ///////////////////////////////////////////////////////////////////////////////
762 // Keep in mind that the streams and adapters defined in this file are
763 // not thread-safe, so this has limited uses.
765 // A StreamRefCount holds the reference count and a pointer to the
766 // wrapped stream. It deletes the wrapped stream when there are no
767 // more references. We can then have multiple StreamReference
768 // instances pointing to one StreamRefCount, all wrapping the same
771 class StreamReference : public StreamAdapterInterface {
772 class StreamRefCount;
774 // Constructor for the first reference to a stream
775 // Note: get more references through NewReference(). Use this
776 // constructor only once on a given stream.
777 explicit StreamReference(StreamInterface* stream);
778 StreamInterface* GetStream() { return stream(); }
779 StreamInterface* NewReference();
780 virtual ~StreamReference();
783 class StreamRefCount {
785 explicit StreamRefCount(StreamInterface* stream)
786 : stream_(stream), ref_count_(1) {
788 void AddReference() {
789 CritScope lock(&cs_);
794 { // Atomic ops would have been a better fit here.
795 CritScope lock(&cs_);
796 ref_count = --ref_count_;
798 if (ref_count == 0) {
804 StreamInterface* stream_;
807 DISALLOW_EVIL_CONSTRUCTORS(StreamRefCount);
810 // Constructor for adding references
811 explicit StreamReference(StreamRefCount* stream_ref_count,
812 StreamInterface* stream);
814 StreamRefCount* stream_ref_count_;
815 DISALLOW_EVIL_CONSTRUCTORS(StreamReference);
818 ///////////////////////////////////////////////////////////////////////////////
820 // Flow attempts to move bytes from source to sink via buffer of size
821 // buffer_len. The function returns SR_SUCCESS when source reaches
822 // end-of-stream (returns SR_EOS), and all the data has been written successful
823 // to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
824 // returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
825 // with the unexpected StreamResult value.
826 // data_len is the length of the valid data in buffer. in case of error
827 // this is the data that read from source but can't move to destination.
828 // as a pass in parameter, it indicates data in buffer that should move to sink
829 StreamResult Flow(StreamInterface* source,
830 char* buffer, size_t buffer_len,
831 StreamInterface* sink, size_t* data_len = NULL);
833 ///////////////////////////////////////////////////////////////////////////////
835 } // namespace talk_base
837 #endif // TALK_BASE_STREAM_H_