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 | 4b02e7b | 2024-05-30 20:29:39 -0700 | [diff] [blame] | 3 | #include <stddef.h> |
| 4 | |
Stephan Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 5 | namespace aos::libc { |
Brian Silverman | af78486 | 2014-05-13 08:14:55 -0700 | [diff] [blame] | 6 | namespace { |
| 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 Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 39 | } // namespace aos::libc |