blob: c843898f9e6940961862f0bc3f8a17f386d9351a [file] [log] [blame]
Brian Silvermanaf784862014-05-13 08:14:55 -07001#include "aos/common/libc/dirname.h"
2
3namespace aos {
4namespace libc {
5namespace {
6
7::std::string DoDirname(const ::std::string &path, size_t last_slash) {
8 // If there aren't any other '/'s in it.
9 if (last_slash == ::std::string::npos) return ".";
10
11 // Back up as long as we see '/'s.
12 do {
13 // If we get all the way to the beginning.
14 if (last_slash == 0) return "/";
15 --last_slash;
16 } while (path[last_slash] == '/');
17
18 return path.substr(0, last_slash + 1);
19}
20
21} // namespace
22
23::std::string Dirname(const ::std::string &path) {
24 // Without this, we end up with integer underflows below, which is technically
25 // undefined.
26 if (path.size() == 0) return ".";
27
28 size_t last_slash = path.rfind('/');
29
30 // If the path ends with a '/'.
31 if (last_slash == path.size() - 1) {
32 last_slash = DoDirname(path, last_slash).rfind('/');
33 }
34
35 return DoDirname(path, last_slash);
36}
37
38} // namespace libc
39} // namespace aos