Shaka Packager SDK
file_util.cc
1 // Copyright 2016 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/file/file_util.h"
8 
9 #include <inttypes.h>
10 
11 #include "packager/base/files/file_path.h"
12 #include "packager/base/files/file_util.h"
13 #include "packager/base/process/process_handle.h"
14 #include "packager/base/strings/stringprintf.h"
15 #include "packager/base/threading/platform_thread.h"
16 #include "packager/base/time/time.h"
17 
18 namespace shaka {
19 namespace {
20 // Create a temp file name using process id, thread id and current time.
21 std::string TempFileName() {
22  const int32_t process_id = static_cast<int32_t>(base::GetCurrentProcId());
23  const int32_t thread_id =
24  static_cast<int32_t>(base::PlatformThread::CurrentId());
25 
26  // We may need two or more temporary files in the same thread. There might be
27  // name collision if they are requested around the same time, e.g. called
28  // consecutively. Use a thread_local instance to avoid that.
29  static thread_local int32_t instance_id = 0;
30  ++instance_id;
31 
32  const int64_t current_time = base::Time::Now().ToInternalValue();
33  return base::StringPrintf("packager-tempfile-%x-%x-%x-%" PRIx64, process_id,
34  thread_id, instance_id, current_time);
35 }
36 } // namespace
37 
38 bool TempFilePath(const std::string& temp_dir, std::string* temp_file_path) {
39  if (temp_dir.empty()) {
40  base::FilePath file_path;
41  if (!base::CreateTemporaryFile(&file_path)) {
42  LOG(ERROR) << "Failed to create temporary file.";
43  return false;
44  }
45  *temp_file_path = file_path.AsUTF8Unsafe();
46  } else {
47  *temp_file_path =
48  base::FilePath::FromUTF8Unsafe(temp_dir)
49  .Append(base::FilePath::FromUTF8Unsafe(TempFileName()))
50  .AsUTF8Unsafe();
51  }
52  return true;
53 }
54 
55 } // namespace shaka
bool TempFilePath(const std::string &temp_dir, std::string *temp_file_path)
Definition: file_util.cc:38
All the methods that are virtual are virtual for mocking.