memory: xstrchrnul and xmemscan.

This commit is contained in:
Scott Prager 2014-09-05 04:25:34 -04:00
parent afe7ba1e71
commit eff839b26d
4 changed files with 34 additions and 10 deletions

View File

@ -222,6 +222,35 @@ void *xmemdupz(const void *data, size_t len)
return memcpy(xmallocz(len), data, len);
}
/// A version of strchr() that returns a pointer to the terminating NUL if it
/// doesn't find `c`.
///
/// @param str The string to search.
/// @param c The char to look for.
/// @returns a pointer to the first instance of `c`, or to the NUL terminator
/// if not found.
char *xstrchrnul(const char *str, char c)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
{
char *p = strchr(str, c);
return p ? p : (char *)(str + strlen(str));
}
/// A version of memchr() that returns a pointer one past the end
/// if it doesn't find `c`.
///
/// @param addr The address of the memory object.
/// @param c The char to look for.
/// @param size The size of the memory object.
/// @returns a pointer to the first instance of `c`, or one past the end if not
/// found.
void *xmemscan(const void *addr, char c, size_t size)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
{
char *p = memchr(addr, c, size);
return p ? p : (char *)addr + size;
}
/// The xstpcpy() function shall copy the string pointed to by src (including
/// the terminating NUL character) into the array pointed to by dst.
///

View File

@ -3173,8 +3173,7 @@ int vim_vsnprintf(char *str, size_t str_m, char *fmt, va_list ap, typval_T *tvs)
p = "";
while (*p != NUL) {
if (*p != '%') {
char *q = strchr(p + 1, '%');
size_t n = (q == NULL) ? STRLEN(p) : (size_t)(q - p);
size_t n = xstrchrnul(p + 1, '%') - p;
/* Copy up to the next '%' or NUL without any changes. */
if (str_l < str_m) {

View File

@ -4903,10 +4903,9 @@ static void str_to_reg(struct yankreg *y_ptr,
* Find the end of each line and save it into the array.
*/
for (start = 0; start < len + extraline; start += i + 1) {
for (i = start; i < len; ++i) /* find the end of the line */
if (str[i] == '\n')
break;
i -= start; /* i is now length of line */
// Let i represent the length of one line.
const char_u *p = str + start;
i = (char_u *)xmemscan(p, '\n', len - start) - p;
if (i > maxlen)
maxlen = i;
if (append) {

View File

@ -134,10 +134,7 @@ static bool is_executable_in_path(const char_u *name, char_u **abspath)
// Walk through all entries in $PATH to check if "name" exists there and
// is an executable file.
for (;; ) {
const char *e = strchr(path, ':');
if (e == NULL) {
e = path + STRLEN(path);
}
const char *e = xstrchrnul(path, ':');
// Glue together the given directory from $PATH with name and save into
// buf.