xref: /aosp_15_r20/external/cronet/base/files/scoped_temp_file.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/files/scoped_temp_file.h"
6 
7 #include <utility>
8 
9 #include "base/check.h"
10 #include "base/files/file_util.h"
11 #include "base/logging.h"
12 
13 namespace base {
14 
15 ScopedTempFile::ScopedTempFile() = default;
16 
ScopedTempFile(ScopedTempFile && other)17 ScopedTempFile::ScopedTempFile(ScopedTempFile&& other) noexcept
18     : path_(std::move(other.path_)) {}
19 
operator =(ScopedTempFile && other)20 ScopedTempFile& ScopedTempFile::operator=(ScopedTempFile&& other) noexcept {
21   if (!path_.empty()) {
22     CHECK_NE(path_, other.path_);
23   }
24   if (!Delete()) {
25     DLOG(WARNING) << "Could not delete temp dir in operator=().";
26   }
27   path_ = std::move(other.path_);
28   return *this;
29 }
30 
~ScopedTempFile()31 ScopedTempFile::~ScopedTempFile() {
32   if (!Delete()) {
33     DLOG(WARNING) << "Could not delete temp dir in destructor.";
34   }
35 }
36 
Create()37 bool ScopedTempFile::Create() {
38   CHECK(path_.empty());
39   return base::CreateTemporaryFile(&path_);
40 }
41 
Delete()42 bool ScopedTempFile::Delete() {
43   if (path_.empty()) {
44     return true;
45   }
46   if (DeleteFile(path_)) {
47     path_.clear();
48     return true;
49   }
50   return false;
51 }
52 
Reset()53 void ScopedTempFile::Reset() {
54   if (!Delete()) {
55     DLOG(WARNING) << "Could not delete temp dir in Reset().";
56   }
57   path_.clear();
58 }
59 
60 }  // namespace base
61