1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2  * vim: set ts=8 sts=2 et sw=2 tw=80:
3  * This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef util_CompleteFile_h
8 #define util_CompleteFile_h
9 
10 #include "mozilla/Assertions.h"  // MOZ_ASSERT
11 
12 #include <stdint.h>  // uint8_t
13 #include <stdio.h>   // fclose, FILE, stdin
14 
15 #include "jstypes.h"         // JS_PUBLIC_API
16 #include "js/AllocPolicy.h"  // js::TempAllocPolicy
17 #include "js/Vector.h"       // js::Vector
18 
19 struct JS_PUBLIC_API JSContext;
20 
21 namespace js {
22 
23 using FileContents = Vector<uint8_t, 8, TempAllocPolicy>;
24 
25 extern bool ReadCompleteFile(JSContext* cx, FILE* fp, FileContents& buffer);
26 
27 class AutoFile {
28   FILE* fp_ = nullptr;
29 
30  public:
31   AutoFile() = default;
32 
~AutoFile()33   ~AutoFile() {
34     if (fp_ && fp_ != stdin) {
35       fclose(fp_);
36     }
37   }
38 
fp()39   FILE* fp() const { return fp_; }
40 
41   bool open(JSContext* cx, const char* filename);
42 
readAll(JSContext * cx,FileContents & buffer)43   bool readAll(JSContext* cx, FileContents& buffer) {
44     MOZ_ASSERT(fp_);
45     return ReadCompleteFile(cx, fp_, buffer);
46   }
47 };
48 
49 }  // namespace js
50 
51 #endif /* util_CompleteFile_h */
52