blob: 94939f6219e93a595cc49910855733caebba7947 [file] [log] [blame]
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001/*
2 * Copyright 2017 Google Inc.
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 SKSL_FILEOUTPUTSTREAM
9#define SKSL_FILEOUTPUTSTREAM
10
11#include "SkSLOutputStream.h"
Hal Canarye80e6182017-04-05 12:55:32 -040012#include "SkSLUtil.h"
Ethan Nicholas0df1b042017-03-31 13:56:23 -040013#include <stdio.h>
14
15namespace SkSL {
16
17class FileOutputStream : public OutputStream {
18public:
19 FileOutputStream(const char* name) {
Brian Osman8d4b56b2017-08-15 14:34:09 -040020 fFile = fopen(name, "wb");
Ethan Nicholas0df1b042017-03-31 13:56:23 -040021 }
22
Matt Sarett76fcb102017-05-05 13:21:52 -040023 ~FileOutputStream() override {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040024 SkASSERT(!fOpen);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040025 }
26
27 bool isValid() const override {
28 return nullptr != fFile;
29 }
30
31 void write8(uint8_t b) override {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040032 SkASSERT(fOpen);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040033 if (isValid()) {
34 if (EOF == fputc(b, fFile)) {
35 fFile = nullptr;
36 }
37 }
38 }
39
40 void writeText(const char* s) override {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040041 SkASSERT(fOpen);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040042 if (isValid()) {
43 if (EOF == fputs(s, fFile)) {
44 fFile = nullptr;
45 }
46 }
47 }
48
49 void write(const void* s, size_t size) override {
50 if (isValid()) {
51 size_t written = fwrite(s, 1, size, fFile);
52 if (written != size) {
53 fFile = nullptr;
54 }
55 }
56 }
57
58 bool close() {
59 fOpen = false;
60 if (isValid() && fclose(fFile)) {
61 fFile = nullptr;
62 return false;
63 }
64 return true;
65 }
66
67private:
68 bool fOpen = true;
69 FILE *fFile;
70
71 typedef OutputStream INHERITED;
72};
73
74} // namespace
75
76#endif