xref: /aosp_15_r20/external/icing/icing/file/destructible-file.h (revision 8b6cd535a057e39b3b86660c4aa06c99747c2136)
1 // Copyright (C) 2021 Google LLC
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 ICING_FILE_DESTRUCTIBLE_FILE_H_
16 #define ICING_FILE_DESTRUCTIBLE_FILE_H_
17 
18 #include <unistd.h>
19 
20 #include <string>
21 
22 #include "icing/file/filesystem.h"
23 #include "icing/util/logging.h"
24 
25 namespace icing {
26 namespace lib {
27 
28 // A convenient RAII class which will open the specified file path for write and
29 // delete the underlying file upon destruction.
30 class DestructibleFile {
31  public:
DestructibleFile(const std::string & filepath,const Filesystem * filesystem)32   explicit DestructibleFile(const std::string& filepath,
33                             const Filesystem* filesystem)
34       : filesystem_(filesystem), filepath_(filepath) {
35     fd_ = filesystem_->OpenForWrite(filepath_.c_str());
36   }
37 
38   DestructibleFile(const DestructibleFile&) = delete;
DestructibleFile(DestructibleFile && other)39   DestructibleFile(DestructibleFile&& other) : filesystem_(nullptr), fd_(-1) {
40     *this = std::move(other);
41   }
42 
43   DestructibleFile& operator=(const DestructibleFile&) = delete;
44   DestructibleFile& operator=(DestructibleFile&& other) {
45     std::swap(fd_, other.fd_);
46     std::swap(filesystem_, other.filesystem_);
47     std::swap(filepath_, other.filepath_);
48     return *this;
49   }
50 
~DestructibleFile()51   ~DestructibleFile() {
52     if (is_valid()) {
53       close(fd_);
54       if (!filesystem_->DeleteFile(filepath_.c_str())) {
55         ICING_VLOG(1) << "Failed to delete file " << filepath_;
56       }
57     }
58   }
59 
is_valid()60   bool is_valid() const { return fd_ >= 0; }
get_fd()61   int get_fd() const { return fd_; }
62 
63  private:
64   const Filesystem* filesystem_;
65   std::string filepath_;
66   int fd_;
67 };
68 
69 }  // namespace lib
70 }  // namespace icing
71 
72 #endif  // ICING_FILE_DESTRUCTIBLE_FILE_H_
73