• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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 #ifndef BASE_FILES_SAFE_BASE_NAME_H_
6 #define BASE_FILES_SAFE_BASE_NAME_H_
7 
8 #include <optional>
9 
10 #include "base/base_export.h"
11 #include "base/compiler_specific.h"
12 #include "base/files/file_path.h"
13 
14 namespace base {
15 
16 // Represents the last path component of a FilePath object, either a file or a
17 // directory. This type does not allow absolute paths or references to parent
18 // directories and is considered safe to be passed over IPC. See
19 // FilePath::BaseName().
20 // Usage examples:
21 // std::optional<SafeBaseName> a
22 //     (SafeBaseName::Create(FILE_PATH_LITERAL("file.txt")));
23 // FilePath dir(FILE_PATH_LITERAL("foo")); dir.Append(*a);
24 class BASE_EXPORT SafeBaseName {
25  public:
26   // TODO(crbug.com/40205226): Change to only be exposed to Mojo.
27   SafeBaseName() = default;
28 
29   // Factory method that returns a valid SafeBaseName or std::nullopt.
30   static std::optional<SafeBaseName> Create(const FilePath&);
31 
32   // Same as above, but takes a StringPieceType for convenience.
33   static std::optional<SafeBaseName> Create(FilePath::StringPieceType);
path()34   const FilePath& path() const LIFETIME_BOUND { return path_; }
35 
36   // Convenience functions.
AsUTF8Unsafe()37   const std::string AsUTF8Unsafe() const { return path_.AsUTF8Unsafe(); }
value()38   const FilePath::StringType& value() const LIFETIME_BOUND {
39     return path_.value();
40   }
empty()41   [[nodiscard]] bool empty() const { return path_.empty(); }
42 
43   bool operator==(const SafeBaseName& that) const;
44 
45  private:
46   // Constructs a new SafeBaseName from the given FilePath.
47   explicit SafeBaseName(const FilePath&);
48   FilePath path_;
49 };
50 
51 }  // namespace base
52 
53 #endif  // BASE_FILES_SAFE_BASE_NAME_H_
54