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__
31
#include "talk/base/basictypes.h"
32
#include "talk/base/criticalsection.h"
33
#include "talk/base/logging.h"
34
#include "talk/base/messagehandler.h"
35
#include "talk/base/scoped_ptr.h"
36
#include "talk/base/sigslot.h"
40
///////////////////////////////////////////////////////////////////////////////
41
// StreamInterface is a generic asynchronous stream interface, supporting read,
42
// write, and close operations, and asynchronous signalling of state changes.
43
// The interface is designed with file, memory, and socket implementations in
44
// mind. Some implementations offer extended operations, such as seeking.
45
///////////////////////////////////////////////////////////////////////////////
47
// The following enumerations are declared outside of the StreamInterface
48
// class for brevity in use.
50
// The SS_OPENING state indicates that the stream will signal open or closed
52
enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
54
// Stream read/write methods return this value to indicate various success
55
// and failure conditions described below.
56
enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
58
// StreamEvents are used to asynchronously signal state transitionss. The flags
60
// SE_OPEN: The stream has transitioned to the SS_OPEN state
61
// SE_CLOSE: The stream has transitioned to the SS_CLOSED state
62
// SE_READ: Data is available, so Read is likely to not return SR_BLOCK
63
// SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
64
enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
68
class StreamInterface : public MessageHandler {
71
MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
74
virtual ~StreamInterface();
76
virtual StreamState GetState() const = 0;
78
// Read attempts to fill buffer of size buffer_len. Write attempts to send
79
// data_len bytes stored in data. The variables read and write are set only
80
// on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
81
// Read and Write return a value indicating:
82
// SR_ERROR: an error occurred, which is returned in a non-null error
83
// argument. Interpretation of the error requires knowledge of the
84
// stream's concrete type, which limits its usefulness.
85
// SR_SUCCESS: some number of bytes were successfully written, which is
86
// returned in a non-null read/write argument.
87
// SR_BLOCK: the stream is in non-blocking mode, and the operation would
88
// block, or the stream is in SS_OPENING state.
89
// SR_EOS: the end-of-stream has been reached, or the stream is in the
91
virtual StreamResult Read(void* buffer, size_t buffer_len,
92
size_t* read, int* error) = 0;
93
virtual StreamResult Write(const void* data, size_t data_len,
94
size_t* written, int* error) = 0;
95
// Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
96
// signalled as a result of this call.
97
virtual void Close() = 0;
99
// Streams may signal one or more StreamEvents to indicate state changes.
100
// The first argument identifies the stream on which the state change occured.
101
// The second argument is a bit-wise combination of StreamEvents.
102
// If SE_CLOSE is signalled, then the third argument is the associated error
103
// code. Otherwise, the value is undefined.
104
// Note: Not all streams will support asynchronous event signalling. However,
105
// SS_OPENING and SR_BLOCK returned from stream member functions imply that
106
// certain events will be raised in the future.
107
sigslot::signal3<StreamInterface*, int, int> SignalEvent;
109
// Like calling SignalEvent, but posts a message to the specified thread,
110
// which will call SignalEvent. This helps unroll the stack and prevent
112
void PostEvent(Thread* t, int events, int err);
113
// Like the aforementioned method, but posts to the current thread.
114
void PostEvent(int events, int err);
117
// OPTIONAL OPERATIONS
119
// Not all implementations will support the following operations. In general,
120
// a stream will only support an operation if it reasonably efficient to do
121
// so. For example, while a socket could buffer incoming data to support
122
// seeking, it will not do so. Instead, a buffering stream adapter should
125
// Even though several of these operations are related, you should
126
// always use whichever operation is most relevant. For example, you may
127
// be tempted to use GetSize() and GetPosition() to deduce the result of
128
// GetAvailable(). However, a stream which is read-once may support the
129
// latter operation but not the former.
132
// The following four methods are used to avoid copying data multiple times.
134
// GetReadData returns a pointer to a buffer which is owned by the stream.
135
// The buffer contains data_len bytes. NULL is returned if no data is
136
// available, or if the method fails. If the caller processes the data, it
137
// must call ConsumeReadData with the number of processed bytes. GetReadData
138
// does not require a matching call to ConsumeReadData if the data is not
139
// processed. Read and ConsumeReadData invalidate the buffer returned by
141
virtual const void* GetReadData(size_t* data_len) { return NULL; }
142
virtual void ConsumeReadData(size_t used) {}
144
// GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
145
// The buffer has a capacity of buf_len bytes. NULL is returned if there is
146
// no buffer available, or if the method fails. The call may write data to
147
// the buffer, and then call ConsumeWriteBuffer with the number of bytes
148
// written. GetWriteBuffer does not require a matching call to
149
// ConsumeWriteData if no data is written. Write, ForceWrite, and
150
// ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
151
// TODO: Allow the caller to specify a minimum buffer size. If the specified
152
// amount of buffer is not yet available, return NULL and Signal SE_WRITE
153
// when it is available. If the requested amount is too large, return an
155
virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; }
156
virtual void ConsumeWriteBuffer(size_t used) {}
158
// Write data_len bytes found in data, circumventing any throttling which
159
// would could cause SR_BLOCK to be returned. Returns true if all the data
160
// was written. Otherwise, the method is unsupported, or an unrecoverable
161
// error occurred, and the error value is set. This method should be used
162
// sparingly to write critical data which should not be throttled. A stream
163
// which cannot circumvent its blocking constraints should not implement this
165
// NOTE: This interface is being considered experimentally at the moment. It
166
// would be used by JUDP and BandwidthStream as a way to circumvent certain
167
// soft limits in writing.
168
//virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
169
// if (error) *error = -1;
173
// Seek to a byte offset from the beginning of the stream. Returns false if
174
// the stream does not support seeking, or cannot seek to the specified
176
virtual bool SetPosition(size_t position) { return false; }
178
// Get the byte offset of the current position from the start of the stream.
179
// Returns false if the position is not known.
180
virtual bool GetPosition(size_t* position) const { return false; }
182
// Get the byte length of the entire stream. Returns false if the length
184
virtual bool GetSize(size_t* size) const { return false; }
186
// Return the number of Read()-able bytes remaining before end-of-stream.
187
// Returns false if not known.
188
virtual bool GetAvailable(size_t* size) const { return false; }
190
// Return the number of Write()-able bytes remaining before end-of-stream.
191
// Returns false if not known.
192
virtual bool GetWriteRemaining(size_t* size) const { return false; }
194
// Communicates the amount of data which will be written to the stream. The
195
// stream may choose to preallocate memory to accomodate this data. The
196
// stream may return false to indicate that there is not enough room (ie,
197
// Write will return SR_EOS/SR_ERROR at some point). Note that calling this
198
// function should not affect the existing state of data in the stream.
199
virtual bool ReserveSize(size_t size) { return true; }
202
// CONVENIENCE METHODS
204
// These methods are implemented in terms of other methods, for convenience.
207
// Seek to the start of the stream.
208
inline bool Rewind() { return SetPosition(0); }
210
// WriteAll is a helper function which repeatedly calls Write until all the
211
// data is written, or something other than SR_SUCCESS is returned. Note that
212
// unlike Write, the argument 'written' is always set, and may be non-zero
213
// on results other than SR_SUCCESS. The remaining arguments have the
214
// same semantics as Write.
215
StreamResult WriteAll(const void* data, size_t data_len,
216
size_t* written, int* error);
218
// Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
219
// until a non-SR_SUCCESS result is returned. 'read' is always set.
220
StreamResult ReadAll(void* buffer, size_t buffer_len,
221
size_t* read, int* error);
223
// ReadLine is a helper function which repeatedly calls Read until it hits
224
// the end-of-line character, or something other than SR_SUCCESS.
225
// TODO: this is too inefficient to keep here. Break this out into a buffered
226
// readline object or adapter
227
StreamResult ReadLine(std::string *line);
232
// MessageHandler Interface
233
virtual void OnMessage(Message* msg);
236
DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
239
///////////////////////////////////////////////////////////////////////////////
240
// StreamAdapterInterface is a convenient base-class for adapting a stream.
241
// By default, all operations are pass-through. Override the methods that you
242
// require adaptation. Streams should really be upgraded to reference-counted.
243
// In the meantime, use the owned flag to indicate whether the adapter should
244
// own the adapted stream.
245
///////////////////////////////////////////////////////////////////////////////
247
class StreamAdapterInterface : public StreamInterface,
248
public sigslot::has_slots<> {
250
explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
252
// Core Stream Interface
253
virtual StreamState GetState() const {
254
return stream_->GetState();
256
virtual StreamResult Read(void* buffer, size_t buffer_len,
257
size_t* read, int* error) {
258
return stream_->Read(buffer, buffer_len, read, error);
260
virtual StreamResult Write(const void* data, size_t data_len,
261
size_t* written, int* error) {
262
return stream_->Write(data, data_len, written, error);
264
virtual void Close() {
268
// Optional Stream Interface
269
/* Note: Many stream adapters were implemented prior to this Read/Write
270
interface. Therefore, a simple pass through of data in those cases may
271
be broken. At a later time, we should do a once-over pass of all
272
adapters, and make them compliant with these interfaces, after which this
273
code can be uncommented.
274
virtual const void* GetReadData(size_t* data_len) {
275
return stream_->GetReadData(data_len);
277
virtual void ConsumeReadData(size_t used) {
278
stream_->ConsumeReadData(used);
281
virtual void* GetWriteBuffer(size_t* buf_len) {
282
return stream_->GetWriteBuffer(buf_len);
284
virtual void ConsumeWriteBuffer(size_t used) {
285
stream_->ConsumeWriteBuffer(used);
289
/* Note: This interface is currently undergoing evaluation.
290
virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
291
return stream_->ForceWrite(data, data_len, error);
295
virtual bool SetPosition(size_t position) {
296
return stream_->SetPosition(position);
298
virtual bool GetPosition(size_t* position) const {
299
return stream_->GetPosition(position);
301
virtual bool GetSize(size_t* size) const {
302
return stream_->GetSize(size);
304
virtual bool GetAvailable(size_t* size) const {
305
return stream_->GetAvailable(size);
307
virtual bool GetWriteRemaining(size_t* size) const {
308
return stream_->GetWriteRemaining(size);
310
virtual bool ReserveSize(size_t size) {
311
return stream_->ReserveSize(size);
314
void Attach(StreamInterface* stream, bool owned = true);
315
StreamInterface* Detach();
318
virtual ~StreamAdapterInterface();
320
// Note that the adapter presents itself as the origin of the stream events,
321
// since users of the adapter may not recognize the adapted object.
322
virtual void OnEvent(StreamInterface* stream, int events, int err) {
323
SignalEvent(this, events, err);
325
StreamInterface* stream() { return stream_; }
328
StreamInterface* stream_;
330
DISALLOW_EVIL_CONSTRUCTORS(StreamAdapterInterface);
333
///////////////////////////////////////////////////////////////////////////////
334
// StreamTap is a non-modifying, pass-through adapter, which copies all data
335
// in either direction to the tap. Note that errors or blocking on writing to
336
// the tap will prevent further tap writes from occurring.
337
///////////////////////////////////////////////////////////////////////////////
339
class StreamTap : public StreamAdapterInterface {
341
explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
343
void AttachTap(StreamInterface* tap);
344
StreamInterface* DetachTap();
345
StreamResult GetTapResult(int* error);
347
// StreamAdapterInterface Interface
348
virtual StreamResult Read(void* buffer, size_t buffer_len,
349
size_t* read, int* error);
350
virtual StreamResult Write(const void* data, size_t data_len,
351
size_t* written, int* error);
354
scoped_ptr<StreamInterface> tap_;
355
StreamResult tap_result_;
357
DISALLOW_EVIL_CONSTRUCTORS(StreamTap);
360
///////////////////////////////////////////////////////////////////////////////
361
// StreamSegment adapts a read stream, to expose a subset of the adapted
362
// stream's data. This is useful for cases where a stream contains multiple
363
// documents concatenated together. StreamSegment can expose a subset of
364
// the data as an independent stream, including support for rewinding and
366
///////////////////////////////////////////////////////////////////////////////
368
class StreamSegment : public StreamAdapterInterface {
370
// The current position of the adapted stream becomes the beginning of the
371
// segment. If a length is specified, it bounds the length of the segment.
372
explicit StreamSegment(StreamInterface* stream);
373
explicit StreamSegment(StreamInterface* stream, size_t length);
375
// StreamAdapterInterface Interface
376
virtual StreamResult Read(void* buffer, size_t buffer_len,
377
size_t* read, int* error);
378
virtual bool SetPosition(size_t position);
379
virtual bool GetPosition(size_t* position) const;
380
virtual bool GetSize(size_t* size) const;
381
virtual bool GetAvailable(size_t* size) const;
384
size_t start_, pos_, length_;
385
DISALLOW_EVIL_CONSTRUCTORS(StreamSegment);
388
///////////////////////////////////////////////////////////////////////////////
389
// NullStream gives errors on read, and silently discards all written data.
390
///////////////////////////////////////////////////////////////////////////////
392
class NullStream : public StreamInterface {
395
virtual ~NullStream();
397
// StreamInterface Interface
398
virtual StreamState GetState() const;
399
virtual StreamResult Read(void* buffer, size_t buffer_len,
400
size_t* read, int* error);
401
virtual StreamResult Write(const void* data, size_t data_len,
402
size_t* written, int* error);
403
virtual void Close();
406
///////////////////////////////////////////////////////////////////////////////
407
// FileStream is a simple implementation of a StreamInterface, which does not
408
// support asynchronous notification.
409
///////////////////////////////////////////////////////////////////////////////
411
class FileStream : public StreamInterface {
414
virtual ~FileStream();
416
// The semantics of filename and mode are the same as stdio's fopen
417
virtual bool Open(const std::string& filename, const char* mode, int* error);
418
virtual bool OpenShare(const std::string& filename, const char* mode,
419
int shflag, int* error);
421
// By default, reads and writes are buffered for efficiency. Disabling
422
// buffering causes writes to block until the bytes on disk are updated.
423
virtual bool DisableBuffering();
425
virtual StreamState GetState() const;
426
virtual StreamResult Read(void* buffer, size_t buffer_len,
427
size_t* read, int* error);
428
virtual StreamResult Write(const void* data, size_t data_len,
429
size_t* written, int* error);
430
virtual void Close();
431
virtual bool SetPosition(size_t position);
432
virtual bool GetPosition(size_t* position) const;
433
virtual bool GetSize(size_t* size) const;
434
virtual bool GetAvailable(size_t* size) const;
435
virtual bool ReserveSize(size_t size);
440
// Tries to aquire an exclusive lock on the file.
441
// Use OpenShare(...) on win32 to get similar functionality.
446
// Note: Deprecated in favor of Filesystem::GetFileSize().
447
static bool GetSize(const std::string& filename, size_t* size);
450
virtual void DoClose();
455
DISALLOW_EVIL_CONSTRUCTORS(FileStream);
459
// A FileStream that is actually not a file, but the output or input of a
460
// sub-command. See "man 3 popen" for documentation of the underlying OS popen()
462
class POpenStream : public FileStream {
464
POpenStream() : wait_status_(-1) {}
465
virtual ~POpenStream();
467
virtual bool Open(const std::string& subcommand, const char* mode,
469
// Same as Open(). shflag is ignored.
470
virtual bool OpenShare(const std::string& subcommand, const char* mode,
471
int shflag, int* error);
473
// Returns the wait status from the last Close() of an Open()'ed stream, or
474
// -1 if no Open()+Close() has been done on this object. Meaning of the number
475
// is documented in "man 2 wait".
476
int GetWaitStatus() const { return wait_status_; }
479
virtual void DoClose();
486
///////////////////////////////////////////////////////////////////////////////
487
// MemoryStream is a simple implementation of a StreamInterface over in-memory
488
// data. Data is read and written at the current seek position. Reads return
489
// end-of-stream when they reach the end of data. Writes actually extend the
491
///////////////////////////////////////////////////////////////////////////////
493
class MemoryStreamBase : public StreamInterface {
495
virtual StreamState GetState() const;
496
virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read,
498
virtual StreamResult Write(const void* buffer, size_t bytes,
499
size_t* bytes_written, int* error);
500
virtual void Close();
501
virtual bool SetPosition(size_t position);
502
virtual bool GetPosition(size_t* position) const;
503
virtual bool GetSize(size_t* size) const;
504
virtual bool GetAvailable(size_t* size) const;
505
virtual bool ReserveSize(size_t size);
507
char* GetBuffer() { return buffer_; }
508
const char* GetBuffer() const { return buffer_; }
513
virtual StreamResult DoReserve(size_t size, int* error);
515
// Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
517
size_t buffer_length_;
519
size_t seek_position_;
522
DISALLOW_EVIL_CONSTRUCTORS(MemoryStreamBase);
525
// MemoryStream dynamically resizes to accomodate written data.
527
class MemoryStream : public MemoryStreamBase {
530
explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
531
MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
532
virtual ~MemoryStream();
534
void SetData(const void* data, size_t length);
537
virtual StreamResult DoReserve(size_t size, int* error);
538
// Memory Streams are aligned for efficiency.
539
static const int kAlignment = 16;
543
// ExternalMemoryStream adapts an external memory buffer, so writes which would
544
// extend past the end of the buffer will return end-of-stream.
546
class ExternalMemoryStream : public MemoryStreamBase {
548
ExternalMemoryStream();
549
ExternalMemoryStream(void* data, size_t length);
550
virtual ~ExternalMemoryStream();
552
void SetData(void* data, size_t length);
555
// FifoBuffer allows for efficient, thread-safe buffering of data between
556
// writer and reader. As the data can wrap around the end of the buffer,
557
// MemoryStreamBase can't help us here.
559
class FifoBuffer : public StreamInterface {
561
// Creates a FIFO buffer with the specified capacity.
562
explicit FifoBuffer(size_t length);
563
// Creates a FIFO buffer with the specified capacity and owner
564
FifoBuffer(size_t length, Thread* owner);
565
virtual ~FifoBuffer();
566
// Gets the amount of data currently readable from the buffer.
567
bool GetBuffered(size_t* data_len) const;
568
// Resizes the buffer to the specified capacity. Fails if data_length_ > size
569
bool SetCapacity(size_t length);
571
// Read into |buffer| with an offset from the current read position, offset
572
// is specified in number of bytes.
573
// This method doesn't adjust read position nor the number of available
574
// bytes, user has to call ConsumeReadData() to do this.
575
StreamResult ReadOffset(void* buffer, size_t bytes, size_t offset,
578
// Write |buffer| with an offset from the current write position, offset is
579
// specified in number of bytes.
580
// This method doesn't adjust the number of buffered bytes, user has to call
581
// ConsumeWriteBuffer() to do this.
582
StreamResult WriteOffset(const void* buffer, size_t bytes, size_t offset,
583
size_t* bytes_written);
585
// StreamInterface methods
586
virtual StreamState GetState() const;
587
virtual StreamResult Read(void* buffer, size_t bytes,
588
size_t* bytes_read, int* error);
589
virtual StreamResult Write(const void* buffer, size_t bytes,
590
size_t* bytes_written, int* error);
591
virtual void Close();
592
virtual const void* GetReadData(size_t* data_len);
593
virtual void ConsumeReadData(size_t used);
594
virtual void* GetWriteBuffer(size_t *buf_len);
595
virtual void ConsumeWriteBuffer(size_t used);
596
virtual bool GetWriteRemaining(size_t* size) const;
599
// Helper method that implements ReadOffset. Caller must acquire a lock
600
// when calling this method.
601
StreamResult ReadOffsetLocked(void* buffer, size_t bytes, size_t offset,
604
// Helper method that implements WriteOffset. Caller must acquire a lock
605
// when calling this method.
606
StreamResult WriteOffsetLocked(const void* buffer, size_t bytes,
607
size_t offset, size_t* bytes_written);
609
StreamState state_; // keeps the opened/closed state of the stream
610
scoped_array<char> buffer_; // the allocated buffer
611
size_t buffer_length_; // size of the allocated buffer
612
size_t data_length_; // amount of readable data in the buffer
613
size_t read_position_; // offset to the readable data
614
Thread* owner_; // stream callbacks are dispatched on this thread
615
mutable CriticalSection crit_; // object lock
616
DISALLOW_EVIL_CONSTRUCTORS(FifoBuffer);
619
///////////////////////////////////////////////////////////////////////////////
621
class LoggingAdapter : public StreamAdapterInterface {
623
LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
624
const std::string& label, bool hex_mode = false);
626
void set_label(const std::string& label);
628
virtual StreamResult Read(void* buffer, size_t buffer_len,
629
size_t* read, int* error);
630
virtual StreamResult Write(const void* data, size_t data_len,
631
size_t* written, int* error);
632
virtual void Close();
635
virtual void OnEvent(StreamInterface* stream, int events, int err);
638
LoggingSeverity level_;
641
LogMultilineState lms_;
643
DISALLOW_EVIL_CONSTRUCTORS(LoggingAdapter);
646
///////////////////////////////////////////////////////////////////////////////
647
// StringStream - Reads/Writes to an external std::string
648
///////////////////////////////////////////////////////////////////////////////
650
class StringStream : public StreamInterface {
652
explicit StringStream(std::string& str);
653
explicit StringStream(const std::string& str);
655
virtual StreamState GetState() const;
656
virtual StreamResult Read(void* buffer, size_t buffer_len,
657
size_t* read, int* error);
658
virtual StreamResult Write(const void* data, size_t data_len,
659
size_t* written, int* error);
660
virtual void Close();
661
virtual bool SetPosition(size_t position);
662
virtual bool GetPosition(size_t* position) const;
663
virtual bool GetSize(size_t* size) const;
664
virtual bool GetAvailable(size_t* size) const;
665
virtual bool ReserveSize(size_t size);
673
///////////////////////////////////////////////////////////////////////////////
674
// StreamReference - A reference counting stream adapter
675
///////////////////////////////////////////////////////////////////////////////
677
// Keep in mind that the streams and adapters defined in this file are
678
// not thread-safe, so this has limited uses.
680
// A StreamRefCount holds the reference count and a pointer to the
681
// wrapped stream. It deletes the wrapped stream when there are no
682
// more references. We can then have multiple StreamReference
683
// instances pointing to one StreamRefCount, all wrapping the same
686
class StreamReference : public StreamAdapterInterface {
687
class StreamRefCount;
689
// Constructor for the first reference to a stream
690
// Note: get more references through NewReference(). Use this
691
// constructor only once on a given stream.
692
explicit StreamReference(StreamInterface* stream);
693
StreamInterface* GetStream() { return stream(); }
694
StreamInterface* NewReference();
695
virtual ~StreamReference();
698
class StreamRefCount {
700
explicit StreamRefCount(StreamInterface* stream)
701
: stream_(stream), ref_count_(1) {
703
void AddReference() {
704
CritScope lock(&cs_);
709
{ // Atomic ops would have been a better fit here.
710
CritScope lock(&cs_);
711
ref_count = --ref_count_;
713
if (ref_count == 0) {
719
StreamInterface* stream_;
722
DISALLOW_EVIL_CONSTRUCTORS(StreamRefCount);
725
// Constructor for adding references
726
explicit StreamReference(StreamRefCount* stream_ref_count,
727
StreamInterface* stream);
729
StreamRefCount* stream_ref_count_;
730
DISALLOW_EVIL_CONSTRUCTORS(StreamReference);
733
///////////////////////////////////////////////////////////////////////////////
735
// Flow attempts to move bytes from source to sink via buffer of size
736
// buffer_len. The function returns SR_SUCCESS when source reaches
737
// end-of-stream (returns SR_EOS), and all the data has been written successful
738
// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
739
// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
740
// with the unexpected StreamResult value.
741
// data_len is the length of the valid data in buffer. in case of error
742
// this is the data that read from source but can't move to destination.
743
// as a pass in parameter, it indicates data in buffer that should move to sink
744
StreamResult Flow(StreamInterface* source,
745
char* buffer, size_t buffer_len,
746
StreamInterface* sink, size_t* data_len = NULL);
748
///////////////////////////////////////////////////////////////////////////////
750
} // namespace talk_base
752
#endif // TALK_BASE_STREAM_H__