Fix compilation with old g++ 3.3.5 and debian-sarge.
[wvstreams.git] / utils / wvhex.cc
blob44a24bd4d60695ff1f70d040ee487dec07dc9eb4
1 /*
2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
5 * Hex encoder and decoder.
6 */
7 #include "wvhex.h"
8 #include <ctype.h>
11 static inline char tohex(int digit, char alphabase)
13 return (digit < 10 ? '0' : alphabase) + digit;
16 static inline int fromhex(char digit)
18 if (isdigit(digit))
19 return digit - '0';
20 if (isupper(digit))
21 return digit - 'A' + 10;
22 return digit - 'a' + 10;
25 /***** WvHexEncoder *****/
27 WvHexEncoder::WvHexEncoder(bool use_uppercase)
29 alphabase = (use_uppercase ? 'A' : 'a') - 10;
30 _reset();
34 bool WvHexEncoder::_reset()
36 return true;
40 bool WvHexEncoder::_encode(WvBuf &in, WvBuf &out, bool flush)
42 while (in.used() != 0)
44 unsigned char byte = in.getch();
45 out.putch(tohex(byte >> 4, alphabase));
46 out.putch(tohex(byte & 15, alphabase));
48 return true;
52 /***** WvHexDecoder *****/
54 WvHexDecoder::WvHexDecoder()
56 _reset();
60 bool WvHexDecoder::_reset()
62 issecond = false;
63 first = 0;
64 return true;
68 bool WvHexDecoder::_encode(WvBuf &in, WvBuf &out, bool flush)
70 while (in.used() != 0)
72 char ch = (char) in.getch();
73 if (isxdigit(ch))
75 int digit = fromhex(ch);
76 if ( (issecond = ! issecond) )
77 first = digit;
78 else
79 out.putch(first << 4 | digit);
80 continue;
82 if (isspace(ch))
83 continue;
84 seterror("invalid character '%s' in hex input", ch);
85 return false;
87 if (flush && issecond)
88 return false; // not enough hex digits supplied
89 return true;
93 /*** Compatibility ***/
95 void hexify(char *obuf, const void *ibuf, size_t len)
97 size_t outlen = len * 2 + 1;
98 WvHexEncoder(false /*use_uppercase*/).
99 flushmemmem(ibuf, len, obuf, & outlen);
100 obuf[outlen] = '\0';
104 void unhexify(void *obuf, const char *ibuf)
106 size_t inlen = strlen(ibuf);
107 size_t outlen = inlen / 2;
108 WvHexDecoder().flushmemmem(ibuf, inlen, obuf, & outlen);