dinit-util.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef DINIT_UTIL_H_INCLUDED
  2. #define DINIT_UTIL_H_INCLUDED 1
  3. #include <string>
  4. #include <cstddef>
  5. #include <cerrno>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. // Complete read - read the specified size until end-of-file or error; continue read if
  9. // interrupted by signal.
  10. inline ssize_t complete_read(int fd, void * buf, size_t n)
  11. {
  12. char * cbuf = static_cast<char *>(buf);
  13. ssize_t r = 0;
  14. while ((size_t)r < n) {
  15. ssize_t res = read(fd, cbuf + r, n - r);
  16. if (res == 0) {
  17. return r;
  18. }
  19. if (res < 0) {
  20. if (errno == EINTR) {
  21. continue;
  22. }
  23. // If any other error, and we have successfully read some, return it:
  24. if (r == 0) {
  25. return -1;
  26. }
  27. else {
  28. return r;
  29. }
  30. }
  31. r += res;
  32. }
  33. return n;
  34. }
  35. // Combine two paths to produce a path. If the second path is absolute, it is returned unmodified;
  36. // otherwise, it is appended to the first path (with a slash separator added if needed).
  37. inline std::string combine_paths(const std::string &p1, const char * p2)
  38. {
  39. if (*p2 == 0) return p1;
  40. if (p1.empty()) return std::string(p2);
  41. if (p2[0] == '/') return p2;
  42. if (*(p1.rbegin()) == '/') return p1 + p2;
  43. return p1 + '/' + p2;
  44. }
  45. // Find the parent path of a given path, which should refer to a named file or directory (not . or ..).
  46. // If the path contains no directory, returns the empty string.
  47. inline std::string parent_path(const std::string &p)
  48. {
  49. auto spos = p.rfind('/');
  50. if (spos == std::string::npos) {
  51. return std::string {};
  52. }
  53. return p.substr(0, spos + 1);
  54. }
  55. // Find the base name of a path (the name after the final '/').
  56. inline const char * base_name(const char *path)
  57. {
  58. const char * basen = path;
  59. const char * s = path;
  60. while (*s != 0) {
  61. if (*s == '/') basen = s + 1;
  62. s++;
  63. }
  64. return basen;
  65. }
  66. // Check if one string starts with another
  67. inline bool starts_with(std::string s, const char *prefix)
  68. {
  69. const char * sp = s.c_str();
  70. while (*sp != 0 && *prefix != 0) {
  71. if (*sp != *prefix) return false;
  72. sp++; prefix++;
  73. }
  74. return *prefix == 0;
  75. }
  76. #endif