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