Home | History | Annotate | Download | only in sksl
      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"
     12 #include "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         ASSERT(!fOpen);
     25     }
     26 
     27     bool isValid() const override {
     28         return nullptr != fFile;
     29     }
     30 
     31     void write8(uint8_t b) override {
     32         ASSERT(fOpen);
     33         if (isValid()) {
     34             if (EOF == fputc(b, fFile)) {
     35                 fFile = nullptr;
     36             }
     37         }
     38     }
     39 
     40     void writeText(const char* s) override {
     41         ASSERT(fOpen);
     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
     77