aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/sksl/SkSLFileOutputStream.h
blob: 7d8394162cba37a513c02675769ca61e73087dc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SKSL_FILEOUTPUTSTREAM
#define SKSL_FILEOUTPUTSTREAM

#include "SkSLOutputStream.h"
#include "SkSLUtil.h"
#include <stdio.h>

namespace SkSL {

class FileOutputStream : public OutputStream {
public:
    FileOutputStream(const char* name) {
        fFile = fopen(name, "wb");
    }

    ~FileOutputStream() override {
        ASSERT(!fOpen);
    }

    bool isValid() const override {
        return nullptr != fFile;
    }

    void write8(uint8_t b) override {
        ASSERT(fOpen);
        if (isValid()) {
            if (EOF == fputc(b, fFile)) {
                fFile = nullptr;
            }
        }
    }

    void writeText(const char* s) override {
        ASSERT(fOpen);
        if (isValid()) {
            if (EOF == fputs(s, fFile)) {
                fFile = nullptr;
            }
        }
    }

    void write(const void* s, size_t size) override {
        if (isValid()) {
            size_t written = fwrite(s, 1, size, fFile);
            if (written != size) {
                fFile = nullptr;
            }
        }
    }

    bool close() {
        fOpen = false;
        if (isValid() && fclose(fFile)) {
            fFile = nullptr;
            return false;
        }
        return true;
    }

private:
    bool fOpen = true;
    FILE *fFile;

    typedef OutputStream INHERITED;
};

} // namespace

#endif