1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
|
/* vim:set ts=8 sts=4 sw=4 tw=0: */
/*
* wordbuf.h -
*
* Written By: MURAOKA Taro <koron.kaoriya@gmail.com>
* Last Change: 25-Oct-2011.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "wordbuf.h"
#define WORDLEN_DEF 64
int n_wordbuf_open = 0; /* for DEBUG */
int n_wordbuf_close = 0; /* for DEBUG */
/* function pre-declaration */
static int wordbuf_extend(wordbuf_p p, int len);
wordbuf_p
wordbuf_open()
{
wordbuf_p p = (wordbuf_p)malloc(sizeof(wordbuf_t));
if (p)
{
++n_wordbuf_open; /* for DEBUG */
p->len = WORDLEN_DEF;
p->buf = (unsigned char*)malloc(p->len);
p->last = 0;
p->buf[0] = '\0';
}
return p;
}
void
wordbuf_close(wordbuf_p p)
{
if (p)
{
++n_wordbuf_close; /* for DEBUG */
free(p->buf);
free(p);
}
}
void
wordbuf_reset(wordbuf_p p)
{
p->last = 0;
p->buf[0] = '\0';
}
/*
* wordbuf_extend(wordbuf_p p, int req_len);
* obt@̐LBG[ɂ0AB
* ̂߂ɐLׂ͌ďoŔfB
*/
static int
wordbuf_extend(wordbuf_p p, int req_len)
{
int newlen = p->len * 2;
unsigned char *newbuf;
while (req_len > newlen)
newlen *= 2;
if (!(newbuf = (unsigned char*)realloc(p->buf, newlen)))
{
/*fprintf(stderr, "wordbuf_add(): failed to extend buffer\n");*/
return 0;
}
else
{
p->len = newlen;
p->buf = newbuf;
return req_len;
}
}
int
wordbuf_last(wordbuf_p p)
{
return p->last;
}
int
wordbuf_add(wordbuf_p p, unsigned char ch)
{
int newlen = p->last + 2;
if (newlen > p->len && !wordbuf_extend(p, newlen))
return 0;
else
{
#if 1
unsigned char *buf = p->buf + p->last;
buf[0] = ch;
buf[1] = '\0';
#else
/* gGfBA肷Ȃg邪c */
*(unsigned short*)&p->buf[p->last] = (unsigned short)ch;
#endif
return ++p->last;
}
}
int
wordbuf_cat(wordbuf_p p, const unsigned char* sz)
{
int len = 0;
if (sz != NULL)
{
size_t l = strlen(sz);
len = l < INT_MAX ? (int)l : INT_MAX;
}
if (len > 0)
{
int newlen = p->last + len + 1;
if (newlen > p->len && !wordbuf_extend(p, newlen))
return 0;
memcpy(&p->buf[p->last], sz, len + 1);
p->last = p->last + len;
}
return p->last;
}
unsigned char*
wordbuf_get(wordbuf_p p)
{
return p->buf;
}
|