~ubuntu-branches/ubuntu/saucy/kopete/saucy-proposed

« back to all changes in this revision

Viewing changes to protocols/jabber/googletalk/libjingle/talk/base/stream.h

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell
  • Date: 2013-06-21 02:22:39 UTC
  • Revision ID: package-import@ubuntu.com-20130621022239-63l3zc8p0nf26pt6
Tags: upstream-4.10.80
ImportĀ upstreamĀ versionĀ 4.10.80

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * libjingle
 
3
 * Copyright 2004--2010, Google Inc.
 
4
 *
 
5
 * Redistribution and use in source and binary forms, with or without
 
6
 * modification, are permitted provided that the following conditions are met:
 
7
 *
 
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.
 
15
 *
 
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.
 
26
 */
 
27
 
 
28
#ifndef TALK_BASE_STREAM_H__
 
29
#define TALK_BASE_STREAM_H__
 
30
 
 
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"
 
37
 
 
38
namespace talk_base {
 
39
 
 
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
///////////////////////////////////////////////////////////////////////////////
 
46
 
 
47
// The following enumerations are declared outside of the StreamInterface
 
48
// class for brevity in use.
 
49
 
 
50
// The SS_OPENING state indicates that the stream will signal open or closed
 
51
// in the future.
 
52
enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
 
53
 
 
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 };
 
57
 
 
58
// StreamEvents are used to asynchronously signal state transitionss.  The flags
 
59
// may be combined.
 
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 };
 
65
 
 
66
class Thread;
 
67
 
 
68
class StreamInterface : public MessageHandler {
 
69
 public:
 
70
  enum {
 
71
    MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
 
72
  };
 
73
 
 
74
  virtual ~StreamInterface();
 
75
 
 
76
  virtual StreamState GetState() const = 0;
 
77
 
 
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
 
90
  //    SS_CLOSED state.
 
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;
 
98
 
 
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;
 
108
 
 
109
  // Like calling SignalEvent, but posts a message to the specified thread,
 
110
  // which will call SignalEvent.  This helps unroll the stack and prevent
 
111
  // re-entrancy.
 
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);
 
115
 
 
116
  //
 
117
  // OPTIONAL OPERATIONS
 
118
  //
 
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
 
123
  // be used.
 
124
  //
 
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.
 
130
  //
 
131
 
 
132
  // The following four methods are used to avoid copying data multiple times.
 
133
 
 
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
 
140
  // GetReadData.
 
141
  virtual const void* GetReadData(size_t* data_len) { return NULL; }
 
142
  virtual void ConsumeReadData(size_t used) {}
 
143
 
 
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
 
154
  // error.
 
155
  virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; }
 
156
  virtual void ConsumeWriteBuffer(size_t used) {}
 
157
 
 
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
 
164
  // method.
 
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;
 
170
  //  return false;
 
171
  //}
 
172
 
 
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
 
175
  // position.
 
176
  virtual bool SetPosition(size_t position) { return false; }
 
177
 
 
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; }
 
181
 
 
182
  // Get the byte length of the entire stream.  Returns false if the length
 
183
  // is not known.
 
184
  virtual bool GetSize(size_t* size) const { return false; }
 
185
 
 
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; }
 
189
 
 
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; }
 
193
 
 
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; }
 
200
 
 
201
  //
 
202
  // CONVENIENCE METHODS
 
203
  //
 
204
  // These methods are implemented in terms of other methods, for convenience.
 
205
  //
 
206
 
 
207
  // Seek to the start of the stream.
 
208
  inline bool Rewind() { return SetPosition(0); }
 
209
 
 
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);
 
217
 
 
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);
 
222
 
 
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);
 
228
 
 
229
 protected:
 
230
  StreamInterface();
 
231
 
 
232
  // MessageHandler Interface
 
233
  virtual void OnMessage(Message* msg);
 
234
 
 
235
 private:
 
236
  DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
 
237
};
 
238
 
 
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
///////////////////////////////////////////////////////////////////////////////
 
246
 
 
247
class StreamAdapterInterface : public StreamInterface,
 
248
                               public sigslot::has_slots<> {
 
249
 public:
 
250
  explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
 
251
 
 
252
  // Core Stream Interface
 
253
  virtual StreamState GetState() const {
 
254
    return stream_->GetState();
 
255
  }
 
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);
 
259
  }
 
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);
 
263
  }
 
264
  virtual void Close() {
 
265
    stream_->Close();
 
266
  }
 
267
 
 
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);
 
276
  }
 
277
  virtual void ConsumeReadData(size_t used) {
 
278
    stream_->ConsumeReadData(used);
 
279
  }
 
280
 
 
281
  virtual void* GetWriteBuffer(size_t* buf_len) {
 
282
    return stream_->GetWriteBuffer(buf_len);
 
283
  }
 
284
  virtual void ConsumeWriteBuffer(size_t used) {
 
285
    stream_->ConsumeWriteBuffer(used);
 
286
  }
 
287
  */
 
288
 
 
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);
 
292
  }
 
293
  */
 
294
 
 
295
  virtual bool SetPosition(size_t position) {
 
296
    return stream_->SetPosition(position);
 
297
  }
 
298
  virtual bool GetPosition(size_t* position) const {
 
299
    return stream_->GetPosition(position);
 
300
  }
 
301
  virtual bool GetSize(size_t* size) const {
 
302
    return stream_->GetSize(size);
 
303
  }
 
304
  virtual bool GetAvailable(size_t* size) const {
 
305
    return stream_->GetAvailable(size);
 
306
  }
 
307
  virtual bool GetWriteRemaining(size_t* size) const {
 
308
    return stream_->GetWriteRemaining(size);
 
309
  }
 
310
  virtual bool ReserveSize(size_t size) {
 
311
    return stream_->ReserveSize(size);
 
312
  }
 
313
 
 
314
  void Attach(StreamInterface* stream, bool owned = true);
 
315
  StreamInterface* Detach();
 
316
 
 
317
 protected:
 
318
  virtual ~StreamAdapterInterface();
 
319
 
 
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);
 
324
  }
 
325
  StreamInterface* stream() { return stream_; }
 
326
 
 
327
 private:
 
328
  StreamInterface* stream_;
 
329
  bool owned_;
 
330
  DISALLOW_EVIL_CONSTRUCTORS(StreamAdapterInterface);
 
331
};
 
332
 
 
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
///////////////////////////////////////////////////////////////////////////////
 
338
 
 
339
class StreamTap : public StreamAdapterInterface {
 
340
 public:
 
341
  explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
 
342
 
 
343
  void AttachTap(StreamInterface* tap);
 
344
  StreamInterface* DetachTap();
 
345
  StreamResult GetTapResult(int* error);
 
346
 
 
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);
 
352
 
 
353
 private:
 
354
  scoped_ptr<StreamInterface> tap_;
 
355
  StreamResult tap_result_;
 
356
  int tap_error_;
 
357
  DISALLOW_EVIL_CONSTRUCTORS(StreamTap);
 
358
};
 
359
 
 
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
 
365
// seeking.
 
366
///////////////////////////////////////////////////////////////////////////////
 
367
 
 
368
class StreamSegment : public StreamAdapterInterface {
 
369
 public:
 
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);
 
374
 
 
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;
 
382
 
 
383
 private:
 
384
  size_t start_, pos_, length_;
 
385
  DISALLOW_EVIL_CONSTRUCTORS(StreamSegment);
 
386
};
 
387
 
 
388
///////////////////////////////////////////////////////////////////////////////
 
389
// NullStream gives errors on read, and silently discards all written data.
 
390
///////////////////////////////////////////////////////////////////////////////
 
391
 
 
392
class NullStream : public StreamInterface {
 
393
 public:
 
394
  NullStream();
 
395
  virtual ~NullStream();
 
396
 
 
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();
 
404
};
 
405
 
 
406
///////////////////////////////////////////////////////////////////////////////
 
407
// FileStream is a simple implementation of a StreamInterface, which does not
 
408
// support asynchronous notification.
 
409
///////////////////////////////////////////////////////////////////////////////
 
410
 
 
411
class FileStream : public StreamInterface {
 
412
 public:
 
413
  FileStream();
 
414
  virtual ~FileStream();
 
415
 
 
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);
 
420
 
 
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();
 
424
 
 
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);
 
436
 
 
437
  bool Flush();
 
438
 
 
439
#if defined(POSIX)
 
440
  // Tries to aquire an exclusive lock on the file.
 
441
  // Use OpenShare(...) on win32 to get similar functionality.
 
442
  bool TryLock();
 
443
  bool Unlock();
 
444
#endif
 
445
 
 
446
  // Note: Deprecated in favor of Filesystem::GetFileSize().
 
447
  static bool GetSize(const std::string& filename, size_t* size);
 
448
 
 
449
 protected:
 
450
  virtual void DoClose();
 
451
 
 
452
  FILE* file_;
 
453
 
 
454
 private:
 
455
  DISALLOW_EVIL_CONSTRUCTORS(FileStream);
 
456
};
 
457
 
 
458
#ifdef POSIX
 
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()
 
461
// function.
 
462
class POpenStream : public FileStream {
 
463
 public:
 
464
  POpenStream() : wait_status_(-1) {}
 
465
  virtual ~POpenStream();
 
466
 
 
467
  virtual bool Open(const std::string& subcommand, const char* mode,
 
468
                    int* error);
 
469
  // Same as Open(). shflag is ignored.
 
470
  virtual bool OpenShare(const std::string& subcommand, const char* mode,
 
471
                         int shflag, int* error);
 
472
 
 
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_; }
 
477
 
 
478
 protected:
 
479
  virtual void DoClose();
 
480
 
 
481
 private:
 
482
  int wait_status_;
 
483
};
 
484
#endif  // POSIX
 
485
 
 
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
 
490
// end of data mark.
 
491
///////////////////////////////////////////////////////////////////////////////
 
492
 
 
493
class MemoryStreamBase : public StreamInterface {
 
494
 public:
 
495
  virtual StreamState GetState() const;
 
496
  virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read,
 
497
                            int* error);
 
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);
 
506
 
 
507
  char* GetBuffer() { return buffer_; }
 
508
  const char* GetBuffer() const { return buffer_; }
 
509
 
 
510
 protected:
 
511
  MemoryStreamBase();
 
512
 
 
513
  virtual StreamResult DoReserve(size_t size, int* error);
 
514
 
 
515
  // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
 
516
  char* buffer_;
 
517
  size_t buffer_length_;
 
518
  size_t data_length_;
 
519
  size_t seek_position_;
 
520
 
 
521
 private:
 
522
  DISALLOW_EVIL_CONSTRUCTORS(MemoryStreamBase);
 
523
};
 
524
 
 
525
// MemoryStream dynamically resizes to accomodate written data.
 
526
 
 
527
class MemoryStream : public MemoryStreamBase {
 
528
 public:
 
529
  MemoryStream();
 
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();
 
533
 
 
534
  void SetData(const void* data, size_t length);
 
535
 
 
536
 protected:
 
537
  virtual StreamResult DoReserve(size_t size, int* error);
 
538
  // Memory Streams are aligned for efficiency.
 
539
  static const int kAlignment = 16;
 
540
  char* buffer_alloc_;
 
541
};
 
542
 
 
543
// ExternalMemoryStream adapts an external memory buffer, so writes which would
 
544
// extend past the end of the buffer will return end-of-stream.
 
545
 
 
546
class ExternalMemoryStream : public MemoryStreamBase {
 
547
 public:
 
548
  ExternalMemoryStream();
 
549
  ExternalMemoryStream(void* data, size_t length);
 
550
  virtual ~ExternalMemoryStream();
 
551
 
 
552
  void SetData(void* data, size_t length);
 
553
};
 
554
 
 
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.
 
558
 
 
559
class FifoBuffer : public StreamInterface {
 
560
 public:
 
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);
 
570
 
 
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,
 
576
                          size_t* bytes_read);
 
577
 
 
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);
 
584
 
 
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;
 
597
 
 
598
 private:
 
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,
 
602
                                size_t* bytes_read);
 
603
 
 
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);
 
608
 
 
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);
 
617
};
 
618
 
 
619
///////////////////////////////////////////////////////////////////////////////
 
620
 
 
621
class LoggingAdapter : public StreamAdapterInterface {
 
622
 public:
 
623
  LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
 
624
                 const std::string& label, bool hex_mode = false);
 
625
 
 
626
  void set_label(const std::string& label);
 
627
 
 
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();
 
633
 
 
634
 protected:
 
635
  virtual void OnEvent(StreamInterface* stream, int events, int err);
 
636
 
 
637
 private:
 
638
  LoggingSeverity level_;
 
639
  std::string label_;
 
640
  bool hex_mode_;
 
641
  LogMultilineState lms_;
 
642
 
 
643
  DISALLOW_EVIL_CONSTRUCTORS(LoggingAdapter);
 
644
};
 
645
 
 
646
///////////////////////////////////////////////////////////////////////////////
 
647
// StringStream - Reads/Writes to an external std::string
 
648
///////////////////////////////////////////////////////////////////////////////
 
649
 
 
650
class StringStream : public StreamInterface {
 
651
 public:
 
652
  explicit StringStream(std::string& str);
 
653
  explicit StringStream(const std::string& str);
 
654
 
 
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);
 
666
 
 
667
 private:
 
668
  std::string& str_;
 
669
  size_t read_pos_;
 
670
  bool read_only_;
 
671
};
 
672
 
 
673
///////////////////////////////////////////////////////////////////////////////
 
674
// StreamReference - A reference counting stream adapter
 
675
///////////////////////////////////////////////////////////////////////////////
 
676
 
 
677
// Keep in mind that the streams and adapters defined in this file are
 
678
// not thread-safe, so this has limited uses.
 
679
 
 
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
 
684
// stream.
 
685
 
 
686
class StreamReference : public StreamAdapterInterface {
 
687
  class StreamRefCount;
 
688
 public:
 
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();
 
696
 
 
697
 private:
 
698
  class StreamRefCount {
 
699
   public:
 
700
    explicit StreamRefCount(StreamInterface* stream)
 
701
        : stream_(stream), ref_count_(1) {
 
702
    }
 
703
    void AddReference() {
 
704
      CritScope lock(&cs_);
 
705
      ++ref_count_;
 
706
    }
 
707
    void Release() {
 
708
      int ref_count;
 
709
      {  // Atomic ops would have been a better fit here.
 
710
        CritScope lock(&cs_);
 
711
        ref_count = --ref_count_;
 
712
      }
 
713
      if (ref_count == 0) {
 
714
        delete stream_;
 
715
        delete this;
 
716
      }
 
717
    }
 
718
   private:
 
719
    StreamInterface* stream_;
 
720
    int ref_count_;
 
721
    CriticalSection cs_;
 
722
    DISALLOW_EVIL_CONSTRUCTORS(StreamRefCount);
 
723
  };
 
724
 
 
725
  // Constructor for adding references
 
726
  explicit StreamReference(StreamRefCount* stream_ref_count,
 
727
                           StreamInterface* stream);
 
728
 
 
729
  StreamRefCount* stream_ref_count_;
 
730
  DISALLOW_EVIL_CONSTRUCTORS(StreamReference);
 
731
};
 
732
 
 
733
///////////////////////////////////////////////////////////////////////////////
 
734
 
 
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);
 
747
 
 
748
///////////////////////////////////////////////////////////////////////////////
 
749
 
 
750
}  // namespace talk_base
 
751
 
 
752
#endif  // TALK_BASE_STREAM_H__