2 * qrencode - QR Code encoder
4 * Binary sequence class.
5 * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "bitstream.h"
28 BitStream *BitStream_new(void)
32 bstream = (BitStream *)malloc(sizeof(BitStream));
33 if(bstream == NULL) return NULL;
41 static int BitStream_allocate(BitStream *bstream, int length)
49 data = (unsigned char *)malloc(length);
57 bstream->length = length;
63 static BitStream *BitStream_newFromNum(int bits, unsigned int num)
70 bstream = BitStream_new();
71 if(bstream == NULL) return NULL;
73 if(BitStream_allocate(bstream, bits)) {
74 BitStream_free(bstream);
79 mask = 1 << (bits - 1);
80 for(i=0; i<bits; i++) {
93 static BitStream *BitStream_newFromBytes(int size, unsigned char *data)
100 bstream = BitStream_new();
101 if(bstream == NULL) return NULL;
103 if(BitStream_allocate(bstream, size * 8)) {
104 BitStream_free(bstream);
109 for(i=0; i<size; i++) {
125 int BitStream_append(BitStream *bstream, BitStream *arg)
132 if(arg->length == 0) {
135 if(bstream->length == 0) {
136 if(BitStream_allocate(bstream, arg->length)) {
139 memcpy(bstream->data, arg->data, arg->length);
143 data = (unsigned char *)malloc(bstream->length + arg->length);
147 memcpy(data, bstream->data, bstream->length);
148 memcpy(data + bstream->length, arg->data, arg->length);
151 bstream->length += arg->length;
152 bstream->data = data;
157 int BitStream_appendNum(BitStream *bstream, int bits, unsigned int num)
162 if(bits == 0) return 0;
164 b = BitStream_newFromNum(bits, num);
165 if(b == NULL) return -1;
167 ret = BitStream_append(bstream, b);
173 int BitStream_appendBytes(BitStream *bstream, int size, unsigned char *data)
178 if(size == 0) return 0;
180 b = BitStream_newFromBytes(size, data);
181 if(b == NULL) return -1;
183 ret = BitStream_append(bstream, b);
189 unsigned char *BitStream_toByte(BitStream *bstream)
191 int i, j, size, bytes;
192 unsigned char *data, v;
195 size = BitStream_size(bstream);
199 data = (unsigned char *)malloc((size + 7) / 8);
207 for(i=0; i<bytes; i++) {
218 for(j=0; j<(size & 7); j++) {
229 void BitStream_free(BitStream *bstream)
231 if(bstream != NULL) {