• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef SRC_UTILS_IO_TMPFILE_H_
16 #define SRC_UTILS_IO_TMPFILE_H_
17 
18 #include <sstream>
19 #include <string>
20 
21 namespace tint {
22 namespace utils {
23 
24 /// TmpFile constructs a temporary file that can be written to, and is
25 /// automatically deleted on destruction.
26 class TmpFile {
27  public:
28   /// Constructor.
29   /// Creates a new temporary file which can be written to.
30   /// The temporary file will be automatically deleted on destruction.
31   /// @param extension optional file extension to use with the file. The file
32   /// have no extension by default.
33   explicit TmpFile(std::string extension = "");
34 
35   /// Destructor.
36   /// Deletes the temporary file.
37   ~TmpFile();
38 
39   /// @return true if the temporary file was successfully created.
40   operator bool() { return !path_.empty(); }
41 
42   /// @return the path to the temporary file
Path()43   std::string Path() const { return path_; }
44 
45   /// Opens the temporary file and appends |size| bytes from |data| to the end
46   /// of the temporary file. The temporary file is closed again before
47   /// returning, allowing other processes to open the file on operating systems
48   /// that require exclusive ownership of opened files.
49   /// @param data the data to write to the end of the file
50   /// @param size the number of bytes to write from data
51   /// @returns true on success, otherwise false
52   bool Append(const void* data, size_t size) const;
53 
54   /// Appends the argument to the end of the file.
55   /// @param data the data to write to the end of the file
56   /// @return a reference to this TmpFile
57   template <typename T>
58   inline TmpFile& operator<<(T&& data) {
59     std::stringstream ss;
60     ss << data;
61     std::string str = ss.str();
62     Append(str.data(), str.size());
63     return *this;
64   }
65 
66  private:
67   TmpFile(const TmpFile&) = delete;
68   TmpFile& operator=(const TmpFile&) = delete;
69 
70   std::string path_;
71 };
72 
73 }  // namespace utils
74 }  // namespace tint
75 
76 #endif  //  SRC_UTILS_IO_TMPFILE_H_
77