1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/disk_cache/simple/simple_util.h"
9 #include "base/file_util.h"
10 #include "base/format_macros.h"
11 #include "base/logging.h"
12 #include "base/sha1.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "base/time/time.h"
17 #include "net/disk_cache/simple/simple_entry_format.h"
21 // Size of the uint64 hash_key number in Hex format in a string.
22 const size_t kEntryHashKeyAsHexStringSize
= 2 * sizeof(uint64
);
26 namespace disk_cache
{
28 namespace simple_util
{
30 std::string
ConvertEntryHashKeyToHexString(uint64 hash_key
) {
31 const std::string hash_key_str
= base::StringPrintf("%016" PRIx64
, hash_key
);
32 DCHECK_EQ(kEntryHashKeyAsHexStringSize
, hash_key_str
.size());
36 std::string
GetEntryHashKeyAsHexString(const std::string
& key
) {
37 std::string hash_key_str
=
38 ConvertEntryHashKeyToHexString(GetEntryHashKey(key
));
39 DCHECK_EQ(kEntryHashKeyAsHexStringSize
, hash_key_str
.size());
43 bool GetEntryHashKeyFromHexString(const base::StringPiece
& hash_key
,
44 uint64
* hash_key_out
) {
45 if (hash_key
.size() != kEntryHashKeyAsHexStringSize
) {
48 return base::HexStringToUInt64(hash_key
, hash_key_out
);
51 uint64
GetEntryHashKey(const std::string
& key
) {
53 unsigned char sha_hash
[base::kSHA1Length
];
56 base::SHA1HashBytes(reinterpret_cast<const unsigned char*>(key
.data()),
57 key
.size(), u
.sha_hash
);
61 std::string
GetFilenameFromEntryHashAndIndex(uint64 entry_hash
,
63 return base::StringPrintf("%016" PRIx64
"_%1d", entry_hash
, index
);
66 std::string
GetFilenameFromKeyAndIndex(const std::string
& key
, int index
) {
67 return GetEntryHashKeyAsHexString(key
) + base::StringPrintf("_%1d", index
);
70 int32
GetDataSizeFromKeyAndFileSize(const std::string
& key
, int64 file_size
) {
71 int64 data_size
= file_size
- key
.size() - sizeof(SimpleFileHeader
) -
72 sizeof(SimpleFileEOF
);
73 DCHECK_GE(implicit_cast
<int64
>(std::numeric_limits
<int32
>::max()), data_size
);
77 int64
GetFileSizeFromKeyAndDataSize(const std::string
& key
, int32 data_size
) {
78 return data_size
+ key
.size() + sizeof(SimpleFileHeader
) +
79 sizeof(SimpleFileEOF
);
82 int64
GetFileOffsetFromKeyAndDataOffset(const std::string
& key
,
84 const int64 headers_size
= sizeof(disk_cache::SimpleFileHeader
) + key
.size();
85 return headers_size
+ data_offset
;
88 // TODO(clamy, gavinp): this should go in base
89 bool GetMTime(const base::FilePath
& path
, base::Time
* out_mtime
) {
91 base::PlatformFileInfo file_info
;
92 if (!file_util::GetFileInfo(path
, &file_info
))
94 *out_mtime
= file_info
.last_modified
;
98 } // namespace simple_backend
100 } // namespace disk_cache