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