aboutsummaryrefslogtreecommitdiff
path: root/cutl/fs/path.txx
blob: ff5095b6dee316e4b3e7ae0e9ac4c46875431364 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// file      : cutl/fs/path.txx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009 Code Synthesis Tools CC
// license   : MIT; see accompanying LICENSE file

namespace cutl
{
  namespace fs
  {
    template <typename C>
    basic_path<C> basic_path<C>::
    leaf () const
    {
      size_type n (path_.size ()), i (n);

      for (; i > 0; --i)
      {
        if (path_[i - 1] == '/' || path_[i - 1] == '\\')
          break;
      }

      return i != 0 ? basic_path (path_.c_str () + i, n - i) : *this;
    }

    template <typename C>
    basic_path<C> basic_path<C>::
    directory () const
    {
      size_type i (path_.size ());

      for (; i > 0; --i)
      {
        if (path_[i - 1] == '/' || path_[i - 1] == '\\')
          break;
      }

      return i != 0 ? basic_path (path_.c_str (), i - 1) : *this;
    }

    template <typename C>
    basic_path<C> basic_path<C>::
    base () const
    {
      size_type i (path_.size ());

      for (; i > 0; --i)
      {
        if (path_[i - 1] == '.')
          break;

        if (path_[i - 1] == '/' || path_[i - 1] == '\\')
        {
          i = 0;
          break;
        }
      }

      // Weed out paths like ".txt" and "/.txt"
      //
      if (i > 1 && path_[i - 2] != '/' && path_[i - 2] != '\\')
      {
        return basic_path (path_.c_str (), i - 1);
      }
      else
        return *this;
    }

    template <typename C>
    basic_path<C> basic_path<C>::
    operator/ (basic_path<C> const& r)
    {
      if (r.path_.empty ())
        throw invalid_basic_path<C> (r.path_);

      basic_path<C> x (*this);
      x.path_ += '/';
      x.path_ += r.path_;
      return x;
    }

    template <typename C>
    void basic_path<C>::
    init (bool internal)
    {
      if (!internal && path_.empty ())
        throw invalid_basic_path<C> (path_);

      // Strip trailing slashes. This way empty string represents
      // root directory.
      //
      size_type n (path_.size ());
      for (; n > 0 && (path_[n - 1] == '/' || path_[n - 1] == '\\'); --n) ;
      path_.resize (n);
    }
  }
}