aboutsummaryrefslogtreecommitdiff
path: root/butl/path-map
blob: fc66002e6d156c9f7d1e88ae2d057349c5f002f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// file      : butl/path-map -*- C++ -*-
// copyright : Copyright (c) 2014-2016 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#ifndef BUTL_PATH_MAP
#define BUTL_PATH_MAP

#include <butl/path>
#include <butl/prefix-map>

namespace butl
{
  // prefix_map for filesystem paths
  //
  // Important: the paths should be normalized and canonicalized.
  //
  // Note that the path's representation of POSIX root ('/') is
  // inconsistent in that we have a trailing delimiter at the end of
  // the path (its "proper" representation would have been an empty
  // string but that would have clashed with empty paths). To work
  // around this snag, this implementation, during key comparison,
  // detects '/' and treats it as empty. Note that the map will
  // still store the key as you have first inserted it. So if you
  // want a particular representation (i.e., empty or '/'), pre-
  // populate the map with it.
  //
  template <typename C, typename K>
  struct compare_prefix<basic_path<C, K>>: compare_prefix<std::basic_string<C>>
  {
    typedef basic_path<C, K> key_type;

    typedef C delimiter_type;
    typedef std::basic_string<C> string_type;
    typedef compare_prefix<std::basic_string<C>> base;

    explicit
    compare_prefix (delimiter_type d): base (d) {}

    bool
    operator() (const key_type& x, const key_type& y) const
    {
      const string_type& xs (x.string ());
      const string_type& ys (y.string ());

      return base::compare (xs.c_str (),
                            root (xs) ? 0 : xs.size (),
                            ys.c_str (),
                            root (ys) ? 0 : ys.size ()) < 0;
    }

    bool
    prefix (const key_type& p, const key_type& k) const
    {
      const string_type& ps (p.string ());
      const string_type& ks (k.string ());

      return base::prefix (root (ps) ? string_type () : ps,
                           root (ks) ? string_type () : ks);
    }

  protected:
    static bool
    root (const string_type& p)
    {
      return p.size () == 1 && key_type::traits::is_separator (p[0]);
    }
  };

  template <typename T>
  using path_map = prefix_map<path, T, path::traits::directory_separator>;

  template <typename T>
  using dir_path_map =
    prefix_map<dir_path, T, dir_path::traits::directory_separator>;
}

#endif // BUTL_PATH_MAP