SkStream.h revision 6cab1a4b6a68aa81237731308ff37a646d48f51c
1/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkStream_DEFINED
9#define SkStream_DEFINED
10
11#include "SkRefCnt.h"
12#include "SkScalar.h"
13
14class SkData;
15
16class SkStream;
17class SkStreamRewindable;
18class SkStreamSeekable;
19class SkStreamAsset;
20class SkStreamMemory;
21
22/**
23 *  SkStream -- abstraction for a source of bytes. Subclasses can be backed by
24 *  memory, or a file, or something else.
25 *
26 *  NOTE:
27 *
28 *  Classic "streams" APIs are sort of async, in that on a request for N
29 *  bytes, they may return fewer than N bytes on a given call, in which case
30 *  the caller can "try again" to get more bytes, eventually (modulo an error)
31 *  receiving their total N bytes.
32 *
33 *  Skia streams behave differently. They are effectively synchronous, and will
34 *  always return all N bytes of the request if possible. If they return fewer
35 *  (the read() call returns the number of bytes read) then that means there is
36 *  no more data (at EOF or hit an error). The caller should *not* call again
37 *  in hopes of fulfilling more of the request.
38 */
39class SK_API SkStream : public SkRefCnt { //TODO: remove SkRefCnt
40public:
41    /**
42     *  Attempts to open the specified file, and return a stream to it (using
43     *  mmap if available). On success, the caller must call unref() on the
44     *  returned object. On failure, returns NULL.
45     */
46    static SkStreamAsset* NewFromFile(const char path[]);
47
48    SK_DECLARE_INST_COUNT(SkStream)
49
50    /** Reads or skips size number of bytes.
51     *  If buffer == NULL, skip size bytes, return how many were skipped.
52     *  If buffer != NULL, copy size bytes into buffer, return how many were copied.
53     *  @param buffer when NULL skip size bytes, otherwise copy size bytes into buffer
54     *  @param size the number of bytes to skip or copy
55     *  @return bytes read on success
56     */
57    virtual size_t read(void* buffer, size_t size) = 0;
58
59    /** Skip size number of bytes.
60     *  @return the actual number bytes that could be skipped.
61     */
62    size_t skip(size_t size) {
63        //return this->read(NULL, size);
64        //TODO: remove this old logic after updating existing implementations
65        return 0 == size ? 0 : this->read(NULL, size);
66    }
67
68    /** Returns true if there are no more bytes to be read.
69     *  In Progress: do not use until all implementations are updated.
70     *  TODO: after this is implemented everywhere, make pure virtual.
71     */
72    virtual bool isAtEnd() const {
73        SkASSERT(false);
74        return true;
75    }
76
77    int8_t   readS8();
78    int16_t  readS16();
79    int32_t  readS32();
80
81    uint8_t  readU8() { return (uint8_t)this->readS8(); }
82    uint16_t readU16() { return (uint16_t)this->readS16(); }
83    uint32_t readU32() { return (uint32_t)this->readS32(); }
84
85    bool     readBool() { return this->readU8() != 0; }
86    SkScalar readScalar();
87    size_t   readPackedUInt();
88
89    /**
90     *  Reconstitute an SkData object that was written to the stream
91     *  using SkWStream::writeData().
92     */
93    SkData* readData();
94
95//SkStreamRewindable
96    /** Rewinds to the beginning of the stream. If this cannot be done, return false. */
97    virtual bool rewind() { return false; }
98
99    /** Duplicates this stream. If this cannot be done, returns NULL.
100     *  The returned stream will be positioned at the beginning of its data.
101     */
102    virtual SkStreamRewindable* duplicate() const { return NULL; }
103
104//SkStreamSeekable
105    /** Returns true if this stream can report it's current position. */
106    virtual bool hasPosition() const { return false; }
107    /** Returns the current position in the stream. If this cannot be done, returns 0. */
108    virtual size_t getPosition() const { return 0; }
109
110    /** Seeks to an absolute position in the stream. If this cannot be done, returns false.
111     *  If an attempt is made to seek past the end of the stream, the position will be set
112     *  to the end of the stream.
113     */
114    virtual bool seek(size_t position) { return false; }
115
116    /** Seeks to an relative offset in the stream. If this cannot be done, returns false.
117     *  If an attempt is made to move to a position outside the stream, the position will be set
118     *  to the closest point within the stream (beginning or end).
119     */
120    virtual bool move(long offset) { return false; }
121
122    /** Duplicates this stream. If this cannot be done, returns NULL.
123     *  The returned stream will be positioned the same as this stream.
124     */
125    virtual SkStreamSeekable* fork() const { return NULL; }
126
127//SkStreamAsset
128    /** Returns true if this stream can report it's total length. */
129    virtual bool hasLength() const { return false; }
130    /** Returns the total length of the stream. If this cannot be done, returns 0. */
131    virtual size_t getLength() const {
132        //return 0;
133        //TODO: remove the following after everyone is updated.
134        return ((SkStream*)this)->read(NULL, 0);
135    }
136
137//SkStreamMemory
138    /** Returns the starting address for the data. If this cannot be done, returns NULL. */
139    //TODO: replace with virtual const SkData* getData()
140    virtual const void* getMemoryBase() { return NULL; }
141
142private:
143    typedef SkRefCnt INHERITED;
144};
145
146/** SkStreamRewindable is a SkStream for which rewind and duplicate are required. */
147class SK_API SkStreamRewindable : public SkStream {
148public:
149    //TODO: remove the following after everyone is updated (ensures new behavior on new classes).
150    virtual bool isAtEnd() const SK_OVERRIDE = 0;
151    //TODO: remove the following after everyone is updated (ensures new behavior on new classes).
152    virtual size_t getLength() const SK_OVERRIDE { return 0; }
153
154    virtual bool rewind() SK_OVERRIDE = 0;
155    virtual SkStreamRewindable* duplicate() const SK_OVERRIDE = 0;
156};
157
158/** SkStreamSeekable is a SkStreamRewindable for which position, seek, move, and fork are required. */
159class SK_API SkStreamSeekable : public SkStreamRewindable {
160public:
161    virtual SkStreamSeekable* duplicate() const SK_OVERRIDE = 0;
162
163    virtual bool hasPosition() const SK_OVERRIDE { return true; }
164    virtual size_t getPosition() const SK_OVERRIDE = 0;
165    virtual bool seek(size_t position) SK_OVERRIDE = 0;
166    virtual bool move(long offset) SK_OVERRIDE = 0;
167    virtual SkStreamSeekable* fork() const SK_OVERRIDE = 0;
168};
169
170/** SkStreamAsset is a SkStreamSeekable for which getLength is required. */
171class SK_API SkStreamAsset : public SkStreamSeekable {
172public:
173    virtual SkStreamAsset* duplicate() const SK_OVERRIDE = 0;
174    virtual SkStreamAsset* fork() const SK_OVERRIDE = 0;
175
176    virtual bool hasLength() const SK_OVERRIDE { return true; }
177    virtual size_t getLength() const SK_OVERRIDE = 0;
178};
179
180/** SkStreamMemory is a SkStreamAsset for which getMemoryBase is required. */
181class SK_API SkStreamMemory : public SkStreamAsset {
182public:
183    virtual SkStreamMemory* duplicate() const SK_OVERRIDE = 0;
184    virtual SkStreamMemory* fork() const SK_OVERRIDE = 0;
185
186    virtual const void* getMemoryBase() SK_OVERRIDE = 0;
187};
188
189class SK_API SkWStream : SkNoncopyable {
190public:
191    SK_DECLARE_INST_COUNT_ROOT(SkWStream)
192
193    virtual ~SkWStream();
194
195    /** Called to write bytes to a SkWStream. Returns true on success
196        @param buffer the address of at least size bytes to be written to the stream
197        @param size The number of bytes in buffer to write to the stream
198        @return true on success
199    */
200    virtual bool write(const void* buffer, size_t size) = 0;
201    virtual void newline();
202    virtual void flush();
203
204    // helpers
205
206    bool    write8(U8CPU);
207    bool    write16(U16CPU);
208    bool    write32(uint32_t);
209
210    bool    writeText(const char text[]);
211    bool    writeDecAsText(int32_t);
212    bool    writeBigDecAsText(int64_t, int minDigits = 0);
213    bool    writeHexAsText(uint32_t, int minDigits = 0);
214    bool    writeScalarAsText(SkScalar);
215
216    bool    writeBool(bool v) { return this->write8(v); }
217    bool    writeScalar(SkScalar);
218    bool    writePackedUInt(size_t);
219
220    bool writeStream(SkStream* input, size_t length);
221
222    /**
223     * Append an SkData object to the stream, such that it can be read
224     * out of the stream using SkStream::readData().
225     *
226     * Note that the encoding method used to write the SkData object
227     * to the stream may change over time.  This method DOES NOT
228     * just write the raw content of the SkData object to the stream.
229     */
230    bool writeData(const SkData*);
231};
232
233////////////////////////////////////////////////////////////////////////////////////////
234
235#include "SkString.h"
236
237struct SkFILE;
238
239/** A stream that wraps a C FILE* file stream. */
240class SK_API SkFILEStream : public SkStreamAsset {
241public:
242    SK_DECLARE_INST_COUNT(SkFILEStream)
243
244    /** Initialize the stream by calling sk_fopen on the specified path.
245     *  This internal stream will be closed in the destructor.
246     */
247    explicit SkFILEStream(const char path[] = NULL);
248
249    enum Ownership {
250        kCallerPasses_Ownership,
251        kCallerRetains_Ownership
252    };
253    /** Initialize the stream with an existing C file stream.
254     *  While this stream exists, it assumes exclusive access to the C file stream.
255     *  The C file stream will be closed in the destructor unless the caller specifies
256     *  kCallerRetains_Ownership.
257     */
258    explicit SkFILEStream(FILE* file, Ownership ownership = kCallerPasses_Ownership);
259
260    virtual ~SkFILEStream();
261
262    /** Returns true if the current path could be opened. */
263    bool isValid() const { return fFILE != NULL; }
264
265    /** Close the current file, and open a new file with the specified path.
266     *  If path is NULL, just close the current file.
267     */
268    void setPath(const char path[]);
269
270    virtual size_t read(void* buffer, size_t size) SK_OVERRIDE;
271    virtual bool isAtEnd() const SK_OVERRIDE;
272
273    virtual bool rewind() SK_OVERRIDE;
274    virtual SkStreamAsset* duplicate() const SK_OVERRIDE;
275
276    virtual size_t getPosition() const SK_OVERRIDE;
277    virtual bool seek(size_t position) SK_OVERRIDE;
278    virtual bool move(long offset) SK_OVERRIDE;
279    virtual SkStreamAsset* fork() const SK_OVERRIDE;
280
281    virtual size_t getLength() const SK_OVERRIDE;
282
283    const void* getMemoryBase() SK_OVERRIDE;
284
285private:
286    SkFILE*     fFILE;
287    SkString    fName;
288    Ownership   fOwnership;
289    // fData is lazilly initialized when needed.
290    mutable SkAutoTUnref<SkData> fData;
291
292    typedef SkStreamAsset INHERITED;
293};
294
295class SK_API SkMemoryStream : public SkStreamMemory {
296public:
297    SK_DECLARE_INST_COUNT(SkMemoryStream)
298
299    SkMemoryStream();
300
301    /** We allocate (and free) the memory. Write to it via getMemoryBase() */
302    SkMemoryStream(size_t length);
303
304    /** If copyData is true, the stream makes a private copy of the data. */
305    SkMemoryStream(const void* data, size_t length, bool copyData = false);
306
307    /** Use the specified data as the memory for this stream.
308     *  The stream will call ref() on the data (assuming it is not NULL).
309     */
310    SkMemoryStream(SkData*);
311
312    virtual ~SkMemoryStream();
313
314    /** Resets the stream to the specified data and length,
315        just like the constructor.
316        if copyData is true, the stream makes a private copy of the data
317    */
318    virtual void setMemory(const void* data, size_t length,
319                           bool copyData = false);
320    /** Replace any memory buffer with the specified buffer. The caller
321        must have allocated data with sk_malloc or sk_realloc, since it
322        will be freed with sk_free.
323    */
324    void setMemoryOwned(const void* data, size_t length);
325
326    /** Return the stream's data in a SkData.
327     *  The caller must call unref() when it is finished using the data.
328     */
329    SkData* copyToData() const;
330
331    /**
332     *  Use the specified data as the memory for this stream.
333     *  The stream will call ref() on the data (assuming it is not NULL).
334     *  The function returns the data parameter as a convenience.
335     */
336    SkData* setData(SkData*);
337
338    void skipToAlign4();
339    const void* getAtPos();
340    size_t peek() const { return fOffset; }
341
342    virtual size_t read(void* buffer, size_t size) SK_OVERRIDE;
343    virtual bool isAtEnd() const SK_OVERRIDE;
344
345    virtual bool rewind() SK_OVERRIDE;
346    virtual SkMemoryStream* duplicate() const SK_OVERRIDE;
347
348    virtual size_t getPosition() const SK_OVERRIDE;
349    virtual bool seek(size_t position) SK_OVERRIDE;
350    virtual bool move(long offset) SK_OVERRIDE;
351    virtual SkMemoryStream* fork() const SK_OVERRIDE;
352
353    virtual size_t getLength() const SK_OVERRIDE;
354
355    virtual const void* getMemoryBase() SK_OVERRIDE;
356
357private:
358    SkData* fData;
359    size_t  fOffset;
360
361    typedef SkStreamMemory INHERITED;
362};
363
364/////////////////////////////////////////////////////////////////////////////////////////////
365
366class SK_API SkFILEWStream : public SkWStream {
367public:
368    SK_DECLARE_INST_COUNT(SkFILEWStream)
369
370    SkFILEWStream(const char path[]);
371    virtual ~SkFILEWStream();
372
373    /** Returns true if the current path could be opened.
374    */
375    bool isValid() const { return fFILE != NULL; }
376
377    virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
378    virtual void flush() SK_OVERRIDE;
379
380private:
381    SkFILE* fFILE;
382
383    typedef SkWStream INHERITED;
384};
385
386class SkMemoryWStream : public SkWStream {
387public:
388    SK_DECLARE_INST_COUNT(SkMemoryWStream)
389
390    SkMemoryWStream(void* buffer, size_t size);
391    virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
392    size_t bytesWritten() const { return fBytesWritten; }
393
394private:
395    char*   fBuffer;
396    size_t  fMaxLength;
397    size_t  fBytesWritten;
398
399    typedef SkWStream INHERITED;
400};
401
402class SK_API SkDynamicMemoryWStream : public SkWStream {
403public:
404    SK_DECLARE_INST_COUNT(SkDynamicMemoryWStream)
405
406    SkDynamicMemoryWStream();
407    virtual ~SkDynamicMemoryWStream();
408
409    virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
410    // random access write
411    // modifies stream and returns true if offset + size is less than or equal to getOffset()
412    bool write(const void* buffer, size_t offset, size_t size);
413    bool read(void* buffer, size_t offset, size_t size);
414    size_t getOffset() const { return fBytesWritten; }
415    size_t bytesWritten() const { return fBytesWritten; }
416
417    // copy what has been written to the stream into dst
418    void copyTo(void* dst) const;
419
420    /**
421     *  Return a copy of the data written so far. This call is responsible for
422     *  calling unref() when they are finished with the data.
423     */
424    SkData* copyToData() const;
425
426    // reset the stream to its original state
427    void reset();
428    void padToAlign4();
429private:
430    struct Block;
431    Block*  fHead;
432    Block*  fTail;
433    size_t  fBytesWritten;
434    mutable SkData* fCopy;  // is invalidated if we write after it is created
435
436    void invalidateCopy();
437
438    typedef SkWStream INHERITED;
439};
440
441
442class SK_API SkDebugWStream : public SkWStream {
443public:
444    SK_DECLARE_INST_COUNT(SkDebugWStream)
445
446    // overrides
447    virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
448    virtual void newline() SK_OVERRIDE;
449
450private:
451    typedef SkWStream INHERITED;
452};
453
454// for now
455typedef SkFILEStream SkURLStream;
456
457#endif
458