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