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 | |
| 3 | namespace aos { |
| 4 | namespace libc { |
| 5 | namespace { |
| 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 |