John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 1 | #include "aos/libc/dirname.h" |
Brian Silverman | af78486 | 2014-05-13 08:14:55 -0700 | [diff] [blame] | 2 | |
Stephan Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 3 | namespace aos::libc { |
Brian Silverman | af78486 | 2014-05-13 08:14:55 -0700 | [diff] [blame] | 4 | namespace { |
| 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 Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 37 | } // namespace aos::libc |