1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-07-01 19:42:48 -05:00

Introduce a new 'ptrlen' type.

This wraps up a (pointer, length) pair into a convenient struct that
lets me return it by value from a function, and also pass it through
to other functions in one go.

Ideally quite a lot of this code base could be switched over to using
ptrlen in place of separate pointer and length variables or function
parameters. (In fact, in my personal ideal conception of C, the usual
string type would be of this form, and all the string.h functions
would operate on ptrlens instead of zero-terminated 'char *'.)

For the moment, I'm just introducing it to make some upcoming
refactoring less inconvenient. Bulk migration of existing code to
ptrlen is a project for another time.

Along with the type itself, I've provided a convenient system of
including the contents of a ptrlen in a printf; a constructor function
that wraps up a pointer and length so you can make a ptrlen on the fly
in mid-expression; a function to compare a ptrlen against an ordinary
C string (which I mostly expect to use with string literals); and a
function 'mkstr' to make a dynamically allocated C string out of one.
That last function replaces a function of the same name in sftp.c,
which I'm promoting to a whole-codebase facility and adjusting its
API.
This commit is contained in:
Simon Tatham
2018-05-27 16:56:51 +01:00
parent 8d882756b8
commit 9e96af59ce
9 changed files with 77 additions and 29 deletions

32
misc.c
View File

@ -360,6 +360,16 @@ int toint(unsigned u)
return INT_MIN; /* fallback; should never occur on binary machines */
}
int string_length_for_printf(size_t s)
{
/* Truncate absurdly long strings (should one show up) to fit
* within a positive 'int', which is what the "%.*s" format will
* expect. */
if (s > INT_MAX)
return INT_MAX;
return s;
}
/*
* Do an sprintf(), but into a custom-allocated buffer.
*
@ -1177,6 +1187,28 @@ int match_ssh_id(int stringlen, const void *string, const char *id)
return (idlen == stringlen && !memcmp(string, id, idlen));
}
ptrlen make_ptrlen(const void *ptr, size_t len)
{
ptrlen pl;
pl.ptr = ptr;
pl.len = len;
return pl;
}
int ptrlen_eq_string(ptrlen pl, const char *str)
{
size_t len = strlen(str);
return (pl.len == len && !memcmp(pl.ptr, str, len));
}
char *mkstr(ptrlen pl)
{
char *p = snewn(pl.len + 1, char);
memcpy(p, pl.ptr, pl.len);
p[pl.len] = '\0';
return p;
}
void *get_ssh_string(int *datalen, const void **data, int *stringlen)
{
void *ret;