tizen 2.4 release
[external/xdelta3.git] / examples / iOS / xdelta3-ios-test / xdelta3-ios-test / file_v1.bin
1 /* xdelta 3 - delta compression tools and library
2  * Copyright (C) 2001, 2003, 2004, 2005, 2006, 2007,
3  * 2008, 2009, 2010.  Joshua P. MacDonald
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 /* To know more about Xdelta, start by reading xdelta3.c.  If you are
21  * ready to use the API, continue reading here.  There are two
22  * interfaces -- xd3_encode_input and xd3_decode_input -- plus a dozen
23  * or so related calls.  This interface is styled after Zlib. */
24
25 #ifndef _XDELTA3_H_
26 #define _XDELTA3_H_
27
28 #include <stddef.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32
33 /****************************************************************/
34
35 /* Default configured value of stream->winsize.  If the program
36  * supplies xd3_encode_input() with data smaller than winsize the
37  * stream will automatically buffer the input, otherwise the input
38  * buffer is used directly.
39  */
40 #ifndef XD3_DEFAULT_WINSIZE
41 #define XD3_DEFAULT_WINSIZE (1U << 23)
42 #endif
43
44 /* Default total size of the source window used in xdelta3-main.h */
45 #ifndef XD3_DEFAULT_SRCWINSZ
46 #define XD3_DEFAULT_SRCWINSZ (1U << 26)
47 #endif
48
49 /* When Xdelta requests a memory allocation for certain buffers, it
50  * rounds up to units of at least this size.  The code assumes (and
51  * asserts) that this is a power-of-two. */
52 #ifndef XD3_ALLOCSIZE
53 #define XD3_ALLOCSIZE (1U<<14)
54 #endif
55
56 /* The XD3_HARDMAXWINSIZE parameter is a safety mechanism to protect
57  * decoders against malicious files.  The decoder will never decode a
58  * window larger than this.  If the file specifies VCD_TARGET the
59  * decoder may require two buffers of this size.
60  *
61  * 8-16MB is reasonable, probably don't need to go larger. */
62 #ifndef XD3_HARDMAXWINSIZE
63 #define XD3_HARDMAXWINSIZE (1U<<24)
64 #endif
65 /* The IOPT_SIZE value sets the size of a buffer used to batch
66  * overlapping copy instructions before they are optimized by picking
67  * the best non-overlapping ranges.  The larger this buffer, the
68  * longer a forced xd3_srcwin_setup() decision is held off.  Setting
69  * this value to 0 causes an unlimited buffer to be used. */
70 #ifndef XD3_DEFAULT_IOPT_SIZE
71 #define XD3_DEFAULT_IOPT_SIZE    (1U<<15)
72 #endif
73
74 /* The maximum distance backward to search for small matches */
75 #ifndef XD3_DEFAULT_SPREVSZ
76 #define XD3_DEFAULT_SPREVSZ (1U<<18)
77 #endif
78
79 /* The default compression level
80  */
81 #ifndef XD3_DEFAULT_LEVEL
82 #define XD3_DEFAULT_LEVEL 3
83 #endif
84
85 #ifndef XD3_DEFAULT_SECONDARY_LEVEL
86 #define XD3_DEFAULT_SECONDARY_LEVEL 6
87 #endif
88
89 #ifndef XD3_USE_LARGEFILE64
90 #define XD3_USE_LARGEFILE64 1
91 #endif
92
93 /* Sizes and addresses within VCDIFF windows are represented as usize_t
94  *
95  * For source-file offsets and total file sizes, total input and
96  * output counts, the xoff_t type is used.  The decoder and encoder
97  * generally check for overflow of the xoff_t size (this is tested at
98  * the 32bit boundary [xdelta3-test.h]).
99  */
100 #ifndef _WIN32
101 #include <stdint.h>
102 typedef unsigned int usize_t;
103 #else
104 #define WIN32_LEAN_AND_MEAN
105 #if XD3_USE_LARGEFILE64
106 /* 64 bit file offsets: uses GetFileSizeEx and SetFilePointerEx.
107  * requires Win2000 or newer version of WinNT */
108 #define WINVER          0x0500
109 #define _WIN32_WINNT    0x0500
110 #else
111 /* 32 bit (DWORD) file offsets: uses GetFileSize and
112  * SetFilePointer. compatible with win9x-me and WinNT4 */
113 #define WINVER          0x0400
114 #define _WIN32_WINNT    0x0400
115 #endif
116 #include <windows.h>
117 typedef unsigned int   usize_t;
118 #ifdef _MSC_VER
119 #define inline
120 typedef signed int     ssize_t;
121 typedef unsigned char  uint8_t;
122 typedef unsigned short uint16_t;
123 typedef unsigned long  uint32_t;
124 typedef ULONGLONG      uint64_t;
125 #else
126 /* mingw32, lcc and watcom provide a proper header */
127 #include <stdint.h>
128 #endif
129 #endif
130
131 /* TODO: note that SIZEOF_USIZE_T is never set to 8, although it should be for
132  * a 64bit platform.  OTOH, may be that using 32bits is appropriate even on a
133  * 64bit platform because we allocate large arrays of these values. */
134 #if XD3_USE_LARGEFILE64
135 #define __USE_FILE_OFFSET64 1 /* GLIBC: for 64bit fileops, ... ? */
136 #ifndef _LARGEFILE_SOURCE
137 #define _LARGEFILE_SOURCE
138 #endif
139 #ifndef _FILE_OFFSET_BITS
140 #define _FILE_OFFSET_BITS 64
141 #endif
142
143 typedef uint64_t xoff_t;
144 #define SIZEOF_XOFF_T 8
145 #define SIZEOF_USIZE_T 4
146 #ifndef WIN32
147 #define Q "ll"
148 #else
149 #define Q "I64"
150 #endif
151 #else
152 typedef uint32_t xoff_t;
153 #define SIZEOF_XOFF_T 4
154 #define SIZEOF_USIZE_T 4
155 #define Q
156 #endif
157
158 #define USE_UINT32 (SIZEOF_USIZE_T == 4 || \
159                     SIZEOF_XOFF_T == 4 || REGRESSION_TEST)
160 #define USE_UINT64 (SIZEOF_USIZE_T == 8 || \
161                     SIZEOF_XOFF_T == 8 || REGRESSION_TEST)
162
163 /* TODO: probably should do something better here. */
164 #ifndef UNALIGNED_OK
165 #if defined(__i386__) || defined(__i486__) || defined(__i586__) || \
166   defined(__i686__) || defined(_X86_) || defined(__x86_64__)
167 #define UNALIGNED_OK 1
168 #else
169 #define UNALIGNED_OK 0
170 #endif
171 #endif
172
173 /**********************************************************************/
174
175 /* Whether to build the encoder, otherwise only build the decoder. */
176 #ifndef XD3_ENCODER
177 #define XD3_ENCODER 1
178 #endif
179
180 /* The code returned when main() fails, also defined in system
181    includes. */
182 #ifndef EXIT_FAILURE
183 #define EXIT_FAILURE 1
184 #endif
185
186 /* REGRESSION TEST enables the "xdelta3 test" command, which runs a
187    series of self-tests. */
188 #ifndef REGRESSION_TEST
189 #define REGRESSION_TEST 0
190 #endif
191
192 /* XD3_DEBUG=1 enables assertions and various statistics.  Levels > 1
193  * enable some additional output only useful during development and
194  * debugging. */
195 #ifndef XD3_DEBUG
196 #define XD3_DEBUG 0
197 #endif
198
199 #ifndef PYTHON_MODULE
200 #define PYTHON_MODULE 0
201 #endif
202
203 #ifndef SWIG_MODULE
204 #define SWIG_MODULE 0
205 #endif
206
207 /* There are three string matching functions supplied: one fast, one
208  * slow (default), and one soft-configurable.  To disable any of
209  * these, use the following definitions. */
210 #ifndef XD3_BUILD_SLOW
211 #define XD3_BUILD_SLOW 1
212 #endif
213 #ifndef XD3_BUILD_FAST
214 #define XD3_BUILD_FAST 1
215 #endif
216 #ifndef XD3_BUILD_FASTER
217 #define XD3_BUILD_FASTER 1
218 #endif
219 #ifndef XD3_BUILD_FASTEST
220 #define XD3_BUILD_FASTEST 1
221 #endif
222 #ifndef XD3_BUILD_SOFT
223 #define XD3_BUILD_SOFT 1
224 #endif
225 #ifndef XD3_BUILD_DEFAULT
226 #define XD3_BUILD_DEFAULT 1
227 #endif
228
229 #if XD3_DEBUG
230 #include <stdio.h>
231 #endif
232
233 /* XPRINT.  Debug output and VCDIFF_TOOLS functions report to stderr.
234  * I have used an irregular style to abbreviate [fprintf(stderr, "] as
235  * [DP(RINT "]. */
236 #define DP   fprintf
237 #define RINT stderr,
238
239 typedef struct _xd3_stream             xd3_stream;
240 typedef struct _xd3_source             xd3_source;
241 typedef struct _xd3_hash_cfg           xd3_hash_cfg;
242 typedef struct _xd3_smatcher           xd3_smatcher;
243 typedef struct _xd3_rinst              xd3_rinst;
244 typedef struct _xd3_dinst              xd3_dinst;
245 typedef struct _xd3_hinst              xd3_hinst;
246 typedef struct _xd3_winst              xd3_winst;
247 typedef struct _xd3_rpage              xd3_rpage;
248 typedef struct _xd3_addr_cache         xd3_addr_cache;
249 typedef struct _xd3_output             xd3_output;
250 typedef struct _xd3_desect             xd3_desect;
251 typedef struct _xd3_iopt_buflist       xd3_iopt_buflist;
252 typedef struct _xd3_rlist              xd3_rlist;
253 typedef struct _xd3_sec_type           xd3_sec_type;
254 typedef struct _xd3_sec_cfg            xd3_sec_cfg;
255 typedef struct _xd3_sec_stream         xd3_sec_stream;
256 typedef struct _xd3_config             xd3_config;
257 typedef struct _xd3_code_table_desc    xd3_code_table_desc;
258 typedef struct _xd3_code_table_sizes   xd3_code_table_sizes;
259 typedef struct _xd3_slist              xd3_slist;
260 typedef struct _xd3_whole_state        xd3_whole_state;
261 typedef struct _xd3_wininfo            xd3_wininfo;
262
263 /* The stream configuration has three callbacks functions, all of
264  * which may be supplied with NULL values.  If config->getblk is
265  * provided as NULL, the stream returns XD3_GETSRCBLK. */
266
267 typedef void*  (xd3_alloc_func)    (void       *opaque,
268                                     usize_t      items,
269                                     usize_t      size);
270 typedef void   (xd3_free_func)     (void       *opaque,
271                                     void       *address);
272
273 typedef int    (xd3_getblk_func)   (xd3_stream *stream,
274                                     xd3_source *source,
275                                     xoff_t      blkno);
276
277 /* These are internal functions to delay construction of encoding
278  * tables and support alternate code tables.  See the comments & code
279  * enabled by GENERIC_ENCODE_TABLES. */
280
281 typedef const xd3_dinst* (xd3_code_table_func) (void);
282 typedef int              (xd3_comp_table_func) (xd3_stream *stream,
283                                                 const uint8_t **data,
284                                                 usize_t *size);
285
286
287
288 #if XD3_DEBUG
289 #define XD3_ASSERT(x) \
290     do { if (! (x)) { DP(RINT "%s:%d: XD3 assertion failed: %s\n", __FILE__, __LINE__, #x); \
291     abort (); } } while (0)
292 #else
293 #define XD3_ASSERT(x) (void)0
294 #endif  /* XD3_DEBUG */
295
296 #ifdef __GNUC__
297 #ifndef max
298 #define max(x,y) ({ \
299         const typeof(x) _x = (x);       \
300         const typeof(y) _y = (y);       \
301         (void) (&_x == &_y);            \
302         _x > _y ? _x : _y; })
303 #endif /* __GNUC__ */
304
305 #ifndef min
306 #define min(x,y) ({ \
307         const typeof(x) _x = (x);       \
308         const typeof(y) _y = (y);       \
309         (void) (&_x == &_y);            \
310         _x < _y ? _x : _y; })
311 #endif
312 #else  /* __GNUC__ */
313 #ifndef max
314 #define max(x,y) ((x) < (y) ? (y) : (x))
315 #endif
316 #ifndef min
317 #define min(x,y) ((x) < (y) ? (x) : (y))
318 #endif
319 #endif  /* __GNUC__ */
320
321 /****************************************************************
322  PUBLIC ENUMS
323  ******************************************************************/
324
325 /* These are the five ordinary status codes returned by the
326  * xd3_encode_input() and xd3_decode_input() state machines. */
327 typedef enum {
328
329   /* An application must be prepared to handle these five return
330    * values from either xd3_encode_input or xd3_decode_input, except
331    * in the case of no-source compression, in which case XD3_GETSRCBLK
332    * is never returned.  More detailed comments for these are given in
333    * xd3_encode_input and xd3_decode_input comments, below. */
334   XD3_INPUT     = -17703, /* need input */
335   XD3_OUTPUT    = -17704, /* have output */
336   XD3_GETSRCBLK = -17705, /* need a block of source input (with no
337                            * xd3_getblk function), a chance to do
338                            * non-blocking read. */
339   XD3_GOTHEADER = -17706, /* (decode-only) after the initial VCDIFF &
340                              first window header */
341   XD3_WINSTART  = -17707, /* notification: returned before a window is
342                            * processed, giving a chance to
343                            * XD3_SKIP_WINDOW or not XD3_SKIP_EMIT that
344                            * window. */
345   XD3_WINFINISH  = -17708, /* notification: returned after
346                               encode/decode & output for a window */
347   XD3_TOOFARBACK = -17709, /* (encoder only) may be returned by
348                               getblk() if the block is too old */
349   XD3_INTERNAL   = -17710, /* internal error */
350   XD3_INVALID    = -17711, /* invalid config */
351   XD3_INVALID_INPUT = -17712, /* invalid input/decoder error */
352   XD3_NOSECOND    = -17713, /* when secondary compression finds no
353                                improvement. */
354   XD3_UNIMPLEMENTED = -17714, /* currently VCD_TARGET */
355 } xd3_rvalues;
356
357 /* special values in config->flags */
358 typedef enum
359 {
360   XD3_JUST_HDR       = (1 << 1),   /* used by VCDIFF tools, see
361                                       xdelta3-main.h. */
362   XD3_SKIP_WINDOW    = (1 << 2),   /* used by VCDIFF tools, see
363                                       xdelta3-main.h. */
364   XD3_SKIP_EMIT      = (1 << 3),   /* used by VCDIFF tools, see
365                                       xdelta3-main.h. */
366   XD3_FLUSH          = (1 << 4),   /* flush the stream buffer to
367                                       prepare for
368                                       xd3_stream_close(). */
369
370   XD3_SEC_DJW        = (1 << 5),   /* use DJW static huffman */
371   XD3_SEC_FGK        = (1 << 6),   /* use FGK adaptive huffman */
372   XD3_SEC_TYPE       = (XD3_SEC_DJW | XD3_SEC_FGK),
373
374   XD3_SEC_NODATA     = (1 << 7),   /* disable secondary compression of
375                                       the data section. */
376   XD3_SEC_NOINST     = (1 << 8),   /* disable secondary compression of
377                                       the inst section. */
378   XD3_SEC_NOADDR     = (1 << 9),   /* disable secondary compression of
379                                       the addr section. */
380
381   XD3_SEC_NOALL      = (XD3_SEC_NODATA | XD3_SEC_NOINST | XD3_SEC_NOADDR),
382
383   XD3_ADLER32        = (1 << 10),  /* enable checksum computation in
384                                       the encoder. */
385   XD3_ADLER32_NOVER  = (1 << 11),  /* disable checksum verification in
386                                       the decoder. */
387
388   XD3_ALT_CODE_TABLE = (1 << 12),  /* for testing th
389                                       e alternate code table encoding. */
390
391   XD3_NOCOMPRESS     = (1 << 13),  /* disable ordinary data
392                                     * compression feature, only search
393                                     * the source, not the target. */
394   XD3_BEGREEDY       = (1 << 14),  /* disable the "1.5-pass
395                                     * algorithm", instead use greedy
396                                     * matching.  Greedy is off by
397                                     * default. */
398   XD3_ADLER32_RECODE = (1 << 15),  /* used by "recode". */
399
400   /* 4 bits to set the compression level the same as the command-line
401    * setting -1 through -9 (-0 corresponds to the XD3_NOCOMPRESS flag,
402    * and is independent of compression level).  This is for
403    * convenience, especially with xd3_encode_memory(). */
404
405   XD3_COMPLEVEL_SHIFT = 20,  /* 20 - 24 */
406   XD3_COMPLEVEL_MASK = (0xF << XD3_COMPLEVEL_SHIFT),
407   XD3_COMPLEVEL_1 = (1 << XD3_COMPLEVEL_SHIFT),
408   XD3_COMPLEVEL_2 = (2 << XD3_COMPLEVEL_SHIFT),
409   XD3_COMPLEVEL_3 = (3 << XD3_COMPLEVEL_SHIFT),
410   XD3_COMPLEVEL_6 = (6 << XD3_COMPLEVEL_SHIFT),
411   XD3_COMPLEVEL_9 = (9 << XD3_COMPLEVEL_SHIFT),
412
413 } xd3_flags;
414
415 /* The values of this enumeration are set in xd3_config using the
416  * smatch_cfg variable.  It can be set to default, slow, fast, etc.,
417  * and soft. */
418 typedef enum
419 {
420   XD3_SMATCH_DEFAULT = 0, /* Flags may contain XD3_COMPLEVEL bits,
421                              else default. */
422   XD3_SMATCH_SLOW    = 1,
423   XD3_SMATCH_FAST    = 2,
424   XD3_SMATCH_FASTER  = 3,
425   XD3_SMATCH_FASTEST = 4,
426   XD3_SMATCH_SOFT    = 5,
427 } xd3_smatch_cfg;
428
429 /*********************************************************************
430  PRIVATE ENUMS
431 **********************************************************************/
432
433 /* stream->match_state is part of the xd3_encode_input state machine
434  *  for source matching:
435  *
436  *  1. the XD3_GETSRCBLK block-read mechanism means reentrant matching
437  *  2. this state spans encoder windows: a match and end-of-window
438  *  will continue in the next 3. the initial target byte and source
439  *  byte are a presumed match, to avoid some computation in case the
440  *  inputs are identical.
441  */
442 typedef enum {
443
444   MATCH_TARGET    = 0, /* in this state, attempt to match the start of
445                         * the target with the previously set source
446                         * address (initially 0). */
447   MATCH_BACKWARD  = 1, /* currently expanding a match backward in the
448                           source/target. */
449   MATCH_FORWARD   = 2, /* currently expanding a match forward in the
450                           source/target. */
451   MATCH_SEARCHING = 3, /* currently searching for a match. */
452
453 } xd3_match_state;
454
455 /* The xd3_encode_input state machine steps through these states in
456  * the following order.  The matcher is reentrant and returns
457  * XD3_INPUT whenever it requires more data.  After receiving
458  * XD3_INPUT, if the application reads EOF it should call
459  * xd3_stream_close().
460  */
461 typedef enum {
462
463   ENC_INIT      = 0, /* xd3_encode_input has never been called. */
464   ENC_INPUT     = 1, /* waiting for xd3_avail_input () to be called. */
465   ENC_SEARCH    = 2, /* currently searching for matches. */
466   ENC_INSTR     = 3, /* currently formatting output. */
467   ENC_FLUSH     = 4, /* currently emitting output. */
468   ENC_POSTOUT   = 5, /* after an output section. */
469   ENC_POSTWIN   = 6, /* after all output sections. */
470   ENC_ABORTED   = 7, /* abort. */
471 } xd3_encode_state;
472
473 /* The xd3_decode_input state machine steps through these states in
474  * the following order.  The matcher is reentrant and returns
475  * XD3_INPUT whenever it requires more data.  After receiving
476  * XD3_INPUT, if the application reads EOF it should call
477  * xd3_stream_close().
478  *
479  * 0-8:   the VCDIFF header
480  * 9-18:  the VCDIFF window header
481  * 19-21: the three primary sections: data, inst, addr
482  * 22:    producing output: returns XD3_OUTPUT, possibly XD3_GETSRCBLK,
483  * 23:    return XD3_WINFINISH, set state=9 to decode more input
484  */
485 typedef enum {
486
487   DEC_VCHEAD   = 0, /* VCDIFF header */
488   DEC_HDRIND   = 1, /* header indicator */
489
490   DEC_SECONDID = 2, /* secondary compressor ID */
491
492   DEC_TABLEN   = 3, /* code table length */
493   DEC_NEAR     = 4, /* code table near */
494   DEC_SAME     = 5, /* code table same */
495   DEC_TABDAT   = 6, /* code table data */
496
497   DEC_APPLEN   = 7, /* application data length */
498   DEC_APPDAT   = 8, /* application data */
499
500   DEC_WININD   = 9, /* window indicator */
501
502   DEC_CPYLEN   = 10, /* copy window length */
503   DEC_CPYOFF   = 11, /* copy window offset */
504
505   DEC_ENCLEN   = 12, /* length of delta encoding */
506   DEC_TGTLEN   = 13, /* length of target window */
507   DEC_DELIND   = 14, /* delta indicator */
508
509   DEC_DATALEN  = 15, /* length of ADD+RUN data */
510   DEC_INSTLEN  = 16, /* length of instruction data */
511   DEC_ADDRLEN  = 17, /* length of address data */
512
513   DEC_CKSUM    = 18, /* window checksum */
514
515   DEC_DATA     = 19, /* data section */
516   DEC_INST     = 20, /* instruction section */
517   DEC_ADDR     = 21, /* address section */
518
519   DEC_EMIT     = 22, /* producing data */
520
521   DEC_FINISH   = 23, /* window finished */
522
523   DEC_ABORTED  = 24, /* xd3_abort_stream */
524 } xd3_decode_state;
525
526 /************************************************************
527  internal types
528  ************************************************************/
529
530 /* instruction lists used in the IOPT buffer */
531 struct _xd3_rlist
532 {
533   xd3_rlist  *next;
534   xd3_rlist  *prev;
535 };
536
537 /* the raw encoding of an instruction used in the IOPT buffer */
538 struct _xd3_rinst
539 {
540   uint8_t     type;
541   uint8_t     xtra;
542   uint8_t     code1;
543   uint8_t     code2;
544   usize_t      pos;
545   usize_t      size;
546   xoff_t      addr;
547   xd3_rlist   link;
548 };
549
550 /* the code-table form of an single- or double-instruction */
551 struct _xd3_dinst
552 {
553   uint8_t     type1;
554   uint8_t     size1;
555   uint8_t     type2;
556   uint8_t     size2;
557 };
558
559 /* the decoded form of a single (half) instruction. */
560 struct _xd3_hinst
561 {
562   uint8_t     type;
563   uint32_t    size;  /* TODO: why decode breaks if this is usize_t? */
564   uint32_t    addr;  /* TODO: why decode breaks if this is usize_t? */
565 };
566
567 /* the form of a whole-file instruction */
568 struct _xd3_winst
569 {
570   uint8_t type;  /* RUN, ADD, COPY */
571   uint8_t mode;  /* 0, VCD_SOURCE, VCD_TARGET */
572   usize_t size;
573   xoff_t  addr;
574   xoff_t  position;  /* absolute position of this inst */
575 };
576
577 /* used by the encoder to buffer output in sections.  list of blocks. */
578 struct _xd3_output
579 {
580   uint8_t    *base;
581   usize_t     next;
582   usize_t     avail;
583   xd3_output *next_page;
584 };
585
586 /* used by the decoder to buffer input in sections. */
587 struct _xd3_desect
588 {
589   const uint8_t *buf;
590   const uint8_t *buf_max;
591   uint32_t       size;  /* TODO: why decode breaks if this is usize_t? */
592   usize_t        pos;
593
594   /* used in xdelta3-decode.h */
595   uint8_t       *copied1;
596   usize_t        alloc1;
597
598   /* used in xdelta3-second.h */
599   uint8_t       *copied2;
600   usize_t        alloc2;
601 };
602
603 /* the VCDIFF address cache, see the RFC */
604 struct _xd3_addr_cache
605 {
606   usize_t  s_near;
607   usize_t  s_same;
608   usize_t  next_slot;  /* the circular index for near */
609   usize_t *near_array; /* array of size s_near        */
610   usize_t *same_array; /* array of size s_same*256    */
611 };
612
613 /* the IOPT buffer list is just a list of buffers, which may be allocated
614  * during encode when using an unlimited buffer. */
615 struct _xd3_iopt_buflist
616 {
617   xd3_rinst *buffer;
618   xd3_iopt_buflist *next;
619 };
620
621 /* This is the record of a pre-compiled configuration, a subset of
622    xd3_config. */
623 struct _xd3_smatcher
624 {
625   const char        *name;
626   int             (*string_match) (xd3_stream  *stream);
627   usize_t            large_look;
628   usize_t            large_step;
629   usize_t            small_look;
630   usize_t            small_chain;
631   usize_t            small_lchain;
632   usize_t            max_lazy;
633   usize_t            long_enough;
634 };
635
636 /* hash table size & power-of-two hash function. */
637 struct _xd3_hash_cfg
638 {
639   usize_t           size;
640   usize_t           shift;
641   usize_t           mask;
642 };
643
644 /* the sprev list */
645 struct _xd3_slist
646 {
647   usize_t     last_pos;
648 };
649
650 /* window info (for whole state) */
651 struct _xd3_wininfo {
652   xoff_t offset;
653   usize_t length;
654   uint32_t adler32;
655 };
656
657 /* whole state for, e.g., merge */
658 struct _xd3_whole_state {
659   usize_t addslen;
660   uint8_t *adds;
661   usize_t  adds_alloc;
662
663   usize_t instlen;
664   xd3_winst *inst;
665   usize_t  inst_alloc;
666
667   usize_t wininfolen;
668   xd3_wininfo *wininfo;
669   usize_t wininfo_alloc;
670
671   xoff_t length;
672 };
673
674 /********************************************************************
675  public types
676  *******************************************************************/
677
678 /* Settings for the secondary compressor. */
679 struct _xd3_sec_cfg
680 {
681   int                data_type;     /* Which section. (set automatically) */
682   usize_t            ngroups;       /* Number of DJW Huffman groups. */
683   usize_t            sector_size;   /* Sector size. */
684   int                inefficient;   /* If true, ignore efficiency check [avoid XD3_NOSECOND]. */
685 };
686
687 /* This is the user-visible stream configuration. */
688 struct _xd3_config
689 {
690   usize_t             winsize;       /* The encoder window size. */
691   usize_t             sprevsz;       /* How far back small string
692                                         matching goes */
693   usize_t             iopt_size;     /* entries in the
694                                         instruction-optimizing
695                                         buffer */
696   usize_t             srcwin_maxsz;  /* srcwin_size grows by a factor
697                                         of 2 when no matches are
698                                         found.  encoder will not seek
699                                         back further than this. */
700
701   xd3_getblk_func   *getblk;        /* The three callbacks. */
702   xd3_alloc_func    *alloc;
703   xd3_free_func     *freef;
704   void              *opaque;        /* Not used. */
705   int                flags;         /* stream->flags are initialized
706                                      * from xd3_config & never
707                                      * modified by the library.  Use
708                                      * xd3_set_flags to modify flags
709                                      * settings mid-stream. */
710
711   xd3_sec_cfg       sec_data;       /* Secondary compressor config: data */
712   xd3_sec_cfg       sec_inst;       /* Secondary compressor config: inst */
713   xd3_sec_cfg       sec_addr;       /* Secondary compressor config: addr */
714
715   xd3_smatch_cfg     smatch_cfg;    /* See enum: use fields below  for
716                                        soft config */
717   xd3_smatcher       smatcher_soft;
718 };
719
720 /* The primary source file object. You create one of these objects and
721  * initialize the first four fields.  This library maintains the next
722  * 5 fields.  The configured getblk implementation is responsible for
723  * setting the final 3 fields when called (and/or when XD3_GETSRCBLK
724  * is returned).
725  */
726 struct _xd3_source
727 {
728   /* you set */
729   usize_t             blksize;       /* block size */
730   const char         *name;          /* its name, for debug/print
731                                         purposes */
732   void               *ioh;           /* opaque handle */
733
734   /* getblk sets */
735   xoff_t              curblkno;      /* current block number: client
736                                         sets after getblk request */
737   usize_t             onblk;         /* number of bytes on current
738                                         block: client sets,  must be >= 0
739                                         and <= blksize */
740   const uint8_t      *curblk;        /* current block array: client
741                                         sets after getblk request */
742
743   /* xd3 sets */
744   usize_t             srclen;        /* length of this source window */
745   xoff_t              srcbase;       /* offset of this source window
746                                         in the source itself */
747   int                 shiftby;       /* for power-of-two blocksizes */
748   int                 maskby;        /* for power-of-two blocksizes */
749   xoff_t              cpyoff_blocks; /* offset of dec_cpyoff in blocks */
750   usize_t             cpyoff_blkoff; /* offset of copy window in
751                                         blocks, remainder */
752   xoff_t              getblkno;      /* request block number: xd3 sets
753                                         current getblk request */
754
755   /* See xd3_getblk() */
756   xoff_t              max_blkno;  /* Maximum block, if eof is known,
757                                    * otherwise, equals frontier_blkno
758                                    * (initially 0). */
759   xoff_t              frontier_blkno;  /* If eof is unknown, the next
760                                         * source position to be read.
761                                         * Otherwise, equal to
762                                         * max_blkno. */
763   usize_t             onlastblk;  /* Number of bytes on max_blkno */
764   int                 eof_known;  /* Set to true when the first
765                                    * partial block is read. */
766 };
767
768 /* The primary xd3_stream object, used for encoding and decoding.  You
769  * may access only two fields: avail_out, next_out.  Use the methods
770  * above to operate on xd3_stream. */
771 struct _xd3_stream
772 {
773   /* input state */
774   const uint8_t    *next_in;          /* next input byte */
775   usize_t           avail_in;         /* number of bytes available at
776                                          next_in */
777   xoff_t            total_in;         /* how many bytes in */
778
779   /* output state */
780   uint8_t          *next_out;         /* next output byte */
781   usize_t           avail_out;        /* number of bytes available at
782                                          next_out */
783   usize_t           space_out;        /* total out space */
784   xoff_t            current_window;   /* number of windows encoded/decoded */
785   xoff_t            total_out;        /* how many bytes out */
786
787   /* to indicate an error, xd3 sets */
788   const char       *msg;              /* last error message, NULL if
789                                          no error */
790
791   /* source configuration */
792   xd3_source       *src;              /* source array */
793
794   /* encoder memory configuration */
795   usize_t           winsize;          /* suggested window size */
796   usize_t           sprevsz;          /* small string, previous window
797                                          size (power of 2) */
798   usize_t           sprevmask;        /* small string, previous window
799                                          size mask */
800   usize_t           iopt_size;
801   usize_t           iopt_unlimited;
802   usize_t           srcwin_maxsz;
803
804   /* general configuration */
805   xd3_getblk_func  *getblk;           /* set nxtblk, nxtblkno to scanblkno */
806   xd3_alloc_func   *alloc;            /* malloc function */
807   xd3_free_func    *free;             /* free function */
808   void*             opaque;           /* private data object passed to
809                                          alloc, free, and getblk */
810   int               flags;            /* various options */
811
812   /* secondary compressor configuration */
813   xd3_sec_cfg       sec_data;         /* Secondary compressor config: data */
814   xd3_sec_cfg       sec_inst;         /* Secondary compressor config: inst */
815   xd3_sec_cfg       sec_addr;         /* Secondary compressor config: addr */
816
817   xd3_smatcher      smatcher;
818
819   usize_t           *large_table;      /* table of large checksums */
820   xd3_hash_cfg       large_hash;       /* large hash config */
821
822   usize_t           *small_table;      /* table of small checksums */
823   xd3_slist         *small_prev;       /* table of previous offsets,
824                                           circular linked list */
825   int                small_reset;      /* true if small table should
826                                           be reset */
827
828   xd3_hash_cfg       small_hash;       /* small hash config */
829   xd3_addr_cache     acache;           /* the vcdiff address cache */
830   xd3_encode_state   enc_state;        /* state of the encoder */
831
832   usize_t            taroff;           /* base offset of the target input */
833   usize_t            input_position;   /* current input position */
834   usize_t            min_match;        /* current minimum match
835                                           length, avoids redundent
836                                           matches */
837   usize_t            unencoded_offset; /* current input, first
838                                        * unencoded offset. this value
839                                        * is <= the first instruction's
840                                        * position in the iopt buffer,
841                                        * if there is at least one
842                                        * match in the buffer. */
843
844   // SRCWIN
845   // these variables plus srcwin_maxsz above (set by config)
846   int                srcwin_decided;    /* boolean: true if srclen and
847                                            srcbase have been
848                                            decided. */
849   int                srcwin_decided_early;  /* boolean: true if srclen
850                                                and srcbase were
851                                                decided early. */
852   xoff_t             srcwin_cksum_pos;  /* Source checksum position */
853
854   // MATCH
855   xd3_match_state    match_state;      /* encoder match state */
856   xoff_t             match_srcpos;     /* current match source
857                                           position relative to
858                                           srcbase */
859   xoff_t             match_last_srcpos;  /* previously attempted
860                                           * srcpos, to avoid loops. */
861   xoff_t             match_minaddr;    /* smallest matching address to
862                                        * set window params (reset each
863                                        * window xd3_encode_reset) */
864   xoff_t             match_maxaddr;    /* largest matching address to
865                                        * set window params (reset each
866                                        * window xd3_encode_reset) */
867   usize_t            match_back;       /* match extends back so far */
868   usize_t            match_maxback;    /* match extends back maximum */
869   usize_t            match_fwd;        /* match extends forward so far */
870   usize_t            match_maxfwd;     /* match extends forward maximum */
871
872   xoff_t             maxsrcaddr;      /* address of the last source
873                                          match (across windows) */
874
875   uint8_t          *buf_in;           /* for saving buffered input */
876   usize_t           buf_avail;        /* amount of saved input */
877   const uint8_t    *buf_leftover;     /* leftover content of next_in
878                                          (i.e., user's buffer) */
879   usize_t            buf_leftavail;    /* amount of leftover content */
880
881   xd3_output       *enc_current;      /* current output buffer */
882   xd3_output       *enc_free;         /* free output buffers */
883   xd3_output       *enc_heads[4];     /* array of encoded outputs:
884                                          head of chain */
885   xd3_output       *enc_tails[4];     /* array of encoded outputs:
886                                          tail of chain */
887   uint32_t          recode_adler32;   /* set the adler32 checksum
888                                        * during "recode". */
889
890   xd3_rlist         iopt_used;        /* instruction optimizing buffer */
891   xd3_rlist         iopt_free;
892   xd3_rinst        *iout;             /* next single instruction */
893   xd3_iopt_buflist *iopt_alloc;
894
895   const uint8_t    *enc_appheader;    /* application header to encode */
896   usize_t            enc_appheadsz;    /* application header size */
897
898   /* decoder stuff */
899   xd3_decode_state  dec_state;        /* current DEC_XXX value */
900   usize_t           dec_hdr_ind;      /* VCDIFF header indicator */
901   usize_t           dec_win_ind;      /* VCDIFF window indicator */
902   usize_t           dec_del_ind;      /* VCDIFF delta indicator */
903
904   uint8_t           dec_magic[4];     /* First four bytes */
905   usize_t           dec_magicbytes;   /* Magic position. */
906
907   usize_t           dec_secondid;     /* Optional secondary compressor ID. */
908
909   /* TODO: why decode breaks if this is usize_t? */
910   uint32_t          dec_codetblsz;    /* Optional code table: length. */
911   uint8_t          *dec_codetbl;      /* Optional code table: storage. */
912   usize_t           dec_codetblbytes; /* Optional code table: position. */
913
914   /* TODO: why decode breaks if this is usize_t? */
915   uint32_t          dec_appheadsz;    /* Optional application header:
916                                          size. */
917   uint8_t          *dec_appheader;    /* Optional application header:
918                                          storage */
919   usize_t           dec_appheadbytes; /* Optional application header:
920                                          position. */
921
922   usize_t            dec_cksumbytes;   /* Optional checksum: position. */
923   uint8_t           dec_cksum[4];     /* Optional checksum: storage. */
924   uint32_t          dec_adler32;      /* Optional checksum: value. */
925
926   /* TODO: why decode breaks if this is usize_t? */
927   uint32_t           dec_cpylen;       /* length of copy window
928                                           (VCD_SOURCE or VCD_TARGET) */
929   xoff_t             dec_cpyoff;       /* offset of copy window
930                                           (VCD_SOURCE or VCD_TARGET) */
931   /* TODO: why decode breaks if this is usize_t? */
932   uint32_t           dec_enclen;       /* length of delta encoding */
933   /* TODO: why decode breaks if this is usize_t? */
934   uint32_t           dec_tgtlen;       /* length of target window */
935
936 #if USE_UINT64
937   uint64_t          dec_64part;       /* part of a decoded uint64_t */
938 #endif
939 #if USE_UINT32
940   uint32_t          dec_32part;       /* part of a decoded uint32_t */
941 #endif
942
943   xoff_t            dec_winstart;     /* offset of the start of
944                                          current target window */
945   xoff_t            dec_window_count; /* == current_window + 1 in
946                                          DEC_FINISH */
947   usize_t            dec_winbytes;     /* bytes of the three sections
948                                           so far consumed */
949   usize_t            dec_hdrsize;      /* VCDIFF + app header size */
950
951   const uint8_t    *dec_tgtaddrbase;  /* Base of decoded target
952                                          addresses (addr >=
953                                          dec_cpylen). */
954   const uint8_t    *dec_cpyaddrbase;  /* Base of decoded copy
955                                          addresses (addr <
956                                          dec_cpylen). */
957
958   usize_t            dec_position;     /* current decoder position
959                                           counting the cpylen
960                                           offset */
961   usize_t            dec_maxpos;       /* maximum decoder position
962                                           counting the cpylen
963                                           offset */
964   xd3_hinst         dec_current1;     /* current instruction */
965   xd3_hinst         dec_current2;     /* current instruction */
966
967   uint8_t          *dec_buffer;       /* Decode buffer */
968   uint8_t          *dec_lastwin;      /* In case of VCD_TARGET, the
969                                          last target window. */
970   usize_t            dec_lastlen;      /* length of the last target
971                                           window */
972   xoff_t            dec_laststart;    /* offset of the start of last
973                                          target window */
974   usize_t            dec_lastspace;    /* allocated space of last
975                                           target window, for reuse */
976
977   xd3_desect        inst_sect;        /* staging area for decoding
978                                          window sections */
979   xd3_desect        addr_sect;
980   xd3_desect        data_sect;
981
982   xd3_code_table_func       *code_table_func;
983   xd3_comp_table_func       *comp_table_func;
984   const xd3_dinst           *code_table;
985   const xd3_code_table_desc *code_table_desc;
986   xd3_dinst                 *code_table_alloc;
987
988   /* secondary compression */
989   const xd3_sec_type *sec_type;
990   xd3_sec_stream     *sec_stream_d;
991   xd3_sec_stream     *sec_stream_i;
992   xd3_sec_stream     *sec_stream_a;
993
994   /* state for reconstructing whole files (e.g., for merge), this only
995    * supports loading USIZE_T_MAX instructions, adds, etc. */
996   xd3_whole_state     whole_target;
997
998   /* statistics */
999   xoff_t            n_scpy;
1000   xoff_t            n_tcpy;
1001   xoff_t            n_add;
1002   xoff_t            n_run;
1003
1004   xoff_t            l_scpy;
1005   xoff_t            l_tcpy;
1006   xoff_t            l_add;
1007   xoff_t            l_run;
1008
1009   usize_t           i_slots_used;
1010
1011 #if XD3_DEBUG
1012   usize_t            large_ckcnt;
1013
1014   /* memory usage */
1015   usize_t            alloc_cnt;
1016   usize_t            free_cnt;
1017 #endif
1018 };
1019
1020 /**************************************************************************
1021  PUBLIC FUNCTIONS
1022  **************************************************************************/
1023
1024 /* This function configures an xd3_stream using the provided in-memory
1025  * input buffer, source buffer, output buffer, and flags.  The output
1026  * array must be large enough or else ENOSPC will be returned.  This
1027  * is the simplest in-memory encoding interface. */
1028 int     xd3_encode_memory (const uint8_t *input,
1029                            usize_t        input_size,
1030                            const uint8_t *source,
1031                            usize_t        source_size,
1032                            uint8_t       *output_buffer,
1033                            usize_t       *output_size,
1034                            usize_t        avail_output,
1035                            int            flags);
1036
1037 /* The reverse of xd3_encode_memory. */
1038 int     xd3_decode_memory (const uint8_t *input,
1039                            usize_t        input_size,
1040                            const uint8_t *source,
1041                            usize_t        source_size,
1042                            uint8_t       *output_buf,
1043                            usize_t       *output_size,
1044                            usize_t        avail_output,
1045                            int            flags);
1046
1047 /* This function encodes an in-memory input using a pre-configured
1048  * xd3_stream.  This allows the caller to set a variety of options
1049  * which are not available in the xd3_encode/decode_memory()
1050  * functions.
1051  *
1052  * The output array must be large enough to hold the output or else
1053  * ENOSPC is returned.  The source (if any) should be set using
1054  * xd3_set_source_and_size() with a single-block xd3_source.  This
1055  * calls the underlying non-blocking interfaces,
1056  * xd3_encode/decode_input(), handling the necessary input/output
1057  * states.  This method may be considered a reference for any
1058  * application using xd3_encode_input() directly.
1059  *
1060  *   xd3_stream stream;
1061  *   xd3_config config;
1062  *   xd3_source src;
1063  *
1064  *   memset (& src, 0, sizeof (src));
1065  *   memset (& stream, 0, sizeof (stream));
1066  *   memset (& config, 0, sizeof (config));
1067  *
1068  *   if (source != NULL)
1069  *     {
1070  *       src.size = source_size;
1071  *       src.blksize = source_size;
1072  *       src.curblkno = 0;
1073  *       src.onblk = source_size;
1074  *       src.curblk = source;
1075  *       xd3_set_source(&stream, &src);
1076  *     }
1077  *
1078  *   config.flags = flags;
1079  *   config.srcwin_maxsz = source_size;
1080  *   config.winsize = input_size;
1081  *
1082  *   ... set smatcher, appheader, encoding-table, compression-level, etc.
1083  *
1084  *   xd3_config_stream(&stream, &config);
1085  *   xd3_encode_stream(&stream, ...);
1086  *   xd3_free_stream(&stream);
1087  */
1088 int     xd3_encode_stream (xd3_stream    *stream,
1089                            const uint8_t *input,
1090                            usize_t         input_size,
1091                            uint8_t       *output,
1092                            usize_t        *output_size,
1093                            usize_t         avail_output);
1094
1095 /* The reverse of xd3_encode_stream. */
1096 int     xd3_decode_stream (xd3_stream    *stream,
1097                            const uint8_t *input,
1098                            usize_t        input_size,
1099                            uint8_t       *output,
1100                            usize_t       *output_size,
1101                            usize_t        avail_size);
1102
1103 /* This is the non-blocking interface.
1104  *
1105  * Handling input and output states is the same for encoding or
1106  * decoding using the xd3_avail_input() and xd3_consume_output()
1107  * routines, inlined below.
1108  *
1109  * Return values:
1110  *
1111  *   XD3_INPUT: the process requires more input: call
1112  *               xd3_avail_input() then repeat
1113  *
1114  *   XD3_OUTPUT: the process has more output: read stream->next_out,
1115  *               stream->avail_out, then call xd3_consume_output(),
1116  *               then repeat
1117  *
1118  *   XD3_GOTHEADER: (decoder-only) notification returned following the
1119  *               VCDIFF header and first window header.  the decoder
1120  *               may use the header to configure itself.
1121  *
1122  *   XD3_WINSTART: a general notification returned once for each
1123  *               window except the 0-th window, which is implied by
1124  *               XD3_GOTHEADER.  It is recommended to use a
1125  *               switch-stmt such as:
1126  *
1127  *                 ...
1128  *               again:
1129  *                 switch ((ret = xd3_decode_input (stream))) {
1130  *                    case XD3_GOTHEADER: {
1131  *                      assert(stream->current_window == 0);
1132  *                      stuff;
1133  *                    }
1134  *                    // fallthrough
1135  *                    case XD3_WINSTART: {
1136  *                      something(stream->current_window);
1137  *                      goto again;
1138  *                    }
1139  *                    ...
1140  *
1141  *   XD3_WINFINISH: a general notification, following the complete
1142  *               input & output of a window.  at this point,
1143  *               stream->total_in and stream->total_out are consistent
1144  *               for either encoding or decoding.
1145  *
1146  *   XD3_GETSRCBLK: If the xd3_getblk() callback is NULL, this value
1147  *               is returned to initiate a non-blocking source read.
1148  */
1149 int     xd3_decode_input  (xd3_stream    *stream);
1150 int     xd3_encode_input  (xd3_stream    *stream);
1151
1152 /* The xd3_config structure is used to initialize a stream - all data
1153  * is copied into stream so config may be a temporary variable.  See
1154  * the [documentation] or comments on the xd3_config structure. */
1155 int     xd3_config_stream (xd3_stream    *stream,
1156                            xd3_config    *config);
1157
1158 /* Since Xdelta3 doesn't open any files, xd3_close_stream is just an
1159  * error check that the stream is in a proper state to be closed: this
1160  * means the encoder is flushed and the decoder is at a window
1161  * boundary.  The application is responsible for freeing any of the
1162  * resources it supplied. */
1163 int     xd3_close_stream (xd3_stream    *stream);
1164
1165 /* This arranges for closes the stream to succeed.  Does not free the
1166  * stream.*/
1167 void    xd3_abort_stream (xd3_stream    *stream);
1168
1169 /* xd3_free_stream frees all memory allocated for the stream.  The
1170  * application is responsible for freeing any of the resources it
1171  * supplied. */
1172 void    xd3_free_stream   (xd3_stream    *stream);
1173
1174 /* This function informs the encoder or decoder that source matching
1175  * (i.e., delta-compression) is possible.  For encoding, this should
1176  * be called before the first xd3_encode_input.  A NULL source is
1177  * ignored.  For decoding, this should be called before the first
1178  * window is decoded, but the appheader may be read first
1179  * (XD3_GOTHEADER).  After decoding the header, call xd3_set_source()
1180  * if you have a source file.  Note: if (stream->dec_win_ind & VCD_SOURCE)
1181  * is true, it means the first window expects there to be a source file.
1182  */
1183 int     xd3_set_source    (xd3_stream    *stream,
1184                            xd3_source    *source);
1185
1186 /* If the source size is known, call this instead of xd3_set_source().
1187  * to avoid having stream->getblk called (and/or to avoid XD3_GETSRCBLK).
1188  *
1189  * Follow these steps:
1190   xd3_source source;
1191   memset(&source, 0, sizeof(source));
1192   source.blksize  = size;
1193   source.onblk    = size;
1194   source.curblk   = buf;
1195   source.curblkno = 0;
1196   int ret = xd3_set_source_and_size(&stream, &source, size);
1197   ...
1198  */
1199 int     xd3_set_source_and_size (xd3_stream    *stream,
1200                                  xd3_source    *source,
1201                                  xoff_t         source_size);
1202
1203 /* This should be called before the first call to xd3_encode_input()
1204  * to include application-specific data in the VCDIFF header. */
1205 void    xd3_set_appheader (xd3_stream    *stream,
1206                            const uint8_t *data,
1207                            usize_t        size);
1208
1209 /* xd3_get_appheader may be called in the decoder after XD3_GOTHEADER.
1210  * For convenience, the decoder always adds a single byte padding to
1211  * the end of the application header, which is set to zero in case the
1212  * application header is a string. */
1213 int     xd3_get_appheader (xd3_stream     *stream,
1214                            uint8_t       **data,
1215                            usize_t        *size);
1216
1217 /* To generate a VCDIFF encoded delta with xd3_encode_init() from
1218  * another format, use:
1219  *
1220  *   xd3_encode_init_partial() -- initialze encoder state (w/o hash tables)
1221  *   xd3_init_cache() -- reset VCDIFF address cache
1222  *   xd3_found_match() -- to report a copy instruction
1223  *
1224  * set stream->enc_state to ENC_INSTR and call xd3_encode_input as usual.
1225  */
1226 int xd3_encode_init_partial (xd3_stream *stream);
1227 void xd3_init_cache (xd3_addr_cache* acache);
1228 int xd3_found_match (xd3_stream *stream,
1229                      usize_t pos, usize_t size,
1230                      xoff_t addr, int is_source);
1231
1232 /* Gives an error string for xdelta3-speficic errors, returns NULL for
1233    system errors */
1234 const char* xd3_strerror (int ret);
1235
1236 /* For convenience, zero & initialize the xd3_config structure with
1237    specified flags. */
1238 static inline
1239 void    xd3_init_config (xd3_config *config,
1240                          int         flags)
1241 {
1242   memset (config, 0, sizeof (*config));
1243   config->flags = flags;
1244 }
1245
1246 /* This supplies some input to the stream.
1247  *
1248  * For encoding, if the input is larger than the configured window
1249  * size (xd3_config.winsize), the entire input will be consumed and
1250  * encoded anyway.  If you wish to strictly limit the window size,
1251  * limit the buffer passed to xd3_avail_input to the window size.
1252  *
1253  * For encoding, if the input is smaller than the configured window
1254  * size (xd3_config.winsize), the library will create a window-sized
1255  * buffer and accumulate input until a full-sized window can be
1256  * encoded.  XD3_INPUT will be returned.  The input must remain valid
1257  * until the next time xd3_encode_input() returns XD3_INPUT.
1258  *
1259  * For decoding, the input will be consumed entirely before XD3_INPUT
1260  * is returned again.
1261  */
1262 static inline
1263 void    xd3_avail_input  (xd3_stream    *stream,
1264                           const uint8_t *idata,
1265                           usize_t         isize)
1266 {
1267   /* Even if isize is zero, the code expects a non-NULL idata.  Why?
1268    * It uses this value to determine whether xd3_avail_input has ever
1269    * been called.  If xd3_encode_input is called before
1270    * xd3_avail_input it will return XD3_INPUT right away without
1271    * allocating a stream->winsize buffer.  This is to avoid an
1272    * unwanted allocation. */
1273   XD3_ASSERT (idata != NULL || isize == 0);
1274
1275   stream->next_in  = idata;
1276   stream->avail_in = isize;
1277 }
1278
1279 /* This acknowledges receipt of output data, must be called after any
1280  * XD3_OUTPUT return. */
1281 static inline
1282 void xd3_consume_output (xd3_stream  *stream)
1283 {
1284   stream->avail_out  = 0;
1285 }
1286
1287 /* These are set for each XD3_WINFINISH return. */
1288 static inline
1289 int xd3_encoder_used_source (xd3_stream *stream) {
1290   return stream->src != NULL && stream->src->srclen > 0;
1291 }
1292 static inline
1293 xoff_t xd3_encoder_srcbase (xd3_stream *stream) {
1294   return stream->src->srcbase;
1295 }
1296 static inline
1297 usize_t xd3_encoder_srclen (xd3_stream *stream) {
1298   return stream->src->srclen;
1299 }
1300
1301 /* Checks for legal flag changes. */
1302 static inline
1303 void xd3_set_flags (xd3_stream *stream, int flags)
1304 {
1305   /* The bitwise difference should contain only XD3_FLUSH or
1306      XD3_SKIP_WINDOW */
1307   XD3_ASSERT(((flags ^ stream->flags) & ~(XD3_FLUSH | XD3_SKIP_WINDOW)) == 0);
1308   stream->flags = flags;
1309 }
1310
1311 /* Gives some extra information about the latest library error, if any
1312  * is known. */
1313 static inline
1314 const char* xd3_errstring (xd3_stream  *stream)
1315 {
1316   return stream->msg ? stream->msg : "";
1317 }
1318
1319
1320 /* 64-bit divisions are expensive, which is why we require a
1321  * power-of-two source->blksize.  To relax this restriction is
1322  * relatively easy, see the history for xd3_blksize_div(). */
1323 static inline
1324 void xd3_blksize_div (const xoff_t offset,
1325                       const xd3_source *source,
1326                       xoff_t *blkno,
1327                       usize_t *blkoff) {
1328   *blkno = (xoff_t) (offset >> source->shiftby);
1329   *blkoff = (usize_t) (offset & source->maskby);
1330   XD3_ASSERT (*blkoff < source->blksize);
1331 }
1332
1333 static inline
1334 void xd3_blksize_add (xoff_t *blkno,
1335                       usize_t *blkoff,
1336                       const xd3_source *source,
1337                       const usize_t add)
1338 {
1339   usize_t blkdiff;
1340
1341   /* Does not check for overflow, checked in xdelta3-decode.h. */
1342   *blkoff += add;
1343   blkdiff = *blkoff >> source->shiftby;
1344
1345   if (blkdiff)
1346     {
1347       *blkno += blkdiff;
1348       *blkoff &= source->maskby;
1349     }
1350
1351   XD3_ASSERT (*blkoff < source->blksize);
1352 }
1353
1354 #define XD3_NOOP 0U
1355 #define XD3_ADD 1U
1356 #define  XD3_RUN 2U
1357 #define  XD3_CPY 3U /* XD3_CPY rtypes are represented as (XD3_CPY +
1358                      * copy-mode value) */
1359
1360 #if XD3_DEBUG
1361 #define IF_DEBUG(x) x
1362 #else
1363 #define IF_DEBUG(x)
1364 #endif
1365 #if XD3_DEBUG > 1
1366 #define IF_DEBUG1(x) x
1367 #else
1368 #define IF_DEBUG1(x)
1369 #endif
1370 #if XD3_DEBUG > 2
1371 #define IF_DEBUG2(x) x
1372 #else
1373 #define IF_DEBUG2(x)
1374 #endif
1375
1376 #define SIZEOF_ARRAY(x) (sizeof(x) / sizeof(x[0]))
1377
1378 #endif /* _XDELTA3_H_ */