xref: /aosp_15_r20/external/cronet/base/files/safe_base_name.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/files/file_path.h"
12 
13 namespace base {
14 
15 // Represents the last path component of a FilePath object, either a file or a
16 // directory. This type does not allow absolute paths or references to parent
17 // directories and is considered safe to be passed over IPC. See
18 // FilePath::BaseName().
19 // Usage examples:
20 // std::optional<SafeBaseName> a
21 //     (SafeBaseName::Create(FILE_PATH_LITERAL("file.txt")));
22 // FilePath dir(FILE_PATH_LITERAL("foo")); dir.Append(*a);
23 class BASE_EXPORT SafeBaseName {
24  public:
25   // TODO(crbug.com/1269986): Change to only be exposed to Mojo.
26   SafeBaseName() = default;
27 
28   // Factory method that returns a valid SafeBaseName or std::nullopt.
29   static std::optional<SafeBaseName> Create(const FilePath&);
30 
31   // Same as above, but takes a StringPieceType for convenience.
32   static std::optional<SafeBaseName> Create(FilePath::StringPieceType);
path()33   const FilePath& path() const { return path_; }
34 
35   bool operator==(const SafeBaseName& that) const;
36 
37  private:
38   // Constructs a new SafeBaseName from the given FilePath.
39   explicit SafeBaseName(const FilePath&);
40   FilePath path_;
41 };
42 
43 }  // namespace base
44 
45 #endif  // BASE_FILES_SAFE_BASE_NAME_H_
46