blob: 956ed3f12028090437bb8653fd489d94d65848fa [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLOutputStream.h"
12#include "src/sksl/SkSLUtil.h"
Ethan Nicholas0df1b042017-03-31 13:56:23 -040013#include <stdio.h>
14
15namespace SkSL {
16
17class FileOutputStream : public OutputStream {
18public:
John Stilesa1e8fe32020-11-11 17:29:28 -050019 FileOutputStream(const SkSL::String& name) {
20 fFile = fopen(name.c_str(), "wb");
Ethan Nicholas0df1b042017-03-31 13:56:23 -040021 }
22
Matt Sarett76fcb102017-05-05 13:21:52 -040023 ~FileOutputStream() override {
John Stilesa1e8fe32020-11-11 17:29:28 -050024 if (fOpen) {
25 close();
26 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -040027 }
28
29 bool isValid() const override {
30 return nullptr != fFile;
31 }
32
33 void write8(uint8_t b) override {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040034 SkASSERT(fOpen);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040035 if (isValid()) {
36 if (EOF == fputc(b, fFile)) {
37 fFile = nullptr;
38 }
39 }
40 }
41
42 void writeText(const char* s) override {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040043 SkASSERT(fOpen);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040044 if (isValid()) {
45 if (EOF == fputs(s, fFile)) {
46 fFile = nullptr;
47 }
48 }
49 }
50
51 void write(const void* s, size_t size) override {
52 if (isValid()) {
53 size_t written = fwrite(s, 1, size, fFile);
54 if (written != size) {
55 fFile = nullptr;
56 }
57 }
58 }
59
60 bool close() {
61 fOpen = false;
62 if (isValid() && fclose(fFile)) {
63 fFile = nullptr;
64 return false;
65 }
66 return true;
67 }
68
69private:
70 bool fOpen = true;
71 FILE *fFile;
72
John Stiles7571f9e2020-09-02 22:42:33 -040073 using INHERITED = OutputStream;
Ethan Nicholas0df1b042017-03-31 13:56:23 -040074};
75
76} // namespace
77
78#endif