Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 1 | /* |
| 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 Klein | c0bd9f9 | 2019-04-23 12:05:21 -0500 | [diff] [blame] | 11 | #include "src/sksl/SkSLOutputStream.h" |
| 12 | #include "src/sksl/SkSLUtil.h" |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 13 | #include <stdio.h> |
| 14 | |
| 15 | namespace SkSL { |
| 16 | |
| 17 | class FileOutputStream : public OutputStream { |
| 18 | public: |
John Stiles | a1e8fe3 | 2020-11-11 17:29:28 -0500 | [diff] [blame] | 19 | FileOutputStream(const SkSL::String& name) { |
| 20 | fFile = fopen(name.c_str(), "wb"); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 21 | } |
| 22 | |
Matt Sarett | 76fcb10 | 2017-05-05 13:21:52 -0400 | [diff] [blame] | 23 | ~FileOutputStream() override { |
John Stiles | a1e8fe3 | 2020-11-11 17:29:28 -0500 | [diff] [blame] | 24 | if (fOpen) { |
| 25 | close(); |
| 26 | } |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | bool isValid() const override { |
| 30 | return nullptr != fFile; |
| 31 | } |
| 32 | |
| 33 | void write8(uint8_t b) override { |
Ethan Nicholas | d9d33c3 | 2018-06-12 11:05:59 -0400 | [diff] [blame] | 34 | SkASSERT(fOpen); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 35 | if (isValid()) { |
| 36 | if (EOF == fputc(b, fFile)) { |
| 37 | fFile = nullptr; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | void writeText(const char* s) override { |
Ethan Nicholas | d9d33c3 | 2018-06-12 11:05:59 -0400 | [diff] [blame] | 43 | SkASSERT(fOpen); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 44 | 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 | |
| 69 | private: |
| 70 | bool fOpen = true; |
| 71 | FILE *fFile; |
| 72 | |
John Stiles | 7571f9e | 2020-09-02 22:42:33 -0400 | [diff] [blame] | 73 | using INHERITED = OutputStream; |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 74 | }; |
| 75 | |
| 76 | } // namespace |
| 77 | |
| 78 | #endif |