Browse Source

Update lib hexio module

master
Damien Goutte-Gattat 9 years ago
parent
commit
a7cd9d21e2
  1. 98
      lib/hexio.c
  2. 8
      lib/hexio.h

98
lib/hexio.c

@ -95,7 +95,7 @@ fprinth(FILE *f, unsigned char *buffer, size_t len)
return n + 1;
}
size_t
ssize_t
freadh(FILE *f, unsigned char *buffer, size_t len)
{
int c;
@ -202,3 +202,99 @@ freadha(FILE *f, unsigned char **buffer, size_t *len)
return m;
}
ssize_t
freadhd(FILE *f, unsigned char *buffer, size_t len, int *intext)
{
int c;
size_t n;
char bytes[3];
enum { OFFSET, HIGHCHAR, LOWCHAR, TEXT } state;
if ( ! f || ! buffer ) {
errno = EINVAL;
return -1;
}
n = 0;
bytes[2] = 0;
state = ( intext && *intext ) ? TEXT : OFFSET;
while ( (c = fgetc(f)) != EOF && n < len ) {
switch ( state ) {
case OFFSET:
if ( c == ' ' )
state = HIGHCHAR;
break;
case HIGHCHAR:
if ( isxdigit(c) ) {
bytes[0] = c;
state = LOWCHAR;
}
else if ( c == '|' )
state = TEXT;
break;
case LOWCHAR:
if ( isxdigit(c) ) {
bytes[1] = c;
buffer[n++] = strtol(bytes, NULL, 16);
}
state = HIGHCHAR;
break;
case TEXT:
if ( c == '\n' )
state = OFFSET;
break;
}
}
if ( intext )
*intext = state == TEXT;
return n;
}
ssize_t
freadhda(FILE *f, unsigned char **buffer, size_t *len)
{
unsigned char buf[BLOCK_SIZE];
size_t n, m, l;
int s;
if ( ! f || ! buffer ) {
errno = EINVAL;
return -1;
}
if ( ! len )
len = &l;
if ( ! *buffer )
*len = 0;
n = m = s = 0;
while ( (n = freadhd(f, buf, sizeof(buf), &s)) > 0 ) {
if ( *len < m + n ) {
#ifdef EXIT_ENOMEM
*len += BLOCK_SIZE;
*buffer = xrealloc(*buffer, *len);
#else
unsigned char *p;
if ( ! (p = realloc(*buffer, *len + BLOCK_SIZE)) )
return -1;
*buffer = p;
*len += BLOCK_SIZE;
#endif
}
memcpy(*buffer + m, buf, n);
m += n;
}
return m;
}

8
lib/hexio.h

@ -31,12 +31,18 @@ fprinthd(FILE *, unsigned char *, size_t, unsigned);
int
fprinth(FILE *, unsigned char *, size_t);
size_t
ssize_t
freadh(FILE *, unsigned char *, size_t);
ssize_t
freadha(FILE *, unsigned char **, size_t *);
ssize_t
freadhd(FILE *, unsigned char *, size_t, int *);
ssize_t
freadhda(FILE *, unsigned char **, size_t *);
#ifdef __cplusplus
}
#endif

Loading…
Cancel
Save