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 | |
| 11 | #include "SkSLOutputStream.h" |
Hal Canary | e80e618 | 2017-04-05 12:55:32 -0400 | [diff] [blame] | 12 | #include "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: |
| 19 | FileOutputStream(const char* name) { |
Brian Osman | 8d4b56b | 2017-08-15 14:34:09 -0400 | [diff] [blame] | 20 | fFile = fopen(name, "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 { |
Ethan Nicholas | d9d33c3 | 2018-06-12 11:05:59 -0400 | [diff] [blame] | 24 | SkASSERT(!fOpen); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 25 | } |
| 26 | |
| 27 | bool isValid() const override { |
| 28 | return nullptr != fFile; |
| 29 | } |
| 30 | |
| 31 | void write8(uint8_t b) override { |
Ethan Nicholas | d9d33c3 | 2018-06-12 11:05:59 -0400 | [diff] [blame] | 32 | SkASSERT(fOpen); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 33 | if (isValid()) { |
| 34 | if (EOF == fputc(b, fFile)) { |
| 35 | fFile = nullptr; |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | void writeText(const char* s) override { |
Ethan Nicholas | d9d33c3 | 2018-06-12 11:05:59 -0400 | [diff] [blame] | 41 | SkASSERT(fOpen); |
Ethan Nicholas | 0df1b04 | 2017-03-31 13:56:23 -0400 | [diff] [blame] | 42 | 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 | |
| 67 | private: |
| 68 | bool fOpen = true; |
| 69 | FILE *fFile; |
| 70 | |
| 71 | typedef OutputStream INHERITED; |
| 72 | }; |
| 73 | |
| 74 | } // namespace |
| 75 | |
| 76 | #endif |