xref: /aosp_15_r20/external/cronet/net/disk_cache/simple/simple_util_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2014 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 "net/disk_cache/simple/simple_util.h"
6 
7 #include <windows.h>
8 
9 #include "base/files/file_util.h"
10 #include "base/format_macros.h"
11 #include "base/rand_util.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "net/disk_cache/cache_util.h"
15 
16 namespace disk_cache {
17 namespace simple_util {
18 
SimpleCacheDeleteFile(const base::FilePath & path)19 bool SimpleCacheDeleteFile(const base::FilePath& path) {
20   // Even if a file was opened with FLAG_WIN_SHARE_DELETE, it is not possible to
21   // create a new file with the same name until the original file is actually
22   // deleted. To allow new files to be created with the new name right away,
23   // the file is renamed before it is deleted.
24 
25   // Why a random name? Because if the name was derived from our original name,
26   // then churn on a particular cache entry could cause flakey behaviour.
27 
28   // TODO(morlovich): Ensure these "todelete_" files are cleaned up on periodic
29   // directory sweeps.
30   const base::FilePath rename_target =
31       path.DirName().AppendASCII(base::StringPrintf("todelete_%016" PRIx64,
32                                                     base::RandUint64()));
33 
34   bool rename_succeeded =
35       !!MoveFile(path.value().c_str(), rename_target.value().c_str());
36   if (rename_succeeded)
37     return base::DeleteFile(rename_target);
38 
39   // The rename did not succeed. The fallback behaviour is to delete the file in
40   // place, which might cause some flake.
41   return base::DeleteFile(path);
42 }
43 
44 }  // namespace simple_util
45 }  // namespace disk_cache
46