| 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 "src/sksl/SkSLOutputStream.h" |
| 12 |
#include "src/sksl/SkSLUtil.h" |
| 13 |
#include <stdio.h> |
| 14 |
|
| 15 |
namespace SkSL { |
| 16 |
|
| 17 |
class FileOutputStream : public OutputStream { |
| 18 |
public: |
| 19 |
FileOutputStream(const char* name) { |
| 20 |
fFile = fopen(name, "wb"); |
| 21 |
} |
| 22 |
|
| 23 |
~FileOutputStream() override { |
| 24 |
if (fOpen) { |
| 25 |
close(); |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
bool isValid() const override { |
| 30 |
return nullptr != fFile; |
| 31 |
} |
| 32 |
|
| 33 |
void write8(uint8_t b) override { |
| 34 |
SkASSERT(fOpen); |
| 35 |
if (isValid()) { |
| 36 |
if (EOF == fputc(b, fFile)) { |
| 37 |
fFile = nullptr; |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
void writeText(const char* s) override { |
| 43 |
SkASSERT(fOpen); |
| 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 |
|
| 73 |
using INHERITED = OutputStream; |
| 74 |
}; |
| 75 |
|
| 76 |
} // namespace |
| 77 |
|
| 78 |
#endif |