SkStream.h revision 884300dca5531f60535501424bbd86b30e20450a
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 value)   {
198        uint8_t v = SkToU8(value);
199        return this->write(&v, 1);
200    }
201    bool write16(U16CPU value) {
202        uint16_t v = SkToU16(value);
203        return this->write(&v, 2);
204    }
205    bool write32(uint32_t v) {
206        return this->write(&v, 4);
207    }
208
209    bool writeText(const char text[]) {
210        SkASSERT(text);
211        return this->write(text, strlen(text));
212    }
213    bool    writeDecAsText(int32_t);
214    bool    writeBigDecAsText(int64_t, int minDigits = 0);
215    bool    writeHexAsText(uint32_t, int minDigits = 0);
216    bool    writeScalarAsText(SkScalar);
217
218    bool    writeBool(bool v) { return this->write8(v); }
219    bool    writeScalar(SkScalar);
220    bool    writePackedUInt(size_t);
221
222    bool    writeStream(SkStream* input, size_t length);
223
224    /**
225     * This returns the number of bytes in the stream required to store
226     * 'value'.
227     */
228    static int SizeOfPackedUInt(size_t value);
229};
230
231////////////////////////////////////////////////////////////////////////////////////////
232
233#include "SkString.h"
234#include <stdio.h>
235
236/** A stream that wraps a C FILE* file stream. */
237class SK_API SkFILEStream : public SkStreamAsset {
238public:
239    /** Initialize the stream by calling sk_fopen on the specified path.
240     *  This internal stream will be closed in the destructor.
241     */
242    explicit SkFILEStream(const char path[] = NULL);
243
244    enum Ownership {
245        kCallerPasses_Ownership,
246        kCallerRetains_Ownership
247    };
248    /** Initialize the stream with an existing C file stream.
249     *  While this stream exists, it assumes exclusive access to the C file stream.
250     *  The C file stream will be closed in the destructor unless the caller specifies
251     *  kCallerRetains_Ownership.
252     */
253    explicit SkFILEStream(FILE* file, Ownership ownership = kCallerPasses_Ownership);
254
255    virtual ~SkFILEStream();
256
257    /** Returns true if the current path could be opened. */
258    bool isValid() const { return fFILE != NULL; }
259
260    /** Close the current file, and open a new file with the specified path.
261     *  If path is NULL, just close the current file.
262     */
263    void setPath(const char path[]);
264
265    size_t read(void* buffer, size_t size) override;
266    bool isAtEnd() const override;
267
268    bool rewind() override;
269    SkStreamAsset* duplicate() const override;
270
271    size_t getPosition() const override;
272    bool seek(size_t position) override;
273    bool move(long offset) override;
274    SkStreamAsset* fork() const override;
275
276    size_t getLength() const override;
277
278    const void* getMemoryBase() override;
279
280private:
281    FILE*       fFILE;
282    SkString    fName;
283    Ownership   fOwnership;
284    // fData is lazilly initialized when needed.
285    mutable sk_sp<SkData> fData;
286
287    typedef SkStreamAsset INHERITED;
288};
289
290class SK_API SkMemoryStream : public SkStreamMemory {
291public:
292    SkMemoryStream();
293
294    /** We allocate (and free) the memory. Write to it via getMemoryBase() */
295    SkMemoryStream(size_t length);
296
297    /** If copyData is true, the stream makes a private copy of the data. */
298    SkMemoryStream(const void* data, size_t length, bool copyData = false);
299
300    /** Creates the stream to read from the specified data */
301    SkMemoryStream(sk_sp<SkData>);
302
303    /** Resets the stream to the specified data and length,
304        just like the constructor.
305        if copyData is true, the stream makes a private copy of the data
306    */
307    virtual void setMemory(const void* data, size_t length,
308                           bool copyData = false);
309    /** Replace any memory buffer with the specified buffer. The caller
310        must have allocated data with sk_malloc or sk_realloc, since it
311        will be freed with sk_free.
312    */
313    void setMemoryOwned(const void* data, size_t length);
314
315    sk_sp<SkData> asData() const { return fData; }
316    void setData(sk_sp<SkData>);
317
318    void skipToAlign4();
319    const void* getAtPos();
320
321    size_t read(void* buffer, size_t size) override;
322    bool isAtEnd() const override;
323
324    size_t peek(void* buffer, size_t size) const override;
325
326    bool rewind() override;
327    SkMemoryStream* duplicate() const override;
328
329    size_t getPosition() const override;
330    bool seek(size_t position) override;
331    bool move(long offset) override;
332    SkMemoryStream* fork() const override;
333
334    size_t getLength() const override;
335
336    const void* getMemoryBase() override;
337
338private:
339    sk_sp<SkData>   fData;
340    size_t          fOffset;
341
342    typedef SkStreamMemory INHERITED;
343};
344
345/////////////////////////////////////////////////////////////////////////////////////////////
346
347class SK_API SkFILEWStream : public SkWStream {
348public:
349    SkFILEWStream(const char path[]);
350    virtual ~SkFILEWStream();
351
352    /** Returns true if the current path could be opened.
353    */
354    bool isValid() const { return fFILE != NULL; }
355
356    bool write(const void* buffer, size_t size) override;
357    void flush() override;
358    void fsync();
359    size_t bytesWritten() const override;
360
361private:
362    FILE* fFILE;
363
364    typedef SkWStream INHERITED;
365};
366
367class SK_API SkMemoryWStream : public SkWStream {
368public:
369    SkMemoryWStream(void* buffer, size_t size);
370    bool write(const void* buffer, size_t size) override;
371    size_t bytesWritten() const override { return fBytesWritten; }
372
373private:
374    char*   fBuffer;
375    size_t  fMaxLength;
376    size_t  fBytesWritten;
377
378    typedef SkWStream INHERITED;
379};
380
381class SK_API SkDynamicMemoryWStream : public SkWStream {
382public:
383    SkDynamicMemoryWStream();
384    virtual ~SkDynamicMemoryWStream();
385
386    bool write(const void* buffer, size_t size) override;
387    size_t bytesWritten() const override;
388
389    bool read(void* buffer, size_t offset, size_t size);
390
391    /** More efficient version of read(dst, 0, bytesWritten()). */
392    void copyTo(void* dst) const;
393    void writeToStream(SkWStream* dst) const;
394
395    /** Return the contents as SkData, and then reset the stream. */
396    sk_sp<SkData> detachAsData();
397
398    /** Reset, returning a reader stream with the current content. */
399    SkStreamAsset* detachAsStream();
400
401    /** Reset the stream to its original, empty, state. */
402    void reset();
403    void padToAlign4();
404private:
405    struct Block;
406    Block*  fHead;
407    Block*  fTail;
408    size_t  fBytesWrittenBeforeTail;
409
410#ifdef SK_DEBUG
411    void validate() const;
412#else
413    void validate() const {}
414#endif
415
416    // For access to the Block type.
417    friend class SkBlockMemoryStream;
418    friend class SkBlockMemoryRefCnt;
419
420    typedef SkWStream INHERITED;
421};
422
423
424class SK_API SkDebugWStream : public SkWStream {
425public:
426    SkDebugWStream() : fBytesWritten(0) {}
427
428    // overrides
429    bool write(const void* buffer, size_t size) override;
430    void newline() override;
431    size_t bytesWritten() const override { return fBytesWritten; }
432
433private:
434    size_t fBytesWritten;
435    typedef SkWStream INHERITED;
436};
437
438// for now
439typedef SkFILEStream SkURLStream;
440
441#endif
442