1 //
2 // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 #pragma once
8 
9 #include "td/utils/Slice.h"
10 
11 namespace td {
12 
13 class PathView {
14  public:
15   explicit PathView(Slice path);
16 
empty()17   bool empty() const {
18     return path_.empty();
19   }
20 
is_dir()21   bool is_dir() const {
22     if (empty()) {
23       return false;
24     }
25     return is_slash(path_.back());
26   }
27 
parent_dir()28   Slice parent_dir() const {
29     return path_.substr(0, last_slash_ + 1);
30   }
31   Slice parent_dir_noslash() const;
32 
extension()33   Slice extension() const {
34     if (last_dot_ == static_cast<int32>(path_.size())) {
35       return Slice();
36     }
37     return path_.substr(last_dot_ + 1);
38   }
39 
without_extension()40   Slice without_extension() const {
41     return path_.substr(0, last_dot_);
42   }
43 
file_stem()44   Slice file_stem() const {
45     return path_.substr(last_slash_ + 1, last_dot_ - last_slash_ - 1);
46   }
47 
file_name()48   Slice file_name() const {
49     return path_.substr(last_slash_ + 1);
50   }
51 
path()52   Slice path() const {
53     return path_;
54   }
55 
is_absolute()56   bool is_absolute() const {
57     return !empty() && (is_slash(path_[0]) || (path_.size() >= 3 && path_[1] == ':' && is_slash(path_[2])));
58   }
59 
is_relative()60   bool is_relative() const {
61     return !is_absolute();
62   }
63 
64   static Slice relative(Slice path, Slice dir, bool force = false);
65   static Slice dir_and_file(Slice path);
66 
67  private:
is_slash(char c)68   static bool is_slash(char c) {
69     return c == '/' || c == '\\';
70   }
71 
72   Slice path_;
73   int32 last_slash_;
74   int32 last_dot_;
75 };
76 
77 }  // namespace td
78