code:
// Conversion betweeen different charmaps.

// github.com/michael105/slterm
// miSc Mychael Myer, 23, BSD 3clause
//
// Don't blame me for erratic conversions.
//
// There are some flaws - BOM conversion, e.g.
// I wouldn't recommend using this code in security relevant contexts;
// e.g. the missing BOM conversion could get into a remote execution with a websever.
// (Very extrapolated worst case)
//
// local conversion might be safe, however,
// especially for using this hack as an input filter.
// That's why I wrote this.
// Yet I didn't need BOM characters, I write with latex.
//
// The codepage "guessing" might work only for German, it looks
// for umlauts.
// If you'd need other languages, you would have to add the typical (extended ascii) characters
// below to the constant charmap cp.
//

// uncomment, to abort at (some) invalid UTF8 characters.
// (They might still be filtered out)
#define UTF8_STRICT

// Buffer sizes
#define BUF 64000
#define OBUF (BUF*2)

// memory used for the precomputed cache of the unicode translation table (in Bytes)
// (Mostly) All unicode chars defined per default are below 0x2600
#define UNITABLE 0x2800

typedef char Arg;
typedef unsigned int uint;
typedef unsigned char uchar;

#include "../src/charmaps.h"

typedef struct {
	const unsigned short *map;
	const char esign; // used for unconvertible chars
	const char *name;
	const unsigned char *chars;
} charmap;

#define MAP(name,esign,chars) { name, 0x##esign, #name, (unsigned char*) chars }

static const short unsigned int utf8[128]; // empty

// chars, which are likely to be in literal texts.
// It would be helpful using a dictionary.
// But this works out as well, for my needs.
//
// Try to guess by the used characters.
// This eventually works best with german and english literal texts,
// I only added few mathematical and special other chars
// ( (C),  +-, quotation marks, Euro, ..)
// For recognition of other languages,
// the typically used characters (and cp's) would need to be added below.
const charmap cp[] = {
	MAP( cpe4002a,a8, "\x81\x84\x8e\x94\x9a\x99" // umlaute
	                  "\xe1\xe3\xe4\x9b\x9c\xe6" ),
	MAP( cp850,  a8,  "\x81\x84\x8e\x94\x9a\x99" // umlaute
   	               "\xe1\x9c\xe6\xf4\xf5\xf8\xb8" ),
	MAP( cp437,  a8,  "\x81\x84\x8e\x94\x9a\x99" // umlaute
	                  "\xe1\xe3\xe4\x9b\x9c\xe6" ),
	MAP( cp1252, b6,  "\xe4\xf6\xfc\xdc\xd5\xc4" // "������" // Umlauts
                     "\x80\xb6\xa7\x93\x94\xa9"
                     "\xf7\xa9\xb0\xb1\xd7\xb5\xae" ),
	MAP( cp1250, b6, "" ),
	MAP( cp1251, b6, "" ),
	MAP( cp1253, b6, "" ),
	MAP( cp1255, b6, "" ),
	MAP( cp1256, b6, "" ),
	MAP( cp1257, b6, "" ),
	MAP( cp1258, b6, "" ),
	MAP( atarist, b6, "" ),
	MAP( macintosh, b6, "" ),
	MAP( mac_centraleurope, b6, "" ),
	MAP( iso8859_15, b6, "" ),

	MAP(utf8,7e,""),
	{0,0,0,0},
};

// The default target encoding
#define DEFAULT_CP 0

#define UTF8 (sizeof(cp)/sizeof(charmap)-2)

#define NUMCP (sizeof(cp)/sizeof(charmap)-1)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define W(msg) write(2,msg,sizeof(msg))

int opts;
// verbose
#define V(msg) ({ if ( opts&1 ) W(msg); 1; })
#define v(...) { if ( opts&1 ) fprintf(stderr,__VA_ARGS__); }
// silent
#define E(msg) { if ( !(opts&2) ) W(msg); }
#define e(...) { if ( !(opts&2) ) fprintf(stderr,__VA_ARGS__); }

void usage(){
	W("convert stdin to stdout\n"
			"Usage: convert [-hs] [tocp] [fromcp]\n\n"
			"Example: cat text.txt | convert cp1252 cp850\n"
			"        (convert from cp850 to cp1252)\n"
			"         cat text.txt | convert cp1252\n"
			"        (convert to cp1252, guessing source charset\n\n"
			"Whithout any options, try to guess the charset and convert to ");
   write(2,cp[DEFAULT_CP].name,strlen(cp[DEFAULT_CP].name));
	W(		"\n(change the default in the source, if needed)\n\n"
			"options: -s : silence, no messages to stderr\n"
			"         -l : list codepages\n"
			"         -x : display non convertible chars in hexadecimal\n"
			"\n"
			"(I'm using this as input filter for vi - just filter every text file,\n"
			" the conversion is done automatically, if needed..)\n"
			"\nmiSc 23, BSD 3clause\n"
			);
	exit(1);
}

// according to rfc 3629, this values are not valid
int valid_uc_utf8(uint unicode){
	if ( (unicode>0xd800)&&(unicode<0xdfff) ){
#ifdef UTF8_STRICT
		e("invalid utf8 conversion: %x\n",unicode);
		exit(1);
#endif
		return(0);
	}
	return(1);
}

int guess_charmap(const unsigned char *buf, int len){
	int guess[NUMCP];
	memset(guess,0,NUMCP*sizeof(int));
	int n = 0; // ascii 32-127
	int so=0; // chars, extended ascii ( 128-192 )
	int co = 0; // control chars.
	int ext = 0; // chars 128-255

	int a = 0;
	while ( a<len ){
		switch (buf[a]) {
			case 0 ... 31:
				co++;
				break;
			case 128 ... 255:

				ext++;
				//printf("c: %d\n",buf[a]);
				for ( int b = 0; b<NUMCP-1; b++ ){
					//printf("BBB\n");
					for ( const unsigned char *c = cp[b].chars; *c; c++ ){
						//printf("b: %d c: %d\n",b,*c);
						if ( *c == buf[a] ){
							guess[b] = guess[b] + 1;
							//printf("guess, b: %d = %d\n",b,guess[b]);
							break;
						}
					}
				}

				if ( buf[a] < 192 ){ // 128-192 = no utf8
					so++;
					//utf -= 4; // I'm uncertain about mixed encodings
				} else { // coul'd be  utf8
					if ( (buf[a] & 0xe0) == 0xc0 ){ // initial Byte 2Byte utf8
						if ( (a+1<len) && ( (buf[a+1] & 0xc0) == 0x80 ) ){
							guess[UTF8] ++;
							a++;
						}
					} else if ( (buf[a] & 0xf0) == 0xe0 ){ // 3byte
						if ( (a+2 < len ) && ( (buf[a+1] & 0xc0) == 0x80 ) &&
								( (buf[a+2] & 0xc0) == 0x80 )){
							guess[UTF8] += 2;
							a+=2;
						}
					} else if ( (buf[a] & 0xf8) == 0xf0 ){ //4byte
						if ( ( a+3<len ) && ( (buf[a+1] & 0xc0) == 0x80 ) &&
								( (buf[a+2] & 0xc0) == 0x80 ) &&
								( (buf[a+3] & 0xc0) == 0x80 ) ){
							guess[UTF8] += 3;
							a+=3;
						}
					}

				}

			break;

			default: // ascii char 32-127
				n++;
		}

		a++;
	}

	if ( !ext ){
		V("No extended Ascii/UTF present.\n");
		return(-1);
	}

	if ( n<len-len/4 ){
		V("This looks like binary data.\nContinuing anyways\n");
	}

	int max = 0;
	int guessed = -1;
	for ( int a = 0; a<NUMCP; a++ )
		if ( guess[a] > max ){
			max = guess[a];
			guessed = a;
		}

	v("Guess: %s\n(%d chars match)\n",cp[guessed].name,max);
	v("  chars: %d\n   utf8: %d\n   0-31: %d\n"
	  " 32-127: %d\n128-191: %d\n192-255: %d\n",len,guess[UTF8],co,n,so,ext);

	return(guessed);
}

void listcodepages(){
	W("Supported (extended ASCII) encodings:\n\n");
	for ( const charmap *cm = cp; cm->name != 0; cm++ )
		printf("%s\n",cm->name);

	exit(0);
}

int main(int argc, char **argv ){
	opts = 1; // verbose

	// parse options
	for ( *argv++; *argv && *argv[0] == '-'; *argv++ ){
		argc--;
		for ( char *o = *argv+1; *o; o++ ){
			switch (*o) {
				case 'l':
					listcodepages();
				case 's':
					opts|=2;
					opts&=0xfe; // reset bit verbose
					break;
				case 'u':
					opts|=4; // write utf8 for nonconvertible chars
					break;
				case 'x':
					opts|=8; // write hex unicode for nonconv. chars
				break;
				default: // -h, --help, ..
					usage();
			}
		}
	}
	argc--;

	unsigned char buf[BUF],obuf[OBUF];
	int len;
	int from = -1;
	int to = -1;

	// parse from and to codepage (if)
	while ( argc>0 ){
		from = to;
		 const charmap *c = cp;
		 while ( strcmp(c->name,argv[argc-1]) != 0 ){
			 c++;
			 if ( c->name == 0 ){
				 fprintf(stderr,"Unknown codepage: %s\n",argv[argc-1]);
				 exit(1);
			 }
		 }
		 to = c - cp;
		 argc--;
	}

	if ( to==-1 )
		to = DEFAULT_CP;

	// create reverse table
	unsigned char ocp[UNITABLE];
	memset( ocp, 0 , UNITABLE );
	for ( int a=0; a<128; a++ ){
		if ( cp[to].map[a] < UNITABLE )
			ocp[ cp[to].map[a] ] = a + 128;
	}

	len = read(0,buf,BUF);

	if ( from == -1 ){
		V("Guessing charset\n");
		from = guess_charmap(buf,len);
	}

	if ( (from == -1) || // no conversion possible, no extended ascii
			( (from==to) && ( V("Source and destination codepage are equal\n")) ) ){
		// write stdin to stdout (we are a filter)
		do{ write(1,buf,len); } while (( len=read(0,buf,BUF) ));
		exit(0);
	}

	v("Converting from %s to %s\n", cp[from].name,cp[to].name);

	do { // mainloop
		int p = 0;
		int a = 0;
		while ( a<len ){

			if ( buf[a] <128 )
				obuf[p++] = buf[a];
			else { // char > 127
				// get unicode point
				uint uc;
				// convert utf-8 to unicode
				if ( from == UTF8 ){
					if ( a+3>=len ){ // refill the buffer, before the conversion
						len -= a;
						memmove(buf,(buf+a),len);
						a = 0;
						int l = read(0,(buf+len),BUF-len);
						if ( l>0 )
							len += l;
					}

					int tmp = a;

					if ( (a+1<len) && ( (buf[a+1] & 0xc0) == 0x80 ) ){
						uc = ( (buf[a] & 0x1f) << 6 ) | (buf[a+1] & 0x3f);
						if ( (buf[a] & 0xe0) == 0xc0 ){ // initial Byte 2Byte utf8
							a++;
						} else if ( (a+2<len) && ( (buf[a+2] & 0xc0) == 0x80 ) ){
							uc = ( uc << 6 ) | (buf[a+2] & 0x3f);
							if ( (buf[a] & 0xf0) == 0xe0 ){ // initial Byte 3Byte utf8
								a+=2;
							} else if ( (a+3<len) && ( (buf[a+3] & 0xc0) == 0x80 ) ){
								if ( (buf[a] & 0xf8) == 0xf0 ){ // 4byte
									uc = ((uc<<6) & 0x1FFFFF ) | ( buf[a+3] & 0x3f );
									a+=3;
								}
							}
						}
					}
					/*
					char bits = 0xc0;
					uc = (buf[a] & 0x1f);
					for ( int b = 1; b<4; b++ ){
						if ( (a+b<len) && ( (buf[a+b] & 0xc0) == 0x80 ) ){
							uc = ( uc << 6 ) | (buf[a+b] & 0x3f);
							if ( bits == (buf[a] & (bits>>(char)1) ) ){ // initial Byte
								a+=b;
								if ( b==3 )
									uc &= 0x1fffff;
								break;
							}
							bits >>=(char)1;
						}
					}*/

					if ( (tmp == a) || !( valid_uc_utf8(uc) ) ){ // error. invalid utf8
						e("Invalid utf8 sequence: %02x%02x\n",buf[a],buf[a+1]);
						uc = buf[a]; // for "mixed" encodings (e.g. cp1252, and utf-8)
						// I'm a bit uncertain. In theory, the whole document's conversion
						// is "invalid". In practice - maybe, some umlauts fall through
						// I did say, John, you don't use umlauts for the calculation of the escape velocity.
						// Just don't do it. Well.
					}

				} else { // codepage table conversion to unicode
					uc = cp[from].map[buf[a]-128];
				}

				// convert unicode to the destination encoding
				int t=p;
				if ( to == UTF8 ){ // convert to utf8
					if ( !valid_uc_utf8(uc) )
						goto ERR_UTF8;
					// invalid values (rfc3629
					/* if ( uc < 2048 ){ // 2byte
						obuf[p++] = 0xc0 | ( uc >> 6 );
						obuf[p++] = ( uc & 0x3f ) | 0x80;
					} else if ( uc < 65536 ){ // 3byte
						obuf[p++] = 0xe0 | ( uc >> 12 );
						obuf[p++] = ( (uc >> 6 ) & 0x3f ) | 0x80;
						obuf[p++] = ( uc & 0x3f ) | 0x80;
					}else { // 4byte
						obuf[p++] = 0xf0 | ( uc >> 18 );
						obuf[p++] = ( (uc >> 12 ) & 0x3f ) | 0x80;
						obuf[p++] = ( (uc >> 6 ) & 0x3f ) | 0x80;
						obuf[p++] = ( uc & 0x3f ) | 0x80;
					}
					*/
					/*
					char initb=(char)0x80;
					uint bits=0xffff;
					int pc = 3;
					do {
						if ( (uc > bits) ){
							obuf[t+pc] = (uc & 0x3f) | 0x80;
							initb >>= (char)1;
							uc >>= 6;
							p++;
						}
						pc--;
						bits >>= 5;
					} while ( pc );
					obuf[t] = (char)uc | (char)initb;
					p++;
					*/

					char initb=(char)0xc0;
					if ( uc >= 65536 ){
						obuf[t+3] = (uc & 0x3f) | 0x80;
						initb >>= (char)1;
						uc >>= 6;
						p++;
					}
					if ( uc >= 2048 ){
						obuf[t+2] = (uc & 0x3f) | 0x80;
						initb >>= (char)1;
						uc >>= 6;
						p++;
					}
					obuf[t+1] = (uc & 0x3f) | 0x80;
					obuf[t] = (uc>>6) | initb;
					p += 2;

				} else {
					// convert to codepage
					if ( (uc<UNITABLE) && ( ocp[ uc ] != 0 ) ){
						obuf[p++] = ocp[ uc ];
					} else if ( uc>=UNITABLE ){
						for ( int a = 0; a<128; a++ )
							if ( cp[to].map[a] == uc ){
								obuf[p++] = a+128;
								break;
							}
					}
				}

				if ( t == p ){ // no conversion possible
ERR_UTF8:
					e( "Cannot convert: %s: %d, unicode: %x\n",
							cp[from].name, buf[a], uc );
					obuf[p++] = cp[to].esign;
					if ( opts&8 ){
						p+= sprintf( (char*)obuf+p,"<%x>",uc );
					}
				}
			}
			if ( p > OBUF - 16 ){
				write(1,obuf,p);
				p=0;
			}
			a++;
		}

		write(1,obuf,p);

	} while (( len = read(0,buf,BUF) ));

	exit(0);
}


code:
/*# Small Deflate
`sdefl` is a small bare bone lossless compression library in ANSI C (ISO C90)
which implements the Deflate (RFC 1951) compressed data format specification standard.
It is mainly tuned to get as much speed and compression ratio from as little code
as needed to keep the implementation as concise as possible.

## Features
- Portable single header and source file duo written in ANSI C (ISO C90)
- Dual license with either MIT or public domain
- Small implementation
    - Deflate: 525 LoC
    - Inflate: 320 LoC
- Webassembly:
    - Deflate ~3.7 KB (~2.2KB compressed)
    - Inflate ~3.6 KB (~2.2KB compressed)

## Usage:
This file behaves differently depending on what symbols you define
before including it.

Header-File mode:
If you do not define `SDEFL_IMPLEMENTATION` before including this file, it
will operate in header only mode. In this mode it declares all used structs
and the API of the library without including the implementation of the library.

Implementation mode:
If you define `SDEFL_IMPLEMENTATION` before including this file, it will
compile the implementation . Make sure that you only include
this file implementation in *one* C or C++ file to prevent collisions.

### Benchmark

| Compressor name         | Compression| Decompress.| Compr. size | Ratio |
| ------------------------| -----------| -----------| ----------- | ----- |
| miniz 1.0 -1            |   122 MB/s |   208 MB/s |    48510028 | 48.51 |
| miniz 1.0 -6            |    27 MB/s |   260 MB/s |    36513697 | 36.51 |
| miniz 1.0 -9            |    23 MB/s |   261 MB/s |    36460101 | 36.46 |
| zlib 1.2.11 -1          |    72 MB/s |   307 MB/s |    42298774 | 42.30 |
| zlib 1.2.11 -6          |    24 MB/s |   313 MB/s |    36548921 | 36.55 |
| zlib 1.2.11 -9          |    20 MB/s |   314 MB/s |    36475792 | 36.48 |
| sdefl 1.0 -0            |   127 MB/s |   355 MB/s |    40004116 | 39.88 |
| sdefl 1.0 -1            |   111 MB/s |   413 MB/s |    38940674 | 38.82 |
| sdefl 1.0 -5            |    45 MB/s |   436 MB/s |    36577183 | 36.46 |
| sdefl 1.0 -7            |    38 MB/s |   432 MB/s |    36523781 | 36.41 |
| libdeflate 1.3 -1       |   147 MB/s |   667 MB/s |    39597378 | 39.60 |
| libdeflate 1.3 -6       |    69 MB/s |   689 MB/s |    36648318 | 36.65 |
| libdeflate 1.3 -9       |    13 MB/s |   672 MB/s |    35197141 | 35.20 |
| libdeflate 1.3 -12      |  8.13 MB/s |   670 MB/s |    35100568 | 35.10 |

### Compression
Results on the [Silesia compression corpus](http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia):

| File    |   Original | `sdefl 0`    | `sdefl 5`  | `sdefl 7`   |
| --------| -----------| -------------| ---------- | ------------|
| dickens | 10.192.446 | 4,260,187    |  3,845,261 |   3,833,657 |
| mozilla | 51.220.480 | 20,774,706   | 19,607,009 |  19,565,867 |
| mr      |  9.970.564 | 3,860,531    |  3,673,460 |   3,665,627 |
| nci     | 33.553.445 | 4,030,283    |  3,094,526 |   3,006,075 |
| ooffice |  6.152.192 | 3,320,063    |  3,186,373 |   3,183,815 |
| osdb    | 10.085.684 | 3,919,646    |  3,649,510 |   3,649,477 |
| reymont |  6.627.202 | 2,263,378    |  1,857,588 |   1,827,237 |
| samba   | 21.606.400 | 6,121,797    |  5,462,670 |   5,450,762 |
| sao     |  7.251.944 | 5,612,421    |  5,485,380 |   5,481,765 |
| webster | 41.458.703 | 13,972,648   | 12,059,432 |  11,991,421 |
| xml     |  5.345.280 | 886,620      |    674,009 |     662,141 |
| x-ray   |  8.474.240 | 6,304,655    |  6,244,779 |   6,244,779 |

## License
```
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2020-2023 Micha Mettke
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
```
*/
#ifndef SDEFL_H_INCLUDED
#define SDEFL_H_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif

#define SDEFL_MAX_OFF   (1 << 15)
#define SDEFL_WIN_SIZ   SDEFL_MAX_OFF
#define SDEFL_WIN_MSK   (SDEFL_WIN_SIZ-1)

#define SDEFL_HASH_BITS 15
#define SDEFL_HASH_SIZ  (1 << SDEFL_HASH_BITS)
#define SDEFL_HASH_MSK  (SDEFL_HASH_SIZ-1)

#define SDEFL_MIN_MATCH 4
#define SDEFL_BLK_MAX   (256*1024)
#define SDEFL_SEQ_SIZ   ((SDEFL_BLK_MAX+2)/3)

#define SDEFL_SYM_MAX   (288)
#define SDEFL_OFF_MAX   (32)
#define SDEFL_PRE_MAX   (19)

#define SDEFL_LVL_MIN   0
#define SDEFL_LVL_DEF   5
#define SDEFL_LVL_MAX   8

struct sdefl_freq {
  unsigned lit[SDEFL_SYM_MAX];
  unsigned off[SDEFL_OFF_MAX];
};
struct sdefl_code_words {
  unsigned lit[SDEFL_SYM_MAX];
  unsigned off[SDEFL_OFF_MAX];
};
struct sdefl_lens {
  unsigned char lit[SDEFL_SYM_MAX];
  unsigned char off[SDEFL_OFF_MAX];
};
struct sdefl_codes {
  struct sdefl_code_words word;
  struct sdefl_lens len;
};
struct sdefl_seqt {
  int off, len;
};
struct sdefl {
  int bits, bitcnt;
  int tbl[SDEFL_HASH_SIZ];
  int prv[SDEFL_WIN_SIZ];

  int seq_cnt;
  struct sdefl_seqt seq[SDEFL_SEQ_SIZ];
  struct sdefl_freq freq;
  struct sdefl_codes cod;
};
extern int sdefl_bound(int in_len);
extern int sdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);
extern int zsdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);

#ifdef __cplusplus
}
#endif

#endif /* SDEFL_H_INCLUDED */

#ifdef SDEFL_IMPLEMENTATION

#include <assert.h> /* assert */
#include <string.h> /* memcpy */
#include <limits.h> /* CHAR_BIT */

#define SDEFL_NIL               (-1)
#define SDEFL_MAX_MATCH         258
#define SDEFL_MAX_CODE_LEN      (15)
#define SDEFL_SYM_BITS          (10u)
#define SDEFL_SYM_MSK           ((1u << SDEFL_SYM_BITS)-1u)
#define SDEFL_RAW_BLK_SIZE      (65535)
#define SDEFL_LIT_LEN_CODES     (14)
#define SDEFL_OFF_CODES         (15)
#define SDEFL_PRE_CODES         (7)
#define SDEFL_CNT_NUM(n)        ((((n)+3u/4u)+3u)&~3u)
#define SDEFL_EOB               (256)

#define sdefl_npow2(n) (1 << (sdefl_ilog2((n)-1) + 1))
#define sdefl_div_round_up(n,d) (((n)+((d)-1))/(d))

static int
sdefl_ilog2(int n) {
  if (!n) return 0;
#ifdef _MSC_VER
  unsigned long msbp = 0;
  _BitScanReverse(&msbp, (unsigned long)n);
  return (int)msbp;
#elif defined(__GNUC__) || defined(__clang__)
  return (int)sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl((unsigned long)n);
#else
  #define lt(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
  static const char tbl[256] = {
    0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,lt(4), lt(5), lt(5), lt(6), lt(6), lt(6), lt(6),
    lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7)};
  int tt, t;
  if ((tt = (n >> 16))) {
    return (t = (tt >> 8)) ? 24 + tbl[t] : 16 + tbl[tt];
  } else {
    return (t = (n >> 8)) ? 8 + tbl[t] : tbl[n];
  }
  #undef lt
#endif
}
static unsigned
sdefl_uload32(const void *p) {
  /* hopefully will be optimized to an unaligned read */
  unsigned n = 0;
  memcpy(&n, p, sizeof(n));
  return n;
}
static unsigned
sdefl_hash32(const void *p) {
  unsigned n = sdefl_uload32(p);
  return (n * 0x9E377989) >> (32 - SDEFL_HASH_BITS);
}
static void
sdefl_put(unsigned char **dst, struct sdefl *s, int code, int bitcnt) {
  s->bits |= (code << s->bitcnt);
  s->bitcnt += bitcnt;
  while (s->bitcnt >= 8) {
    unsigned char *tar = *dst;
    *tar = (unsigned char)(s->bits & 0xFF);
    s->bits >>= 8;
    s->bitcnt -= 8;
    *dst = *dst + 1;
  }
}
static void
sdefl_heap_sub(unsigned A[], unsigned len, unsigned sub) {
  unsigned c, p = sub;
  unsigned v = A[sub];
  while ((c = p << 1) <= len) {
    if (c < len && A[c + 1] > A[c]) c++;
    if (v >= A[c]) break;
    A[p] = A[c], p = c;
  }
  A[p] = v;
}
static void
sdefl_heap_array(unsigned *A, unsigned len) {
  unsigned sub;
  for (sub = len >> 1; sub >= 1; sub--)
    sdefl_heap_sub(A, len, sub);
}
static void
sdefl_heap_sort(unsigned *A, unsigned n) {
  A--;
  sdefl_heap_array(A, n);
  while (n >= 2) {
    unsigned tmp = A[n];
    A[n--] = A[1];
    A[1] = tmp;
    sdefl_heap_sub(A, n, 1);
  }
}
static unsigned
sdefl_sort_sym(unsigned sym_cnt, unsigned *freqs,
               unsigned char *lens, unsigned *sym_out) {
  unsigned cnts[SDEFL_CNT_NUM(SDEFL_SYM_MAX)] = {0};
  unsigned cnt_num = SDEFL_CNT_NUM(sym_cnt);
  unsigned used_sym = 0;
  unsigned sym, i;
  for (sym = 0; sym < sym_cnt; sym++)
    cnts[freqs[sym] < cnt_num-1 ? freqs[sym]: cnt_num-1]++;
  for (i = 1; i < cnt_num; i++) {
    unsigned cnt = cnts[i];
    cnts[i] = used_sym;
    used_sym += cnt;
  }
  for (sym = 0; sym < sym_cnt; sym++) {
    unsigned freq = freqs[sym];
    if (freq) {
        unsigned idx = freq < cnt_num-1 ? freq : cnt_num-1;
        sym_out[cnts[idx]++] = sym | (freq << SDEFL_SYM_BITS);
    } else lens[sym] = 0;
  }
  sdefl_heap_sort(sym_out + cnts[cnt_num-2], cnts[cnt_num-1] - cnts[cnt_num-2]);
  return used_sym;
}
static void
sdefl_build_tree(unsigned *A, unsigned sym_cnt) {
  unsigned i = 0, b = 0, e = 0;
  do {
    unsigned m, n, freq_shift;
    if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
      m = i++;
    else m = b++;
    if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
      n = i++;
    else n = b++;

    freq_shift = (A[m] & ~SDEFL_SYM_MSK) + (A[n] & ~SDEFL_SYM_MSK);
    A[m] = (A[m] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
    A[n] = (A[n] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
    A[e] = (A[e] & SDEFL_SYM_MSK) | freq_shift;
  } while (sym_cnt - ++e > 1);
}
static void
sdefl_gen_len_cnt(unsigned *A, unsigned root, unsigned *len_cnt,
                  unsigned max_code_len) {
  int n;
  unsigned i;
  for (i = 0; i <= max_code_len; i++)
    len_cnt[i] = 0;
  len_cnt[1] = 2;

  A[root] &= SDEFL_SYM_MSK;
  for (n = (int)root - 1; n >= 0; n--) {
    unsigned p = A[n] >> SDEFL_SYM_BITS;
    unsigned pdepth = A[p] >> SDEFL_SYM_BITS;
    unsigned depth = pdepth + 1;
    unsigned len = depth;

    A[n] = (A[n] & SDEFL_SYM_MSK) | (depth << SDEFL_SYM_BITS);
    if (len >= max_code_len) {
      len = max_code_len;
      do len--; while (!len_cnt[len]);
    }
    len_cnt[len]--;
    len_cnt[len+1] += 2;
  }
}
static void
sdefl_gen_codes(unsigned *A, unsigned char *lens, const unsigned *len_cnt,
                unsigned max_code_word_len, unsigned sym_cnt) {
  unsigned i, sym, len, nxt[SDEFL_MAX_CODE_LEN + 1];
  for (i = 0, len = max_code_word_len; len >= 1; len--) {
    unsigned cnt = len_cnt[len];
    while (cnt--) lens[A[i++] & SDEFL_SYM_MSK] = (unsigned char)len;
  }
  nxt[0] = nxt[1] = 0;
  for (len = 2; len <= max_code_word_len; len++)
    nxt[len] = (nxt[len-1] + len_cnt[len-1]) << 1;
  for (sym = 0; sym < sym_cnt; sym++)
    A[sym] = nxt[lens[sym]]++;
}
static unsigned
sdefl_rev(unsigned c, unsigned char n) {
  c = ((c & 0x5555) << 1) | ((c & 0xAAAA) >> 1);
  c = ((c & 0x3333) << 2) | ((c & 0xCCCC) >> 2);
  c = ((c & 0x0F0F) << 4) | ((c & 0xF0F0) >> 4);
  c = ((c & 0x00FF) << 8) | ((c & 0xFF00) >> 8);
  return c >> (16-n);
}
static void
sdefl_huff(unsigned char *lens, unsigned *codes, unsigned *freqs,
           unsigned num_syms, unsigned max_code_len) {
  unsigned c, *A = codes;
  unsigned len_cnt[SDEFL_MAX_CODE_LEN + 1];
  unsigned used_syms = sdefl_sort_sym(num_syms, freqs, lens, A);
  if (!used_syms) return;
  if (used_syms == 1) {
    unsigned s = A[0] & SDEFL_SYM_MSK;
    unsigned i = s ? s : 1;
    codes[0] = 0, lens[0] = 1;
    codes[i] = 1, lens[i] = 1;
    return;
  }
  sdefl_build_tree(A, used_syms);
  sdefl_gen_len_cnt(A, used_syms-2, len_cnt, max_code_len);
  sdefl_gen_codes(A, lens, len_cnt, max_code_len, num_syms);
  for (c = 0; c < num_syms; c++) {
    codes[c] = sdefl_rev(codes[c], lens[c]);
  }
}
struct sdefl_symcnt {
  int items;
  int lit;
  int off;
};
static void
sdefl_precode(struct sdefl_symcnt *cnt, unsigned *freqs, unsigned *items,
              const unsigned char *litlen, const unsigned char *offlen) {
  unsigned *at = items;
  unsigned run_start = 0;

  unsigned total = 0;
  unsigned char lens[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
  for (cnt->lit = SDEFL_SYM_MAX; cnt->lit > 257; cnt->lit--)
    if (litlen[cnt->lit - 1]) break;
  for (cnt->off = SDEFL_OFF_MAX; cnt->off > 1; cnt->off--)
    if (offlen[cnt->off - 1]) break;

  total = (unsigned)(cnt->lit + cnt->off);
  memcpy(lens, litlen, sizeof(unsigned char) * (size_t)cnt->lit);
  memcpy(lens + cnt->lit, offlen, sizeof(unsigned char) * (size_t)cnt->off);
  do {
    unsigned len = lens[run_start];
    unsigned run_end = run_start;
    do run_end++; while (run_end != total && len == lens[run_end]);
    if (!len) {
      while ((run_end - run_start) >= 11) {
        unsigned n = (run_end - run_start) - 11;
        unsigned xbits =  n < 0x7f ? n : 0x7f;
        freqs[18]++;
        *at++ = 18u | (xbits << 5u);
        run_start += 11 + xbits;
      }
      if ((run_end - run_start) >= 3) {
        unsigned n = (run_end - run_start) - 3;
        unsigned xbits =  n < 0x7 ? n : 0x7;
        freqs[17]++;
        *at++ = 17u | (xbits << 5u);
        run_start += 3 + xbits;
      }
    } else if ((run_end - run_start) >= 4) {
      freqs[len]++;
      *at++ = len;
      run_start++;
      do {
        unsigned xbits = (run_end - run_start) - 3;
        xbits = xbits < 0x03 ? xbits : 0x03;
        *at++ = 16 | (xbits << 5);
        run_start += 3 + xbits;
        freqs[16]++;
      } while ((run_end - run_start) >= 3);
    }
    while (run_start != run_end) {
      freqs[len]++;
      *at++ = len;
      run_start++;
    }
  } while (run_start != total);
  cnt->items = (int)(at - items);
}
struct sdefl_match_codest {
  int ls, lc;
  int dc, dx;
};
static void
sdefl_match_codes(struct sdefl_match_codest *cod, int dist, int len) {
  static const short dxmax[] = {0,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576};
  static const unsigned char lslot[258+1] = {
    0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12,
    12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16,
    16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18,
    18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
    20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
    21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
    22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
    23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
    24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
    25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
    25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26,
    26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
    26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
    27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
    27, 27, 28
  };
  assert(len <= 258);
  assert(dist <= 32768);
  cod->ls = lslot[len];
  cod->lc = 257 + cod->ls;
  assert(cod->lc <= 285);

  cod->dx = sdefl_ilog2(sdefl_npow2(dist) >> 2);
  cod->dc = cod->dx ? ((cod->dx + 1) << 1) + (dist > dxmax[cod->dx]) : dist-1;
}
enum sdefl_blk_type {
  SDEFL_BLK_UCOMPR,
  SDEFL_BLK_DYN
};
static enum sdefl_blk_type
sdefl_blk_type(const struct sdefl *s, int blk_len, int pre_item_len,
               const unsigned *pre_freq, const unsigned char *pre_len) {
  static const unsigned char x_pre_bits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  static const unsigned char x_len_bits[] = {0,0,0,0,0,0,0,0, 1,1,1,1,2,2,2,2,
    3,3,3,3,4,4,4,4, 5,5,5,5,0};
  static const unsigned char x_off_bits[] = {0,0,0,0,1,1,2,2, 3,3,4,4,5,5,6,6,
    7,7,8,8,9,9,10,10, 11,11,12,12,13,13};

  int dyn_cost = 0;
  int fix_cost = 0;
  int sym = 0;

  dyn_cost += 5 + 5 + 4 + (3 * pre_item_len);
  for (sym = 0; sym < SDEFL_PRE_MAX; sym++)
    dyn_cost += pre_freq[sym] * (x_pre_bits[sym] + pre_len[sym]);
  for (sym = 0; sym < 256; sym++)
    dyn_cost += s->freq.lit[sym] * s->cod.len.lit[sym];
  dyn_cost += s->cod.len.lit[SDEFL_EOB];
  for (sym = 257; sym < 286; sym++)
    dyn_cost += s->freq.lit[sym] * (x_len_bits[sym - 257] + s->cod.len.lit[sym]);
  for (sym = 0; sym < 30; sym++)
    dyn_cost += s->freq.off[sym] * (x_off_bits[sym] + s->cod.len.off[sym]);

  fix_cost += 8*(5 * sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE) + blk_len + 1 + 2);
  return (dyn_cost < fix_cost) ? SDEFL_BLK_DYN : SDEFL_BLK_UCOMPR;
}
static void
sdefl_put16(unsigned char **dst, unsigned short x) {
  unsigned char *val = *dst;
  val[0] = (unsigned char)(x & 0xff);
  val[1] = (unsigned char)(x >> 8);
  *dst = val + 2;
}
static void
sdefl_match(unsigned char **dst, struct sdefl *s, int dist, int len) {
  static const char lxn[] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  static const short lmin[] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,
      51,59,67,83,99,115,131,163,195,227,258};
  static const short dmin[] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,
      385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577};

  struct sdefl_match_codest cod;
  sdefl_match_codes(&cod, dist, len);
  sdefl_put(dst, s, (int)s->cod.word.lit[cod.lc], s->cod.len.lit[cod.lc]);
  sdefl_put(dst, s, len - lmin[cod.ls], lxn[cod.ls]);
  sdefl_put(dst, s, (int)s->cod.word.off[cod.dc], s->cod.len.off[cod.dc]);
  sdefl_put(dst, s, dist - dmin[cod.dc], cod.dx);
}
static void
sdefl_flush(unsigned char **dst, struct sdefl *s, int is_last,
            const unsigned char *in, int blk_begin, int blk_end) {
  int blk_len = blk_end - blk_begin;
  int j, i = 0, item_cnt = 0;
  struct sdefl_symcnt symcnt = {0};
  unsigned codes[SDEFL_PRE_MAX];
  unsigned char lens[SDEFL_PRE_MAX];
  unsigned freqs[SDEFL_PRE_MAX] = {0};
  unsigned items[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
  static const unsigned char perm[SDEFL_PRE_MAX] = {16,17,18,0,8,7,9,6,10,5,11,
      4,12,3,13,2,14,1,15};

  /* calculate huffman codes */
  s->freq.lit[SDEFL_EOB]++;
  sdefl_huff(s->cod.len.lit, s->cod.word.lit, s->freq.lit, SDEFL_SYM_MAX, SDEFL_LIT_LEN_CODES);
  sdefl_huff(s->cod.len.off, s->cod.word.off, s->freq.off, SDEFL_OFF_MAX, SDEFL_OFF_CODES);
  sdefl_precode(&symcnt, freqs, items, s->cod.len.lit, s->cod.len.off);
  sdefl_huff(lens, codes, freqs, SDEFL_PRE_MAX, SDEFL_PRE_CODES);
  for (item_cnt = SDEFL_PRE_MAX; item_cnt > 4; item_cnt--) {
    if (lens[perm[item_cnt - 1]]){
      break;
    }
  }
  /* write block */
  switch (sdefl_blk_type(s, blk_len, item_cnt, freqs, lens)) {
  case SDEFL_BLK_UCOMPR: {
    /* uncompressed blocks */
    int n = sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE);
    for (i = 0; i < n; ++i) {
      int fin = is_last && (i + 1 == n);
      int amount = blk_len < SDEFL_RAW_BLK_SIZE ? blk_len : SDEFL_RAW_BLK_SIZE;
      sdefl_put(dst, s, !!fin, 1); /* block */
      sdefl_put(dst, s, 0x00, 2); /* stored block */
      if (s->bitcnt) {
        sdefl_put(dst, s, 0x00, 8 - s->bitcnt);
      }
      assert(s->bitcnt == 0);
      sdefl_put16(dst, (unsigned short)amount);
      sdefl_put16(dst, ~(unsigned short)amount);
      memcpy(*dst, in + blk_begin + i * SDEFL_RAW_BLK_SIZE, amount);
      *dst = *dst + amount;
      blk_len -= amount;
    }
  } break;
  case SDEFL_BLK_DYN: {
    /* dynamic huffman block */
    sdefl_put(dst, s, !!is_last, 1); /* block */
    sdefl_put(dst, s, 0x02, 2); /* dynamic huffman */
    sdefl_put(dst, s, symcnt.lit - 257, 5);
    sdefl_put(dst, s, symcnt.off - 1, 5);
    sdefl_put(dst, s, item_cnt - 4, 4);
    for (i = 0; i < item_cnt; ++i) {
      sdefl_put(dst, s, lens[perm[i]], 3);
    }
    for (i = 0; i < symcnt.items; ++i) {
      unsigned sym = items[i] & 0x1F;
      sdefl_put(dst, s, (int)codes[sym], lens[sym]);
      if (sym < 16) continue;
      if (sym == 16) sdefl_put(dst, s, items[i] >> 5, 2);
      else if(sym == 17) sdefl_put(dst, s, items[i] >> 5, 3);
      else sdefl_put(dst, s, items[i] >> 5, 7);
    }
    /* block sequences */
    for (i = 0; i < s->seq_cnt; ++i) {
      if (s->seq[i].off >= 0) {
        for (j = 0; j < s->seq[i].len; ++j) {
          int c = in[s->seq[i].off + j];
          sdefl_put(dst, s, (int)s->cod.word.lit[c], s->cod.len.lit[c]);
        }
      } else {
        sdefl_match(dst, s, -s->seq[i].off, s->seq[i].len);
      }
    }
    sdefl_put(dst, s, (int)(s)->cod.word.lit[SDEFL_EOB], (s)->cod.len.lit[SDEFL_EOB]);
  } break;}
  memset(&s->freq, 0, sizeof(s->freq));
  s->seq_cnt = 0;
}
static void
sdefl_seq(struct sdefl *s, int off, int len) {
  assert(s->seq_cnt + 2 < SDEFL_SEQ_SIZ);
  s->seq[s->seq_cnt].off = off;
  s->seq[s->seq_cnt].len = len;
  s->seq_cnt++;
}
static void
sdefl_reg_match(struct sdefl *s, int off, int len) {
  struct sdefl_match_codest cod;
  sdefl_match_codes(&cod, off, len);

  assert(cod.lc < SDEFL_SYM_MAX);
  assert(cod.dc < SDEFL_OFF_MAX);

  s->freq.lit[cod.lc]++;
  s->freq.off[cod.dc]++;
}
struct sdefl_match {
  int off;
  int len;
};
static void
sdefl_fnd(struct sdefl_match *m, const struct sdefl *s, int chain_len,
          int max_match, const unsigned char *in, int p, int e) {
  int i = s->tbl[sdefl_hash32(in + p)];
  int limit = ((p - SDEFL_WIN_SIZ) < SDEFL_NIL) ? SDEFL_NIL : (p-SDEFL_WIN_SIZ);

  assert(p < e);
  assert(p + max_match <= e);
  while (i > limit) {
    assert(i + m->len < e);
    assert(p + m->len < e);
    assert(i + SDEFL_MIN_MATCH < e);
    assert(p + SDEFL_MIN_MATCH < e);

    if (in[i + m->len] == in[p + m->len] &&
      (sdefl_uload32(&in[i]) == sdefl_uload32(&in[p]))) {
      int n = SDEFL_MIN_MATCH;
      while (n < max_match && in[i + n] == in[p + n]) {
        assert(i + n < e);
        assert(p + n < e);
        n++;
      }
      if (n > m->len) {
        m->len = n, m->off = p - i;
        if (n == max_match)
          break;
      }
    }
    if (!(--chain_len)) break;
    i = s->prv[i & SDEFL_WIN_MSK];
  }
}
static int
sdefl_compr(struct sdefl *s, unsigned char *out, const unsigned char *in,
            int in_len, int lvl) {
  unsigned char *q = out;
  static const unsigned char pref[] = {8,10,14,24,30,48,65,96,130};
  int max_chain = (lvl < 8) ? (1 << (lvl + 1)): (1 << 13);
  int n, i = 0, litlen = 0;
  for (n = 0; n < SDEFL_HASH_SIZ; ++n) {
    s->tbl[n] = SDEFL_NIL;
  }
  do {int blk_begin = i;
    int blk_end = ((i + SDEFL_BLK_MAX) < in_len) ? (i + SDEFL_BLK_MAX) : in_len;
    while (i < blk_end) {
      struct sdefl_match m = {0};
      int left = blk_end - i;
      int max_match = (left > SDEFL_MAX_MATCH) ? SDEFL_MAX_MATCH : left;
      int nice_match = pref[lvl] < max_match ? pref[lvl] : max_match;
      int run = 1, inc = 1, run_inc = 0;
      if (max_match > SDEFL_MIN_MATCH) {
        sdefl_fnd(&m, s, max_chain, max_match, in, i, in_len);
      }
      if (lvl >= 5 && m.len >= SDEFL_MIN_MATCH && m.len + 1 < nice_match){
        struct sdefl_match m2 = {0};
        sdefl_fnd(&m2, s, max_chain, m.len + 1, in, i + 1, in_len);
        m.len = (m2.len > m.len) ? 0 : m.len;
      }
      if (m.len >= SDEFL_MIN_MATCH) {
        if (litlen) {
          sdefl_seq(s, i - litlen, litlen);
          litlen = 0;
        }
        sdefl_seq(s, -m.off, m.len);
        sdefl_reg_match(s, m.off, m.len);
        if (lvl < 2 && m.len >= nice_match) {
          inc = m.len;
        } else {
          run = m.len;
        }
      } else {
        s->freq.lit[in[i]]++;
        litlen++;
      }
      run_inc = run * inc;
      if (in_len - (i + run_inc) > SDEFL_MIN_MATCH) {
        while (run-- > 0) {
          unsigned h = sdefl_hash32(&in[i]);
          s->prv[i&SDEFL_WIN_MSK] = s->tbl[h];
          s->tbl[h] = i, i += inc;
          assert(i <= blk_end);
        }
      } else {
        i += run_inc;
        assert(i <= blk_end);
      }
    }
    if (litlen) {
      sdefl_seq(s, i - litlen, litlen);
      litlen = 0;
    }
    sdefl_flush(&q, s, blk_end == in_len, in, blk_begin, blk_end);
  } while (i < in_len);
  if (s->bitcnt) {
    sdefl_put(&q, s, 0x00, 8 - s->bitcnt);
  }
  assert(s->bitcnt == 0);
  return (int)(q - out);
}
extern int
sdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
  s->bits = s->bitcnt = 0;
  return sdefl_compr(s, (unsigned char*)out, (const unsigned char*)in, n, lvl);
}
static unsigned
sdefl_adler32(unsigned adler32, const unsigned char *in, int in_len) {
  #define SDEFL_ADLER_INIT (1)
  const unsigned ADLER_MOD = 65521;
  unsigned s1 = adler32 & 0xffff;
  unsigned s2 = adler32 >> 16;
  unsigned blk_len, i;

  blk_len = in_len % 5552;
  while (in_len) {
    for (i = 0; i + 7 < blk_len; i += 8) {
      s1 += in[0]; s2 += s1;
      s1 += in[1]; s2 += s1;
      s1 += in[2]; s2 += s1;
      s1 += in[3]; s2 += s1;
      s1 += in[4]; s2 += s1;
      s1 += in[5]; s2 += s1;
      s1 += in[6]; s2 += s1;
      s1 += in[7]; s2 += s1;
      in += 8;
    }
    for (; i < blk_len; ++i) {
      s1 += *in++, s2 += s1;
    }
    s1 %= ADLER_MOD;
    s2 %= ADLER_MOD;
    in_len -= blk_len;
    blk_len = 5552;
  }
  return (unsigned)(s2 << 16) + (unsigned)s1;
}
extern int
zsdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
  int p = 0;
  unsigned a = 0;
  unsigned char *q = (unsigned char*)out;

  s->bits = s->bitcnt = 0;
  sdefl_put(&q, s, 0x78, 8); /* deflate, 32k window */
  sdefl_put(&q, s, 0x01, 8); /* fast compression */
  q += sdefl_compr(s, q, (const unsigned char*)in, n, lvl);

  /* append adler checksum */
  a = sdefl_adler32(SDEFL_ADLER_INIT, (const unsigned char*)in, n);
  for (p = 0; p < 4; ++p) {
    sdefl_put(&q, s, (a >> 24) & 0xFF, 8);
    a <<= 8;
  }
  return (int)(q - (unsigned char*)out);
}
extern int
sdefl_bound(int len) {
  int max_blocks = 1 + sdefl_div_round_up(len, SDEFL_RAW_BLK_SIZE);
  int bound = 5 * max_blocks + len + 1 + 4 + 8;
  return bound;
}
#endif /* SDEFL_IMPLEMENTATION */

repo_name: misc/slterm

license: mit


code:
/*
# Small Deflate
`sdefl` is a small bare bone lossless compression library in ANSI C (ISO C90)
which implements the Deflate (RFC 1951) compressed data format specification standard.
It is mainly tuned to get as much speed and compression ratio from as little code
as needed to keep the implementation as concise as possible.

## Features
- Portable single header and source file duo written in ANSI C (ISO C90)
- Dual license with either MIT or public domain
- Small implementation
    - Deflate: 525 LoC
    - Inflate: 500 LoC
- Webassembly:
    - Deflate ~3.7 KB (~2.2KB compressed)
    - Inflate ~3.6 KB (~2.2KB compressed)

## Usage:
This file behaves differently depending on what symbols you define
before including it.

Header-File mode:
If you do not define `SINFL_IMPLEMENTATION` before including this file, it
will operate in header only mode. In this mode it declares all used structs
and the API of the library without including the implementation of the library.

Implementation mode:
If you define `SINFL_IMPLEMENTATION` before including this file, it will
compile the implementation. Make sure that you only include
this file implementation in *one* C or C++ file to prevent collisions.

### Benchmark

| Compressor name         | Compression| Decompress.| Compr. size | Ratio |
| ------------------------| -----------| -----------| ----------- | ----- |
| miniz 1.0 -1            |   122 MB/s |   208 MB/s |    48510028 | 48.51 |
| miniz 1.0 -6            |    27 MB/s |   260 MB/s |    36513697 | 36.51 |
| miniz 1.0 -9            |    23 MB/s |   261 MB/s |    36460101 | 36.46 |
| zlib 1.2.11 -1          |    72 MB/s |   307 MB/s |    42298774 | 42.30 |
| zlib 1.2.11 -6          |    24 MB/s |   313 MB/s |    36548921 | 36.55 |
| zlib 1.2.11 -9          |    20 MB/s |   314 MB/s |    36475792 | 36.48 |
| sdefl 1.0 -0            |   127 MB/s |   355 MB/s |    40004116 | 39.88 |
| sdefl 1.0 -1            |   111 MB/s |   413 MB/s |    38940674 | 38.82 |
| sdefl 1.0 -5            |    45 MB/s |   436 MB/s |    36577183 | 36.46 |
| sdefl 1.0 -7            |    38 MB/s |   432 MB/s |    36523781 | 36.41 |
| libdeflate 1.3 -1       |   147 MB/s |   667 MB/s |    39597378 | 39.60 |
| libdeflate 1.3 -6       |    69 MB/s |   689 MB/s |    36648318 | 36.65 |
| libdeflate 1.3 -9       |    13 MB/s |   672 MB/s |    35197141 | 35.20 |
| libdeflate 1.3 -12      |  8.13 MB/s |   670 MB/s |    35100568 | 35.10 |

### Compression
Results on the [Silesia compression corpus](http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia):

| File    |   Original | `sdefl 0`    | `sdefl 5`  | `sdefl 7`   |
| --------| -----------| -------------| ---------- | ------------|
| dickens | 10.192.446 | 4,260,187    |  3,845,261 |   3,833,657 |
| mozilla | 51.220.480 | 20,774,706   | 19,607,009 |  19,565,867 |
| mr      |  9.970.564 | 3,860,531    |  3,673,460 |   3,665,627 |
| nci     | 33.553.445 | 4,030,283    |  3,094,526 |   3,006,075 |
| ooffice |  6.152.192 | 3,320,063    |  3,186,373 |   3,183,815 |
| osdb    | 10.085.684 | 3,919,646    |  3,649,510 |   3,649,477 |
| reymont |  6.627.202 | 2,263,378    |  1,857,588 |   1,827,237 |
| samba   | 21.606.400 | 6,121,797    |  5,462,670 |   5,450,762 |
| sao     |  7.251.944 | 5,612,421    |  5,485,380 |   5,481,765 |
| webster | 41.458.703 | 13,972,648   | 12,059,432 |  11,991,421 |
| xml     |  5.345.280 | 886,620      |    674,009 |     662,141 |
| x-ray   |  8.474.240 | 6,304,655    |  6,244,779 |   6,244,779 |

## License
```
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2020-2023 Micha Mettke
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
```
*/
#ifndef SINFL_H_INCLUDED
#define SINFL_H_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif

#define SINFL_PRE_TBL_SIZE 128
#define SINFL_LIT_TBL_SIZE 1334
#define SINFL_OFF_TBL_SIZE 402

struct sinfl {
  const unsigned char *bitptr;
  unsigned long long bitbuf;
  int bitcnt;

  unsigned lits[SINFL_LIT_TBL_SIZE];
  unsigned dsts[SINFL_OFF_TBL_SIZE];
};
extern int sinflate(void *out, int cap, const void *in, int size);
extern int zsinflate(void *out, int cap, const void *in, int size);

#ifdef __cplusplus
}
#endif

#endif /* SINFL_H_INCLUDED */

#ifdef SINFL_IMPLEMENTATION

#include <string.h> /* memcpy, memset */
#include <assert.h> /* assert */

#if defined(__GNUC__) || defined(__clang__)
#define sinfl_likely(x)       __builtin_expect((x),1)
#define sinfl_unlikely(x)     __builtin_expect((x),0)
#else
#define sinfl_likely(x)       (x)
#define sinfl_unlikely(x)     (x)
#endif

#ifndef SINFL_NO_SIMD
#if defined(__x86_64__) || defined(_WIN32) || defined(_WIN64)
  #include <emmintrin.h>
  #define sinfl_char16 __m128i
  #define sinfl_char16_ld(p) _mm_loadu_si128((const __m128i *)(void*)(p))
  #define sinfl_char16_str(d,v)  _mm_storeu_si128((__m128i*)(void*)(d), v)
  #define sinfl_char16_char(c) _mm_set1_epi8(c)
#elif defined(__arm__) || defined(__aarch64__)
  #include <arm_neon.h>
  #define sinfl_char16 uint8x16_t
  #define sinfl_char16_ld(p) vld1q_u8((const unsigned char*)(p))
  #define sinfl_char16_str(d,v) vst1q_u8((unsigned char*)(d), v)
  #define sinfl_char16_char(c) vdupq_n_u8(c)
#else
  #define SINFL_NO_SIMD
#endif
#endif

static int
sinfl_bsr(unsigned n) {
#ifdef _MSC_VER
  _BitScanReverse(&n, n);
  return n;
#elif defined(__GNUC__) || defined(__clang__)
  return 31 - __builtin_clz(n);
#endif
}
static unsigned long long
sinfl_read64(const void *p) {
  unsigned long long n;
  memcpy(&n, p, 8);
  return n;
}
static void
sinfl_copy64(unsigned char **dst, unsigned char **src) {
  unsigned long long n;
  memcpy(&n, *src, 8);
  memcpy(*dst, &n, 8);
  *dst += 8, *src += 8;
}
static unsigned char*
sinfl_write64(unsigned char *dst, unsigned long long w) {
  memcpy(dst, &w, 8);
  return dst + 8;
}
#ifndef SINFL_NO_SIMD
static unsigned char*
sinfl_write128(unsigned char *dst, sinfl_char16 w) {
  sinfl_char16_str(dst, w);
  return dst + 8;
}
static void
sinfl_copy128(unsigned char **dst, unsigned char **src) {
  sinfl_char16 n = sinfl_char16_ld(*src);
  sinfl_char16_str(*dst, n);
  *dst += 16, *src += 16;
}
#endif
static void
sinfl_refill(struct sinfl *s) {
  s->bitbuf |= sinfl_read64(s->bitptr) << s->bitcnt;
  s->bitptr += (63 - s->bitcnt) >> 3;
  s->bitcnt |= 56; /* bitcount in range [56,63] */
}
static int
sinfl_peek(struct sinfl *s, int cnt) {
  assert(cnt >= 0 && cnt <= 56);
  assert(cnt <= s->bitcnt);
  return s->bitbuf & ((1ull << cnt) - 1);
}
static void
sinfl_eat(struct sinfl *s, int cnt) {
  assert(cnt <= s->bitcnt);
  s->bitbuf >>= cnt;
  s->bitcnt -= cnt;
}
static int
sinfl__get(struct sinfl *s, int cnt) {
  int res = sinfl_peek(s, cnt);
  sinfl_eat(s, cnt);
  return res;
}
static int
sinfl_get(struct sinfl *s, int cnt) {
  sinfl_refill(s);
  return sinfl__get(s, cnt);
}
struct sinfl_gen {
  int len;
  int cnt;
  int word;
  short* sorted;
};
static int
sinfl_build_tbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits,
                const int *cnt) {
  int tbl_end = 0;
  while (!(gen->cnt = cnt[gen->len])) {
    ++gen->len;
  }
  tbl_end = 1 << gen->len;
  while (gen->len <= tbl_bits) {
    do {unsigned bit = 0;
      tbl[gen->word] = (*gen->sorted++ << 16) | gen->len;
      if (gen->word == tbl_end - 1) {
        for (; gen->len < tbl_bits; gen->len++) {
          memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0]));
          tbl_end <<= 1;
        }
        return 1;
      }
      bit = 1 << sinfl_bsr((unsigned)(gen->word ^ (tbl_end - 1)));
      gen->word &= bit - 1;
      gen->word |= bit;
    } while (--gen->cnt);
    do {
      if (++gen->len <= tbl_bits) {
        memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0]));
        tbl_end <<= 1;
      }
    } while (!(gen->cnt = cnt[gen->len]));
  }
  return 0;
}
static void
sinfl_build_subtbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits,
                   const int *cnt) {
  int sub_bits = 0;
  int sub_start = 0;
  int sub_prefix = -1;
  int tbl_end = 1 << tbl_bits;
  while (1) {
    unsigned entry;
    int bit, stride, i;
    /* start new sub-table */
    if ((gen->word & ((1 << tbl_bits)-1)) != sub_prefix) {
      int used = 0;
      sub_prefix = gen->word & ((1 << tbl_bits)-1);
      sub_start = tbl_end;
      sub_bits = gen->len - tbl_bits;
      used = gen->cnt;
      while (used < (1 << sub_bits)) {
        sub_bits++;
        used = (used << 1) + cnt[tbl_bits + sub_bits];
      }
      tbl_end = sub_start + (1 << sub_bits);
      tbl[sub_prefix] = (sub_start << 16) | 0x10 | (sub_bits & 0xf);
    }
    /* fill sub-table */
    entry = (*gen->sorted << 16) | ((gen->len - tbl_bits) & 0xf);
    gen->sorted++;
    i = sub_start + (gen->word >> tbl_bits);
    stride = 1 << (gen->len - tbl_bits);
    do {
      tbl[i] = entry;
      i += stride;
    } while (i < tbl_end);
    if (gen->word == (1 << gen->len)-1) {
      return;
    }
    bit = 1 << sinfl_bsr(gen->word ^ ((1 << gen->len) - 1));
    gen->word &= bit - 1;
    gen->word |= bit;
    gen->cnt--;
    while (!gen->cnt) {
      gen->cnt = cnt[++gen->len];
    }
  }
}
static void
sinfl_build(unsigned *tbl, unsigned char *lens, int tbl_bits, int maxlen,
            int symcnt) {
  int i, used = 0;
  short sort[288];
  int cnt[16] = {0}, off[16]= {0};
  struct sinfl_gen gen = {0};
  gen.sorted = sort;
  gen.len = 1;

  for (i = 0; i < symcnt; ++i)
    cnt[lens[i]]++;
  off[1] = cnt[0];
  for (i = 1; i < maxlen; ++i) {
    off[i + 1] = off[i] + cnt[i];
    used = (used << 1) + cnt[i];
  }
  used = (used << 1) + cnt[i];
  for (i = 0; i < symcnt; ++i)
    gen.sorted[off[lens[i]]++] = (short)i;
  gen.sorted += off[0];

  if (used < (1 << maxlen)){
    for (i = 0; i < 1 << tbl_bits; ++i)
      tbl[i] = (0 << 16u) | 1;
    return;
  }
  if (!sinfl_build_tbl(&gen, tbl, tbl_bits, cnt)){
    sinfl_build_subtbl(&gen, tbl, tbl_bits, cnt);
  }
}
static int
sinfl_decode(struct sinfl *s, const unsigned *tbl, int bit_len) {
  int idx = sinfl_peek(s, bit_len);
  unsigned key = tbl[idx];
  if (key & 0x10) {
    /* sub-table lookup */
    int len = key & 0x0f;
    sinfl_eat(s, bit_len);
    idx = sinfl_peek(s, len);
    key = tbl[((key >> 16) & 0xffff) + (unsigned)idx];
  }
  sinfl_eat(s, key & 0x0f);
  return (key >> 16) & 0x0fff;
}
static int
sinfl_decompress(unsigned char *out, int cap, const unsigned char *in, int size) {
  static const unsigned char order[] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  static const short dbase[30+2] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
      257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577};
  static const unsigned char dbits[30+2] = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,
      10,10,11,11,12,12,13,13,0,0};
  static const short lbase[29+2] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,
      43,51,59,67,83,99,115,131,163,195,227,258,0,0};
  static const unsigned char lbits[29+2] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,
      4,4,4,5,5,5,5,0,0,0};

  const unsigned char *oe = out + cap;
  const unsigned char *e = in + size, *o = out;
  enum sinfl_states {hdr,stored,fixed,dyn,blk};
  enum sinfl_states state = hdr;
  struct sinfl s = {0};
  int last = 0;

  s.bitptr = in;
  while (1) {
    switch (state) {
    case hdr: {
      /* block header */
      int type = 0;
      sinfl_refill(&s);
      last = sinfl__get(&s,1);
      type = sinfl__get(&s,2);

      switch (type) {default: return (int)(out-o);
      case 0x00: state = stored; break;
      case 0x01: state = fixed; break;
      case 0x02: state = dyn; break;}
    } break;
    case stored: {
      /* uncompressed block */
      unsigned len, nlen;
      sinfl__get(&s,s.bitcnt & 7);
      len = (unsigned short)sinfl__get(&s,16);
      nlen = (unsigned short)sinfl__get(&s,16);
      s.bitptr -= s.bitcnt / 8;
      s.bitbuf = s.bitcnt = 0;

      if ((unsigned short)len != (unsigned short)~nlen)
        return (int)(out-o);
      if (len > (e - s.bitptr) || !len)
        return (int)(out-o);

      memcpy(out, s.bitptr, (size_t)len);
      s.bitptr += len, out += len;
      if (last) return (int)(out-o);
      state = hdr;
    } break;
    case fixed: {
      /* fixed huffman codes */
      int n; unsigned char lens[288+32];
      for (n = 0; n <= 143; n++) lens[n] = 8;
      for (n = 144; n <= 255; n++) lens[n] = 9;
      for (n = 256; n <= 279; n++) lens[n] = 7;
      for (n = 280; n <= 287; n++) lens[n] = 8;
      for (n = 0; n < 32; n++) lens[288+n] = 5;

      /* build lit/dist tables */
      sinfl_build(s.lits, lens, 10, 15, 288);
      sinfl_build(s.dsts, lens + 288, 8, 15, 32);
      state = blk;
    } break;
    case dyn: {
      /* dynamic huffman codes */
      int n, i;
      unsigned hlens[SINFL_PRE_TBL_SIZE];
      unsigned char nlens[19] = {0}, lens[288+32];

      sinfl_refill(&s);
      {int nlit = 257 + sinfl__get(&s,5);
      int ndist = 1 + sinfl__get(&s,5);
      int nlen = 4 + sinfl__get(&s,4);
      for (n = 0; n < nlen; n++)
        nlens[order[n]] = (unsigned char)sinfl_get(&s,3);
      sinfl_build(hlens, nlens, 7, 7, 19);

      /* decode code lengths */
      for (n = 0; n < nlit + ndist;) {
        int sym = 0;
        sinfl_refill(&s);
        sym = sinfl_decode(&s, hlens, 7);
        switch (sym) {default: lens[n++] = (unsigned char)sym; break;
        case 16: for (i=3+sinfl_get(&s,2);i;i--,n++) lens[n]=lens[n-1]; break;
        case 17: for (i=3+sinfl_get(&s,3);i;i--,n++) lens[n]=0; break;
        case 18: for (i=11+sinfl_get(&s,7);i;i--,n++) lens[n]=0; break;}
      }
      /* build lit/dist tables */
      sinfl_build(s.lits, lens, 10, 15, nlit);
      sinfl_build(s.dsts, lens + nlit, 8, 15, ndist);
      state = blk;}
    } break;
    case blk: {
      /* decompress block */
      while (1) {
        int sym;
        sinfl_refill(&s);
        sym = sinfl_decode(&s, s.lits, 10);
        if (sym < 256) {
          /* literal */
          if (sinfl_unlikely(out >= oe)) {
            return (int)(out-o);
          }
          *out++ = (unsigned char)sym;
          sym = sinfl_decode(&s, s.lits, 10);
          if (sym < 256) {
            *out++ = (unsigned char)sym;
            continue;
          }
        }
        if (sinfl_unlikely(sym == 256)) {
          /* end of block */
          if (last) return (int)(out-o);
          state = hdr;
          break;
        }
        /* match */
        if (sym >= 286) {
          /* length codes 286 and 287 must not appear in compressed data */
          return (int)(out-o);
        }
        sym -= 257;
        {int len = sinfl__get(&s, lbits[sym]) + lbase[sym];
        int dsym = sinfl_decode(&s, s.dsts, 8);
        int offs = sinfl__get(&s, dbits[dsym]) + dbase[dsym];
        unsigned char *dst = out, *src = out - offs;
        if (sinfl_unlikely(offs > (int)(out-o))) {
          return (int)(out-o);
        }
        out = out + len;

#ifndef SINFL_NO_SIMD
        if (sinfl_likely(oe - out >= 16 * 3)) {
          if (offs >= 16) {
            /* simd copy match */
            sinfl_copy128(&dst, &src);
            sinfl_copy128(&dst, &src);
            do sinfl_copy128(&dst, &src);
            while (dst < out);
          } else if (offs >= 8) {
            /* word copy match */
            sinfl_copy64(&dst, &src);
            sinfl_copy64(&dst, &src);
            do sinfl_copy64(&dst, &src);
            while (dst < out);
          } else if (offs == 1) {
            /* rle match copying */
            sinfl_char16 w = sinfl_char16_char(src[0]);
            dst = sinfl_write128(dst, w);
            dst = sinfl_write128(dst, w);
            do dst = sinfl_write128(dst, w);
            while (dst < out);
          } else {
            /* byte copy match */
            *dst++ = *src++;
            *dst++ = *src++;
            do *dst++ = *src++;
            while (dst < out);
          }
        }
#else
        if (sinfl_likely(oe - out >= 3 * 8 - 3)) {
          if (offs >= 8) {
            /* word copy match */
            sinfl_copy64(&dst, &src);
            sinfl_copy64(&dst, &src);
            do sinfl_copy64(&dst, &src);
            while (dst < out);
          } else if (offs == 1) {
            /* rle match copying */
            unsigned int c = src[0];
            unsigned int hw = (c << 24u) | (c << 16u) | (c << 8u) | (unsigned)c;
            unsigned long long w = (unsigned long long)hw << 32llu | hw;
            dst = sinfl_write64(dst, w);
            dst = sinfl_write64(dst, w);
            do dst = sinfl_write64(dst, w);
            while (dst < out);
          } else {
            /* byte copy match */
            *dst++ = *src++;
            *dst++ = *src++;
            do *dst++ = *src++;
            while (dst < out);
          }
        }
#endif
        else {
          *dst++ = *src++;
          *dst++ = *src++;
          do *dst++ = *src++;
          while (dst < out);
        }}
      }
    } break;}
  }
  return (int)(out-o);
}
extern int
sinflate(void *out, int cap, const void *in, int size) {
  return sinfl_decompress((unsigned char*)out, cap, (const unsigned char*)in, size);
}
static unsigned
sinfl_adler32(unsigned adler32, const unsigned char *in, int in_len) {
  const unsigned ADLER_MOD = 65521;
  unsigned s1 = adler32 & 0xffff;
  unsigned s2 = adler32 >> 16;
  unsigned blk_len, i;

  blk_len = in_len % 5552;
  while (in_len) {
    for (i=0; i + 7 < blk_len; i += 8) {
      s1 += in[0]; s2 += s1;
      s1 += in[1]; s2 += s1;
      s1 += in[2]; s2 += s1;
      s1 += in[3]; s2 += s1;
      s1 += in[4]; s2 += s1;
      s1 += in[5]; s2 += s1;
      s1 += in[6]; s2 += s1;
      s1 += in[7]; s2 += s1;
      in += 8;
    }
    for (; i < blk_len; ++i)
      s1 += *in++, s2 += s1;
    s1 %= ADLER_MOD; s2 %= ADLER_MOD;
    in_len -= blk_len;
    blk_len = 5552;
  } return (unsigned)(s2 << 16) + (unsigned)s1;
}
extern int
zsinflate(void *out, int cap, const void *mem, int size) {
  const unsigned char *in = (const unsigned char*)mem;
  if (size >= 6) {
    const unsigned char *eob = in + size - 4;
    int n = sinfl_decompress((unsigned char*)out, cap, in + 2u, size);
    unsigned a = sinfl_adler32(1u, (unsigned char*)out, n);
    unsigned h = eob[0] << 24 | eob[1] << 16 | eob[2] << 8 | eob[3] << 0;
    return a == h ? n : -1;
  } else {
    return -1;
  }
}
#endif


code:
tic: *.c *.h
	gcc -I. -o tic tic.c cdbw.c  mi_vector_hash.c compile.c hash.c -Os -s

path: tools/tic/Makefile


code:
terminfo compiler
from netbsd/ncurses

path: tools/tic/README


code:
/*	$NetBSD: cdbw.c,v 1.7 2021/01/07 14:41:50 joerg Exp $	*/
/*-
 * Copyright (c) 2009, 2010, 2015 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Joerg Sonnenberger and Alexander Nasonov.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif

#include <sys/queue.h>
#include <cdbw.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mi_vector_hash.h>

struct key_hash {
	SLIST_ENTRY(key_hash) link;
	uint32_t hashes[3];
	uint32_t idx;
	void *key;
	size_t keylen;
};

SLIST_HEAD(key_hash_head, key_hash);

struct cdbw {
	size_t data_counter;
	size_t data_allocated;
	size_t data_size;
	size_t *data_len;
	void **data_ptr;

	size_t hash_size;
	struct key_hash_head *hash;
	size_t key_counter;
};

 /* Max. data counter that allows the index size to be 32bit. */
static const uint32_t max_data_counter = 0xccccccccU;

struct cdbw *
cdbw_open(void)
{
	struct cdbw *cdbw;
	size_t i;

	cdbw = calloc(sizeof(*cdbw), 1);
	if (cdbw == NULL)
		return NULL;

	cdbw->hash_size = 1024;
	cdbw->hash = calloc(cdbw->hash_size, sizeof(*cdbw->hash));
	if (cdbw->hash == NULL) {
		free(cdbw);
		return NULL;
	}

	for (i = 0; i < cdbw->hash_size; ++i)
		SLIST_INIT(cdbw->hash + i);

	return cdbw;
}

int
cdbw_put(struct cdbw *cdbw, const void *key, size_t keylen,
    const void *data, size_t datalen)
{
	uint32_t idx;
	int rv;

	rv = cdbw_put_data(cdbw, data, datalen, &idx);
	if (rv)
		return rv;
	rv = cdbw_put_key(cdbw, key, keylen, idx);
	if (rv) {
		--cdbw->data_counter;
		free(cdbw->data_ptr[cdbw->data_counter]);
		cdbw->data_size -= datalen;
		return rv;
	}
	return 0;
}

int
cdbw_put_data(struct cdbw *cdbw, const void *data, size_t datalen,
    uint32_t *idx)
{

	if (cdbw->data_counter == max_data_counter)
		return -1;

	if (cdbw->data_size + datalen < cdbw->data_size ||
	    cdbw->data_size + datalen > 0xffffffffU)
		return -1; /* Overflow */

	if (cdbw->data_allocated == cdbw->data_counter) {
		void **new_data_ptr;
		size_t *new_data_len;
		size_t new_allocated;

		if (cdbw->data_allocated == 0)
			new_allocated = 256;
		else
			new_allocated = cdbw->data_allocated * 2;

		new_data_ptr = realloc(cdbw->data_ptr,
		    sizeof(*cdbw->data_ptr) * new_allocated);
		if (new_data_ptr == NULL)
			return -1;
		cdbw->data_ptr = new_data_ptr;

		new_data_len = realloc(cdbw->data_len,
		    sizeof(*cdbw->data_len) * new_allocated);
		if (new_data_len == NULL)
			return -1;
		cdbw->data_len = new_data_len;

		cdbw->data_allocated = new_allocated;
	}

	cdbw->data_ptr[cdbw->data_counter] = malloc(datalen);
	if (cdbw->data_ptr[cdbw->data_counter] == NULL)
		return -1;
	memcpy(cdbw->data_ptr[cdbw->data_counter], data, datalen);
	cdbw->data_len[cdbw->data_counter] = datalen;
	cdbw->data_size += datalen;
	*idx = cdbw->data_counter++;
	return 0;
}

int
cdbw_put_key(struct cdbw *cdbw, const void *key, size_t keylen, uint32_t idx)
{
	uint32_t hashes[3];
	struct key_hash_head *head, *head2, *new_head;
	struct key_hash *key_hash;
	size_t new_hash_size, i;

	if (idx >= cdbw->data_counter ||
	    cdbw->key_counter == max_data_counter)
		return -1;

	mi_vector_hash(key, keylen, 0, hashes);

	head = cdbw->hash + (hashes[0] & (cdbw->hash_size - 1));
	SLIST_FOREACH(key_hash, head, link) {
		if (key_hash->keylen != keylen)
			continue;
		if (key_hash->hashes[0] != hashes[0])
			continue;
		if (key_hash->hashes[1] != hashes[1])
			continue;
		if (key_hash->hashes[2] != hashes[2])
			continue;
		if (memcmp(key, key_hash->key, keylen))
			continue;
		return -1;
	}
	key_hash = malloc(sizeof(*key_hash));
	if (key_hash == NULL)
		return -1;
	key_hash->key = malloc(keylen);
	if (key_hash->key == NULL) {
		free(key_hash);
		return -1;
	}
	memcpy(key_hash->key, key, keylen);
	key_hash->hashes[0] = hashes[0];
	key_hash->hashes[1] = hashes[1];
	key_hash->hashes[2] = hashes[2];
	key_hash->keylen = keylen;
	key_hash->idx = idx;
	SLIST_INSERT_HEAD(head, key_hash, link);
	++cdbw->key_counter;

	if (cdbw->key_counter <= cdbw->hash_size)
		return 0;

	/* Try to resize the hash table, but ignore errors. */
	new_hash_size = cdbw->hash_size * 2;
	new_head = calloc(sizeof(*new_head), new_hash_size);
	if (new_head == NULL)
		return 0;

	head = &cdbw->hash[hashes[0] & (cdbw->hash_size - 1)];
	for (i = 0; i < new_hash_size; ++i)
		SLIST_INIT(new_head + i);

	for (i = 0; i < cdbw->hash_size; ++i) {
		head = cdbw->hash + i;

		while ((key_hash = SLIST_FIRST(head)) != NULL) {
			SLIST_REMOVE_HEAD(head, link);
			head2 = new_head +
			    (key_hash->hashes[0] & (new_hash_size - 1));
			SLIST_INSERT_HEAD(head2, key_hash, link);
		}
	}
	free(cdbw->hash);
	cdbw->hash_size = new_hash_size;
	cdbw->hash = new_head;

	return 0;
}

void
cdbw_close(struct cdbw *cdbw)
{
	struct key_hash_head *head;
	struct key_hash *key_hash;
	size_t i;

	for (i = 0; i < cdbw->hash_size; ++i) {
		head = cdbw->hash + i;
		while ((key_hash = SLIST_FIRST(head)) != NULL) {
			SLIST_REMOVE_HEAD(head, link);
			free(key_hash->key);
			free(key_hash);
		}
	}

	for (i = 0; i < cdbw->data_counter; ++i)
		free(cdbw->data_ptr[i]);
	free(cdbw->data_ptr);
	free(cdbw->data_len);
	free(cdbw->hash);
	free(cdbw);
}

uint32_t
cdbw_stable_seeder(void)
{
	return 0;
}

/*
 * For each vertex in the 3-graph, the incidence lists needs to be kept.
 * Avoid storing the full list by just XORing the indices of the still
 * incident edges and remember the number of such edges as that's all
 * the peeling computation needs. This is inspired by:
 *   Cache-Oblivious Peeling of Random Hypergraphs by Djamal Belazzougui,
 *   Paolo Boldi, Giuseppe Ottaviano, Rossano Venturini, and Sebastiano
 *   Vigna. https://arxiv.org/abs/1312.0526
 *
 * Unlike in the paper, we don't care about external storage and have
 * the edge list at hand all the time. As such, no ordering is necessary
 * and the vertices of the edge don't have to be copied.
 *
 * The core observation of the paper above is that for a degree of one,
 * the incident edge can be obtained directly.
 */
struct vertex {
	uint32_t degree;
	uint32_t edges;
};

struct edge {
	uint32_t vertices[3];
	uint32_t idx;
};

struct state {
	uint32_t data_entries;
	uint32_t entries;
	uint32_t keys;
	uint32_t seed;

	uint32_t *g;
	char *visited;

	struct vertex *vertices;
	struct edge *edges;
	uint32_t output_index;
	uint32_t *output_order;
};

/*
 * Add (delta == 1) or remove (delta == -1) the edge e
 * from the incidence lists.
 */
static inline void
change_edge(struct state *state, int delta, uint32_t e)
{
	int i;
	struct vertex *v;
	struct edge *e_ = &state->edges[e];

	for (i = 0; i < 3; ++i) {
		v = &state->vertices[e_->vertices[i]];
		v->edges ^= e;
		v->degree += delta;
	}
}

static inline void
remove_vertex(struct state *state, uint32_t v)
{
	struct vertex *v_ = &state->vertices[v];
	uint32_t e;

	if (v_->degree == 1) {
		e = v_->edges;
		state->output_order[--state->output_index] = e;
		change_edge(state, -1, e);
	}
}

static int
build_graph(struct cdbw *cdbw, struct state *state)
{
	struct key_hash_head *head;
	struct key_hash *key_hash;
	struct edge *e;
	uint32_t hashes[3];
	size_t i;
	int j;

	memset(state->vertices, 0, sizeof(*state->vertices) * state->entries);

	e = state->edges;

	for (i = 0; i < cdbw->hash_size; ++i) {
		head = &cdbw->hash[i];
		SLIST_FOREACH(key_hash, head, link) {
			mi_vector_hash(key_hash->key, key_hash->keylen,
			    state->seed, hashes);

			for (j = 0; j < 3; ++j)
				e->vertices[j] = hashes[j] % state->entries;

			if (e->vertices[0] == e->vertices[1])
				return -1;
			if (e->vertices[0] == e->vertices[2])
				return -1;
			if (e->vertices[1] == e->vertices[2])
				return -1;
			e->idx = key_hash->idx;
			++e;
		}
	}

	/*
	 * Do the edge processing separately as there is a good chance
	 * the degraded edge case above will happen; this avoid
	 *unnecessary  work.
	 */
	for (i = 0; i < state->keys; ++i)
		change_edge(state, 1, i);

	state->output_index = state->keys;
	for (i = 0; i < state->entries; ++i)
		remove_vertex(state, i);

	i = state->keys;
	while (i > 0 && i > state->output_index) {
		--i;
		e = state->edges + state->output_order[i];
		for (j = 0; j < 3; ++j)
			remove_vertex(state, e->vertices[j]);
	}

	return state->output_index == 0 ? 0 : -1;
}

static void
assign_nodes(struct state *state)
{
	struct edge *e;
	size_t i;

	uint32_t v0, v1, v2;

	for (i = 0; i < state->keys; ++i) {
		e = state->edges + state->output_order[i];
		if (!state->visited[e->vertices[0]]) {
			v0 = e->vertices[0];
			v1 = e->vertices[1];
			v2 = e->vertices[2];
		} else if (!state->visited[e->vertices[1]]) {
			v0 = e->vertices[1];
			v1 = e->vertices[0];
			v2 = e->vertices[2];
		} else {
			v0 = e->vertices[2];
			v1 = e->vertices[0];
			v2 = e->vertices[1];
		}
		state->g[v0] = (2 * state->data_entries + e->idx -
		    state->g[v1] - state->g[v2]) % state->data_entries;
		state->visited[v0] = 1;
		state->visited[v1] = 1;
		state->visited[v2] = 1;
	}
}

static size_t
compute_size(uint32_t size)
{
	if (size < 0x100)
		return 1;
	else if (size < 0x10000)
		return 2;
	else
		return 4;
}

#define COND_FLUSH_BUFFER(n) do { 				\
	if (cur_pos + (n) >= sizeof(buf)) {			\
		ret = write(fd, buf, cur_pos);			\
		if (ret == -1 || (size_t)ret != cur_pos)	\
			return -1;				\
		cur_pos = 0;					\
	}							\
} while (/* CONSTCOND */ 0)

static void
le32enc(uint8_t *buf, uint32_t num)
{
	buf[0] = num;
	buf[1] = num >> 8;
	buf[2] = num >> 16;
	buf[3] = num >> 24;
}

static int
print_hash(struct cdbw *cdbw, struct state *state, int fd, const char *descr)
{
	uint32_t data_size;
	uint8_t buf[90000];
	size_t i, size, size2, cur_pos;
	ssize_t ret;

	memcpy(buf, "NBCDB\n\0", 7);
	buf[7] = 1;
	strncpy((char *)buf + 8, descr, 16);
	le32enc(buf + 24, cdbw->data_size);
	le32enc(buf + 28, cdbw->data_counter);
	le32enc(buf + 32, state->entries);
	le32enc(buf + 36, state->seed);
	cur_pos = 40;

	size = compute_size(state->entries);
	for (i = 0; i < state->entries; ++i) {
		COND_FLUSH_BUFFER(4);
		le32enc(buf + cur_pos, state->g[i]);
		cur_pos += size;
	}
	size2 = compute_size(cdbw->data_size);
	size = size * state->entries % size2;
	if (size != 0) {
		size = size2 - size;
		COND_FLUSH_BUFFER(4);
		le32enc(buf + cur_pos, 0);
		cur_pos += size;
	}
	for (data_size = 0, i = 0; i < cdbw->data_counter; ++i) {
		COND_FLUSH_BUFFER(4);
		le32enc(buf + cur_pos, data_size);
		cur_pos += size2;
		data_size += cdbw->data_len[i];
	}
	COND_FLUSH_BUFFER(4);
	le32enc(buf + cur_pos, data_size);
	cur_pos += size2;

	for (i = 0; i < cdbw->data_counter; ++i) {
		COND_FLUSH_BUFFER(cdbw->data_len[i]);
		if (cdbw->data_len[i] < sizeof(buf)) {
			memcpy(buf + cur_pos, cdbw->data_ptr[i],
			    cdbw->data_len[i]);
			cur_pos += cdbw->data_len[i];
		} else {
			ret = write(fd, cdbw->data_ptr[i], cdbw->data_len[i]);
			if (ret == -1 || (size_t)ret != cdbw->data_len[i])
				return -1;
		}
	}
	if (cur_pos != 0) {
		ret = write(fd, buf, cur_pos);
		if (ret == -1 || (size_t)ret != cur_pos)
			return -1;
	}
	return 0;
}

int
cdbw_output(struct cdbw *cdbw, int fd, const char descr[16],
    uint32_t (*seedgen)(void))
{
	struct state state;
	int rv;

	if (cdbw->data_counter == 0 || cdbw->key_counter == 0) {
		state.entries = 0;
		state.seed = 0;
		print_hash(cdbw, &state, fd, descr);
		return 0;
	}

	if (seedgen == NULL)
		seedgen = cdbw_stable_seeder;

	rv = 0;

	state.keys = cdbw->key_counter;
	state.data_entries = cdbw->data_counter;
	state.entries = state.keys + (state.keys + 3) / 4;
	if (state.entries < 10)
		state.entries = 10;

#define	NALLOC(var, n)	var = calloc(sizeof(*var), n)
	NALLOC(state.g, state.entries);
	NALLOC(state.visited, state.entries);
	NALLOC(state.vertices, state.entries);
	NALLOC(state.edges, state.keys);
	NALLOC(state.output_order, state.keys);
#undef NALLOC

	if (state.g == NULL || state.visited == NULL || state.edges == NULL ||
	    state.vertices == NULL || state.output_order == NULL) {
		rv = -1;
		goto release;
	}

	state.seed = 0;
	do {
		++state.seed;
	} while (build_graph(cdbw, &state));

	assign_nodes(&state);
	rv = print_hash(cdbw, &state, fd, descr);

release:
	free(state.g);
	free(state.visited);
	free(state.vertices);
	free(state.edges);
	free(state.output_order);

	return rv;
}


code:
/*	$NetBSD: cdbw.h,v 1.2 2012/06/03 21:21:45 joerg Exp $	*/
/*-
 * Copyright (c) 2010 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Joerg Sonnenberger.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef	_CDBW_H
#define	_CDBW_H

#include <inttypes.h>
#include <stddef.h>

struct cdbw;

struct cdbw	*cdbw_open(void);
int		 cdbw_put(struct cdbw *, const void *, size_t,
    const void *, size_t);
int		 cdbw_put_data(struct cdbw *, const void *, size_t,
    uint32_t *);
int		 cdbw_put_key(struct cdbw *, const void *, size_t,
    uint32_t);
uint32_t	 cdbw_stable_seeder(void);
int		 cdbw_output(struct cdbw *, int, const char[16],
    uint32_t (*)(void));
void		 cdbw_close(struct cdbw *);

#endif /* _CDBW_H */


code:
/* $NetBSD: compile.c,v 1.26 2020/06/21 15:05:23 roy Exp $ */

/*
 * Copyright (c) 2009, 2010, 2011, 2020 The NetBSD Foundation, Inc.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Roy Marples.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif

#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <term_private.h>
#include <term.h>

static void
dowarn(int flags, const char *fmt, ...)
{
	va_list va;

	errno = EINVAL;
	if (flags & TIC_WARNING) {
		va_start(va, fmt);
		vwarnx(fmt, va);
		va_end(va);
	}
}

#ifdef TERMINFO_COMPAT
int
_ti_promote(TIC *tic)
{
	char *obuf, type, flag, *buf, *delim, *name, *nbuf;
	const char *cap, *code, *str;
	size_t n, entries, strl;
	uint16_t ind;
	int num, ortype, error = 0;

	ortype = tic->rtype;
	tic->rtype = TERMINFO_RTYPE;
	obuf = tic->name;
	tic->name = _ti_getname(tic->rtype, tic->name);
	if (tic->name == NULL) {
		warn("_ti_getname");
		tic->name = obuf;
		return -1;
	}
	free(obuf);

	n = 0;
	obuf = buf = tic->alias;
	tic->alias = NULL;
	while (buf != NULL) {
		delim = strchr(buf, '|');
		if (delim != NULL)
			*delim++ = '\0';
		name = _ti_getname(tic->rtype, buf);
		strl = strlen(name) + 1;
		nbuf = realloc(tic->alias, n + strl);
		if (nbuf == NULL) {
			free(name);
			return -1;
		}
		tic->alias = nbuf;
		memcpy(tic->alias + n, name, strl);
		n += strl;
		free(name);
		buf = delim;
	}
	free(obuf);

	obuf = tic->nums.buf;
	cap = obuf;
	entries = tic->nums.entries;
	tic->nums.buf = NULL;
	tic->nums.entries = tic->nums.buflen = tic->nums.bufpos = 0;
	for (n = entries; n > 0; n--) {
		ind = _ti_decode_16(&cap);
		num = _ti_decode_num(&cap, ortype);
		if (VALID_NUMERIC(num) &&
		    !_ti_encode_buf_id_num(&tic->nums, ind, num,
		    _ti_numsize(tic)))
		{
			warn("promote num");
			error = -1;
			break;
		}
	}
	free(obuf);

	obuf = tic->extras.buf;
	cap = obuf;
	entries = tic->extras.entries;
	tic->extras.buf = NULL;
	tic->extras.entries = tic->extras.buflen = tic->extras.bufpos = 0;
	for (n = entries; n > 0; n--) {
		num = _ti_decode_16(&cap);
		flag = 0; /* satisfy gcc, won't be used for non flag types */
		str = NULL; /* satisfy gcc, won't be used as strl is 0 */
		strl = 0;
		code = cap;
		cap += num;
		type = *cap++;
		switch (type) {
		case 'f':
			flag = *cap++;
			break;
		case 'n':
			num = _ti_decode_num(&cap, ortype);
			break;
		case 's':
			strl = _ti_decode_16(&cap);
			str = cap;
			cap += strl;
			break;
		default:
			errno = EINVAL;
			break;
		}
		if (!_ti_store_extra(tic, 0, code, type, flag, num,
		    str, strl, TIC_EXTRA))
		{
			error = -1;
			break;
		}
	}
	free(obuf);

	return error;
}
#endif

char *
_ti_grow_tbuf(TBUF *tbuf, size_t len)
{
	char *buf;
	size_t l;

	assert(tbuf != NULL);

	l = tbuf->bufpos + len;
	if (l > tbuf->buflen) {
		if (tbuf->buflen == 0)
			buf = malloc(l);
		else
			buf = realloc(tbuf->buf, l);
		if (buf == NULL)
			return NULL;
		tbuf->buf = buf;
		tbuf->buflen = l;
	}
	return tbuf->buf;
}

const char *
_ti_find_cap(TIC *tic, TBUF *tbuf, char type, short ind)
{
	size_t n;
	uint16_t num;
	const char *cap;

	assert(tbuf != NULL);

	cap = tbuf->buf;
	for (n = tbuf->entries; n > 0; n--) {
		num = _ti_decode_16(&cap);
		if ((short)num == ind)
			return cap;
		switch (type) {
		case 'f':
			cap++;
			break;
		case 'n':
			cap += _ti_numsize(tic);
			break;
		case 's':
			num = _ti_decode_16(&cap);
			cap += num;
			break;
		}
	}

	errno = ESRCH;
	return NULL;
}

const char *
_ti_find_extra(TIC *tic, TBUF *tbuf, const char *code)
{
	size_t n;
	uint16_t num;
	const char *cap;

	assert(tbuf != NULL);
	assert(code != NULL);

	cap = tbuf->buf;
	for (n = tbuf->entries; n > 0; n--) {
		num = _ti_decode_16(&cap);
		if (strcmp(cap, code) == 0)
			return cap + num;
		cap += num;
		switch (*cap++) {
		case 'f':
			cap++;
			break;
		case 'n':
			cap += _ti_numsize(tic);
			break;
		case 's':
			num = _ti_decode_16(&cap);
			cap += num;
			break;
		}
	}

	errno = ESRCH;
	return NULL;
}

char *
_ti_getname(int rtype, const char *orig)
{
#ifdef TERMINFO_COMPAT
	const char *delim;
	char *name;
	const char *verstr;
	size_t diff, vlen;

	switch (rtype) {
	case TERMINFO_RTYPE:
		verstr = TERMINFO_VDELIMSTR "v3";
		break;
	case TERMINFO_RTYPE_O1:
		verstr = "";
		break;
	default:
		errno = EINVAL;
		return NULL;
	}

	delim = orig;
	while (*delim != '\0' && *delim != TERMINFO_VDELIM)
		delim++;
	diff = delim - orig;
	vlen = strlen(verstr);
	name = malloc(diff + vlen + 1);
	if (name == NULL)
		return NULL;

	memcpy(name, orig, diff);
	memcpy(name + diff, verstr, vlen + 1);
	return name;
#else
	return strdup(orig);
#endif
}

size_t
_ti_store_extra(TIC *tic, int wrn, const char *id, char type, char flag,
    int num, const char *str, size_t strl, int flags)
{
	size_t l, capl;

	assert(tic != NULL);

	if (strcmp(id, "use") != 0) {
		if (_ti_find_extra(tic, &tic->extras, id) != NULL)
			return 0;
		if (!(flags & TIC_EXTRA)) {
			if (wrn != 0)
				dowarn(flags, "%s: %s: unknown capability",
				    tic->name, id);
			return 0;
		}
	}

	l = strlen(id) + 1;
	if (l > UINT16_MAX) {
		dowarn(flags, "%s: %s: cap name is too long", tic->name, id);
		return 0;
	}

	capl = sizeof(uint16_t) + l + 1;
	switch (type) {
	case 'f':
		capl++;
		break;
	case 'n':
		capl += _ti_numsize(tic);
		break;
	case 's':
		capl += sizeof(uint16_t) + strl;
		break;
	}

	if (!_ti_grow_tbuf(&tic->extras, capl))
		return 0;
	_ti_encode_buf_count_str(&tic->extras, id, l);
	tic->extras.buf[tic->extras.bufpos++] = type;
	switch (type) {
	case 'f':
		tic->extras.buf[tic->extras.bufpos++] = flag;
		break;
	case 'n':
		_ti_encode_buf_num(&tic->extras, num, tic->rtype);
		break;
	case 's':
		_ti_encode_buf_count_str(&tic->extras, str, strl);
		break;
	}
	tic->extras.entries++;
	return 1;
}

static void
_ti_encode_buf(char **cap, const TBUF *buf)
{
	if (buf->entries == 0) {
		_ti_encode_16(cap, 0);
	} else {
		_ti_encode_16(cap, buf->bufpos + sizeof(uint16_t));
		_ti_encode_16(cap, buf->entries);
		_ti_encode_str(cap, buf->buf, buf->bufpos);
	}
}

ssize_t
_ti_flatten(uint8_t **buf, const TIC *tic)
{
	size_t buflen, len, alen, dlen;
	char *cap;

	assert(buf != NULL);
	assert(tic != NULL);

	len = strlen(tic->name) + 1;
	if (tic->alias == NULL)
		alen = 0;
	else
		alen = strlen(tic->alias) + 1;
	if (tic->desc == NULL)
		dlen = 0;
	else
		dlen = strlen(tic->desc) + 1;

	buflen = sizeof(char) +
	    sizeof(uint16_t) + len +
	    sizeof(uint16_t) + alen +
	    sizeof(uint16_t) + dlen +
	    (sizeof(uint16_t) * 2) + tic->flags.bufpos +
	    (sizeof(uint16_t) * 2) + tic->nums.bufpos +
	    (sizeof(uint16_t) * 2) + tic->strs.bufpos +
	    (sizeof(uint16_t) * 2) + tic->extras.bufpos;

	*buf = malloc(buflen);
	if (*buf == NULL)
		return -1;

	cap = (char *)*buf;
	*cap++ = tic->rtype;

	_ti_encode_count_str(&cap, tic->name, len);
	_ti_encode_count_str(&cap, tic->alias, alen);
	_ti_encode_count_str(&cap, tic->desc, dlen);

	_ti_encode_buf(&cap, &tic->flags);

	_ti_encode_buf(&cap, &tic->nums);
	_ti_encode_buf(&cap, &tic->strs);
	_ti_encode_buf(&cap, &tic->extras);

	return (uint8_t *)cap - *buf;
}

static int
encode_string(const char *term, const char *cap, TBUF *tbuf, const char *str,
    int flags)
{
	int slash, i, num;
	char ch, *p, *s, last;

	if (_ti_grow_tbuf(tbuf, strlen(str) + 1) == NULL)
		return -1;
	p = s = tbuf->buf + tbuf->bufpos;
	slash = 0;
	last = '\0';
	/* Convert escape codes */
	while ((ch = *str++) != '\0') {
		if (ch == '\n') {
			/* Following a newline, strip leading whitespace from
			 * capability strings. */
			while (isspace((unsigned char)*str))
				str++;
			continue;
		}
		if (slash == 0 && ch == '\\') {
			slash = 1;
			continue;
		}
		if (slash == 0) {
			if (last != '%' && ch == '^') {
				ch = *str++;
				if (((unsigned char)ch) >= 128)
					dowarn(flags,
					    "%s: %s: illegal ^ character",
					    term, cap);
				if (ch == '\0')
					break;
				if (ch == '?')
					ch = '\177';
				else if ((ch &= 037) == 0)
					ch = (char)128;
			} else if (!isprint((unsigned char)ch))
				dowarn(flags,
				    "%s: %s: unprintable character",
				    term, cap);
			*p++ = ch;
			last = ch;
			continue;
		}
		slash = 0;
		if (ch >= '0' && ch <= '7') {
			num = ch - '0';
			for (i = 0; i < 2; i++) {
				if (*str < '0' || *str > '7') {
					if (isdigit((unsigned char)*str))
						dowarn(flags,
						    "%s: %s: non octal"
						    " digit", term, cap);
					else
						break;
				}
				num = num * 8 + *str++ - '0';
			}
			if (num == 0)
				num = 0200;
			*p++ = (char)num;
			continue;
		}
		switch (ch) {
		case 'a':
			*p++ = '\a';
			break;
		case 'b':
			*p++ = '\b';
			break;
		case 'e': /* FALLTHROUGH */
		case 'E':
			*p++ = '\033';
			break;
		case 'f':
			*p++ = '\014';
			break;
		case 'l': /* FALLTHROUGH */
		case 'n':
			*p++ = '\n';
			break;
		case 'r':
			*p++ = '\r';
			break;
		case 's':
			*p++ = ' ';
			break;
		case 't':
			*p++ = '\t';
			break;
		default:
			/* We should warn here */
		case '^':
		case ',':
		case ':':
		case '|':
			*p++ = ch;
			break;
		}
		last = ch;
	}
	*p++ = '\0';
	tbuf->bufpos += (size_t)(p - s);
	return 0;
}

char *
_ti_get_token(char **cap, char sep)
{
	char esc, *token;

	while (isspace((unsigned char)**cap))
		(*cap)++;
	if (**cap == '\0')
		return NULL;

	/* We can't use stresep(3) as ^ we need two escape chars */
	esc = '\0';
	for (token = *cap;
	     **cap != '\0' && (esc != '\0' || **cap != sep);
	     (*cap)++)
	{
		if (esc == '\0') {
			if (**cap == '\\' || **cap == '^')
				esc = **cap;
		} else {
			/* termcap /E/ is valid */
			if (sep == ':' && esc == '\\' && **cap == 'E')
				esc = 'x';
			else
				esc = '\0';
		}
	}

	if (**cap != '\0')
		*(*cap)++ = '\0';

	return token;
}

int
_ti_encode_buf_id_num(TBUF *tbuf, int ind, int num, size_t len)
{
	if (!_ti_grow_tbuf(tbuf, sizeof(uint16_t) + len))
		return 0;
	_ti_encode_buf_16(tbuf, ind);
	if (len == sizeof(uint32_t))
		_ti_encode_buf_32(tbuf, (uint32_t)num);
	else
		_ti_encode_buf_16(tbuf, (uint16_t)num);
	tbuf->entries++;
	return 1;
}

int
_ti_encode_buf_id_count_str(TBUF *tbuf, int ind, const void *buf, size_t len)
{
	if (!_ti_grow_tbuf(tbuf, 2 * sizeof(uint16_t) + len))
		return 0;
	_ti_encode_buf_16(tbuf, ind);
	_ti_encode_buf_count_str(tbuf, buf, len);
	tbuf->entries++;
	return 1;
}

int
_ti_encode_buf_id_flags(TBUF *tbuf, int ind, int flag)
{
	if (!_ti_grow_tbuf(tbuf, sizeof(uint16_t) + 1))
		return 0;
	_ti_encode_buf_16(tbuf, ind);
	tbuf->buf[tbuf->bufpos++] = flag;
	tbuf->entries++;
	return 1;
}

TIC *
_ti_compile(char *cap, int flags)
{
	char *token, *p, *e, *name, *desc, *alias;
	signed char flag;
	long cnum;
	short ind;
	int num;
	size_t len;
	TBUF buf;
	TIC *tic;

	assert(cap != NULL);

	name = _ti_get_token(&cap, ',');
	if (name == NULL) {
		dowarn(flags, "no separator found: %s", cap);
		return NULL;
	}
	desc = strrchr(name, '|');
	if (desc != NULL)
		*desc++ = '\0';
	alias = strchr(name, '|');
	if (alias != NULL)
		*alias++ = '\0';

	if (strlen(name) > UINT16_MAX - 1) {
		dowarn(flags, "%s: name too long", name);
		return NULL;
	}
	if (desc != NULL && strlen(desc) > UINT16_MAX - 1) {
		dowarn(flags, "%s: description too long: %s", name, desc);
		return NULL;
	}
	if (alias != NULL && strlen(alias) > UINT16_MAX - 1) {
		dowarn(flags, "%s: alias too long: %s", name, alias);
		return NULL;
	}

	tic = calloc(sizeof(*tic), 1);
	if (tic == NULL)
		return NULL;

#ifdef TERMINFO_COMPAT
	tic->rtype = TERMINFO_RTYPE_O1; /* will promote if needed */
#else
	tic->rtype = TERMINFO_RTYPE;
#endif
	buf.buf = NULL;
	buf.buflen = 0;

	tic->name = _ti_getname(tic->rtype, name);
	if (tic->name == NULL)
		goto error;
	if (alias != NULL && flags & TIC_ALIAS) {
		tic->alias = _ti_getname(tic->rtype, alias);
		if (tic->alias == NULL)
			goto error;
	}
	if (desc != NULL && flags & TIC_DESCRIPTION) {
		tic->desc = strdup(desc);
		if (tic->desc == NULL)
			goto error;
	}

	for (token = _ti_get_token(&cap, ',');
	     token != NULL && *token != '\0';
	     token = _ti_get_token(&cap, ','))
	{
		/* Skip commented caps */
		if (!(flags & TIC_COMMENT) && token[0] == '.')
			continue;

		/* Obsolete entries */
		if (token[0] == 'O' && token[1] == 'T') {
			if (!(flags & TIC_EXTRA))
				continue;
			token += 2;
		}

		/* str cap */
		p = strchr(token, '=');
		if (p != NULL) {
			*p++ = '\0';
			/* Don't use the string if we already have it */
			ind = (short)_ti_strindex(token);
			if (ind != -1 &&
			    _ti_find_cap(tic, &tic->strs, 's', ind) != NULL)
				continue;

			/* Encode the string to our scratch buffer */
			buf.bufpos = 0;
			if (encode_string(tic->name, token,
				&buf, p, flags) == -1)
				goto error;
			if (buf.bufpos > UINT16_MAX - 1) {
				dowarn(flags, "%s: %s: string is too long",
				    tic->name, token);
				continue;
			}
			if (!VALID_STRING(buf.buf)) {
				dowarn(flags, "%s: %s: invalid string",
				    tic->name, token);
				continue;
			}

			if (ind == -1) {
				if (!_ti_store_extra(tic, 1, token, 's', -1, -2,
				    buf.buf, buf.bufpos, flags))
					goto error;
			} else {
				if (!_ti_encode_buf_id_count_str(&tic->strs,
				    ind, buf.buf, buf.bufpos))
					goto error;
			}
			continue;
		}

		/* num cap */
		p = strchr(token, '#');
		if (p != NULL) {
			*p++ = '\0';
			/* Don't use the number if we already have it */
			ind = (short)_ti_numindex(token);
			if (ind != -1 &&
			    _ti_find_cap(tic, &tic->nums, 'n', ind) != NULL)
				continue;

			cnum = strtol(p, &e, 0);
			if (*e != '\0') {
				dowarn(flags, "%s: %s: not a number",
				    tic->name, token);
				continue;
			}
			if (!VALID_NUMERIC(cnum) || cnum > INT32_MAX) {
				dowarn(flags, "%s: %s: number %ld out of range",
				    tic->name, token, cnum);
				continue;
			}
			if (cnum > INT16_MAX) {
				if (flags & TIC_COMPAT_V1)
					cnum = INT16_MAX;
#ifdef TERMINFO_COMPAT
				else if (tic->rtype == TERMINFO_RTYPE_O1)
					if (_ti_promote(tic) == -1)
						goto error;
#endif
			}

			num = (int)cnum;
			if (ind == -1) {
				if (!_ti_store_extra(tic, 1, token, 'n', -1,
				    num, NULL, 0, flags))
					goto error;
			} else {
				if (!_ti_encode_buf_id_num(&tic->nums,
				    ind, num, _ti_numsize(tic)))
					    goto error;
			}
			continue;
		}

		flag = 1;
		len = strlen(token) - 1;
		if (token[len] == '@') {
			flag = CANCELLED_BOOLEAN;
			token[len] = '\0';
		}
		ind = (short)_ti_flagindex(token);
		if (ind == -1 && flag == CANCELLED_BOOLEAN) {
			if ((ind = (short)_ti_numindex(token)) != -1) {
				if (_ti_find_cap(tic, &tic->nums, 'n', ind)
				    != NULL)
					continue;
				if (!_ti_encode_buf_id_num(&tic->nums, ind,
				    CANCELLED_NUMERIC, _ti_numsize(tic)))
					goto error;
				continue;
			} else if ((ind = (short)_ti_strindex(token)) != -1) {
				if (_ti_find_cap(tic, &tic->strs, 's', ind)
				    != NULL)
					continue;
				if (!_ti_encode_buf_id_num(
				    &tic->strs, ind, 0, sizeof(uint16_t)))
					goto error;
				continue;
			}
		}
		if (ind == -1) {
			if (!_ti_store_extra(tic, 1, token, 'f', flag, 0, NULL,
			    0, flags))
				goto error;
		} else if (_ti_find_cap(tic, &tic->flags, 'f', ind) == NULL) {
			if (!_ti_encode_buf_id_flags(&tic->flags, ind, flag))
				goto error;
		}
	}

	free(buf.buf);
	return tic;

error:
	free(buf.buf);
	_ti_freetic(tic);
	return NULL;
}

void
_ti_freetic(TIC *tic)
{

	if (tic != NULL) {
		free(tic->name);
		free(tic->alias);
		free(tic->desc);
		free(tic->extras.buf);
		free(tic->flags.buf);
		free(tic->nums.buf);
		free(tic->strs.buf);
		free(tic);
	}
}