Add util function to locate a column in a string
This will help to parse the result of "adb shell ip route" to find the device IP address. PR #2827 <https://github.com/Genymobile/scrcpy/pull/2827>
This commit is contained in:
@@ -304,3 +304,29 @@ sc_str_truncate(char *data, size_t len, const char *endchars) {
|
||||
data[idx] = '\0';
|
||||
return idx;
|
||||
}
|
||||
|
||||
ssize_t
|
||||
sc_str_index_of_column(const char *s, unsigned col, const char *seps) {
|
||||
size_t colidx = 0;
|
||||
|
||||
size_t idx = 0;
|
||||
while (s[idx] != '\0' && colidx != col) {
|
||||
size_t r = strcspn(&s[idx], seps);
|
||||
idx += r;
|
||||
|
||||
if (s[idx] == '\0') {
|
||||
// Not found
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t consecutive_seps = strspn(&s[idx], seps);
|
||||
assert(consecutive_seps); // At least one
|
||||
idx += consecutive_seps;
|
||||
|
||||
if (s[idx] != '\0') {
|
||||
++colidx;
|
||||
}
|
||||
}
|
||||
|
||||
return col == colidx ? (ssize_t) idx : -1;
|
||||
}
|
||||
|
||||
@@ -114,4 +114,24 @@ sc_str_wrap_lines(const char *input, unsigned columns, unsigned indent);
|
||||
size_t
|
||||
sc_str_truncate(char *data, size_t len, const char *endchars);
|
||||
|
||||
/**
|
||||
* Find the start of a column in a string
|
||||
*
|
||||
* A string may represent several columns, separated by some "spaces"
|
||||
* (separators). This function aims to find the start of the column number
|
||||
* `col`.
|
||||
*
|
||||
* For example, to find the 4th column (column number 3):
|
||||
*
|
||||
* // here
|
||||
* // v
|
||||
* const char *s = "abc def ghi jk";
|
||||
* ssize_t index = sc_str_index_of_column(s, 3, " ");
|
||||
* assert(index == 16); // points to "jk"
|
||||
*
|
||||
* Return -1 if no such column exists.
|
||||
*/
|
||||
ssize_t
|
||||
sc_str_index_of_column(const char *s, unsigned col, const char *seps);
|
||||
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user