blob: 324d71cdb2c71c4d03fdaceabe50a8370c206de7 [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 Pleines4b02e7b2024-05-30 20:29:39 -07003#include <stddef.h>
4
Stephan Pleinesf63bde82024-01-13 15:59:33 -08005namespace aos::libc {
Brian Silvermanaf784862014-05-13 08:14:55 -07006namespace {
7
8::std::string DoDirname(const ::std::string &path, size_t last_slash) {
9 // If there aren't any other '/'s in it.
10 if (last_slash == ::std::string::npos) return ".";
11
12 // Back up as long as we see '/'s.
13 do {
14 // If we get all the way to the beginning.
15 if (last_slash == 0) return "/";
16 --last_slash;
17 } while (path[last_slash] == '/');
18
19 return path.substr(0, last_slash + 1);
20}
21
22} // namespace
23
24::std::string Dirname(const ::std::string &path) {
25 // Without this, we end up with integer underflows below, which is technically
26 // undefined.
27 if (path.size() == 0) return ".";
28
29 size_t last_slash = path.rfind('/');
30
31 // If the path ends with a '/'.
32 if (last_slash == path.size() - 1) {
33 last_slash = DoDirname(path, last_slash).rfind('/');
34 }
35
36 return DoDirname(path, last_slash);
37}
38
Stephan Pleinesf63bde82024-01-13 15:59:33 -080039} // namespace aos::libc