Skip to content

Instantly share code, notes, and snippets.

@odzhan
Last active February 18, 2024 20:57
Show Gist options
  • Save odzhan/70817fc2bd92a0f38859ea153eed193b to your computer and use it in GitHub Desktop.
Save odzhan/70817fc2bd92a0f38859ea153eed193b to your computer and use it in GitHub Desktop.
Xpress Compression Utility
/**
BSD 3-Clause License
Copyright (c) 2019 Odzhan. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
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 HOLDER 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.
*/
#include <Windows.h>
#include <stdio.h>
#include <inttypes.h>
#include <limits.h>
#include <compressapi.h>
#define XPRESS_NONE 0
#define XPRESS_PACK 1
#define XPRESS_UNPACK 2
#pragma comment(lib, "cabinet.lib")
static uint32_t file_diff(uint32_t new_len, uint32_t old_len) {
if (new_len <= UINT_MAX / 100) {
new_len *= 100;
} else {
old_len /= 100;
}
if (old_len == 0) {
old_len = 1;
}
return (100 - (new_len / old_len));
}
VOID xstrerror (PCHAR fmt, ...){
PCHAR error=NULL;
va_list arglist;
CHAR buffer[1024];
DWORD dwError=GetLastError();
va_start(arglist, fmt);
_vsnprintf(buffer, ARRAYSIZE(buffer), fmt, arglist);
va_end (arglist);
if (FormatMessage (
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&error, 0, NULL))
{
printf(" [ %s : %s\n", buffer, error);
LocalFree (error);
} else {
printf(" [ %s error : %08lX\n", buffer, dwError);
}
}
DWORD CompressBuffer(DWORD engine, LPVOID inbuf, DWORD inlen, HANDLE outfile) {
COMPRESSOR_HANDLE ch = NULL;
BOOL r;
SIZE_T outlen, len;
LPVOID outbuf;
DWORD wr;
// Create a compressor
r = CreateCompressor(engine, NULL, &ch);
if(r) {
// Query compressed buffer size.
Compress(ch, inbuf, inlen, NULL, 0, &len);
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
// allocate memory for compressed data
outbuf = malloc(len);
if(outbuf != NULL) {
// Compress data and write data to outbuf.
r = Compress(ch, inbuf, inlen, outbuf, len, &outlen);
// if compressed ok, write to file
if(r) {
WriteFile(outfile, outbuf, outlen, &wr, NULL);
FlushFileBuffers(outfile);
} else xstrerror("Compress()");
free(outbuf);
} else xstrerror("malloc()");
} else xstrerror("Compress()");
CloseCompressor(ch);
} else xstrerror("CreateCompressor()");
return r;
}
DWORD DecompressBuffer(DWORD engine, LPVOID inbuf, DWORD inlen, HANDLE outfile) {
DECOMPRESSOR_HANDLE dh = NULL;
BOOL r;
SIZE_T outlen, len;
LPVOID outbuf;
DWORD wr;
// Create a decompressor
r = CreateDecompressor(engine, NULL, &dh);
if(r) {
// Query Decompressed buffer size.
Decompress(dh, inbuf, inlen, NULL, 0, &len);
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
// allocate memory for decompressed data
outbuf = malloc(len);
if(outbuf != NULL) {
// Decompress data and write data to outbuf.
r = Decompress(dh, inbuf, inlen, outbuf, len, &outlen);
// if decompressed ok, write to file
if(r) {
WriteFile(outfile, outbuf, outlen, &wr, NULL);
FlushFileBuffers(outfile);
} else xstrerror("Decompress()");
free(outbuf);
} else xstrerror("malloc()");
} else xstrerror("Decompress()");
CloseDecompressor(dh);
} else xstrerror("CreateDecompressor()");
return r;
}
// map a file for reading
DWORD CompressOrDecompress(DWORD engine, BOOL compress, const char *infile, const char *outfile) {
HANDLE fin, fout, map;
LPVOID inbuf;
DWORD inlen, outlen, err;
LARGE_INTEGER fs;
// open input file for reading
fin = CreateFile(infile, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
// error? exit
if(fin == INVALID_HANDLE_VALUE) {
xstrerror("CreateFile");
return GetLastError();
}
// read the file size
GetFileSizeEx(fin, &fs);
if(fs.QuadPart == 0) {
printf("file is empty\n");
return 0;
}
inlen = fs.LowPart;
// create file mapping
map = CreateFileMapping(fin, NULL, PAGE_READONLY, 0, 0, NULL);
if(map != NULL) {
// map a view of the file
inbuf = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if(inbuf != NULL) {
// open output file for writing
fout = CreateFile(outfile, GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
// if file opened
if(fout != INVALID_HANDLE_VALUE) {
// compress?
if(compress == XPRESS_PACK) {
err = CompressBuffer(engine, inbuf, inlen, fout);
} else {
err = DecompressBuffer(engine, inbuf, inlen, fout);
}
GetFileSizeEx(fout, &fs);
outlen = fs.LowPart;
CloseHandle(fout);
} else {
xstrerror("CreateFile");
}
// unmap view
UnmapViewOfFile(inbuf);
} else {
xstrerror("MapViewOfFile");
}
// close mapping
CloseHandle(map);
} else {
xstrerror("CreateFileMapping");
}
// close input file
CloseHandle(fin);
// return the ratio
return (compress == XPRESS_PACK) ? file_diff(outlen, inlen) : file_diff(inlen, outlen);
}
static char* get_param (int argc, char *argv[], int *i) {
int n = *i;
if (argv[n][2] != 0) {
return &argv[n][2];
}
if ((n+1) < argc) {
*i = n + 1;
return argv[n+1];
}
printf(" [ %c%c requires parameter\n", argv[n][0], argv[n][1]);
exit (0);
}
void usage(void) {
printf(" usage: xpress [options] -i <infile> -o <outfile>\n");
printf(" -c Compress\n");
printf(" -d Decompress\n");
printf(" -i <infile> Input file\n");
printf(" -o <outfile> Output file\n");
printf(" -e <engine> Compression engine. 2=MSZip, 3=Xpress, 4=Xpress Huffman, 5=LZMS\n\n");
exit(-1);
}
int main(int argc, char *argv[]) {
DWORD engine = COMPRESS_ALGORITHM_XPRESS_HUFF;
DWORD ratio, i, compress = XPRESS_NONE;
PCHAR infile = NULL, outfile = NULL;
printf("\n");
printf(" [ Xpress compression utility v0.1\n");
printf(" [ Copyright (c) 2019 Odzhan\n\n");
if(argc < 3) {
usage();
}
// for each argument
for(i=1; i<argc; i++) {
// is this a switch?
if(argv[i][0] == '/' || argv[i][0] == '-') {
switch(argv[i][1]) {
// compress?
case 'c':
compress = XPRESS_PACK;
break;
// decompress?
case 'd':
compress = XPRESS_UNPACK;
break;
// input file
case 'i':
infile = get_param(argc, argv, &i);
break;
// output file
case 'o':
outfile = get_param(argc, argv, &i);
break;
// compression engine
case 'e':
engine = atoi(get_param(argc, argv, &i));
break;
default:
usage();
}
} else {
usage();
}
}
// no input?
if(infile == NULL) {
printf(" [ no input file specified.\n");
return 0;
}
// no output?
if(outfile == NULL) {
printf(" [ no output file specified.\n");
return 0;
}
// invalid engine?
if(engine != COMPRESS_ALGORITHM_MSZIP &&
engine != COMPRESS_ALGORITHM_XPRESS &&
engine != COMPRESS_ALGORITHM_XPRESS_HUFF &&
engine != COMPRESS_ALGORITHM_LZMS)
{
printf(" [ invalid engine specified.\n");
return 0;
}
// no mode selected?
if(compress == 0) {
printf(" [ use -c for compression or -d for decompression.\n");
return 0;
}
printf(" [ %s %s to %s using %s\n",
compress == XPRESS_PACK ? "compressing" : "decompressing",
infile, outfile,
engine == COMPRESS_ALGORITHM_MSZIP ? "MSZip" :
engine == COMPRESS_ALGORITHM_XPRESS ? "Xpress" :
engine == COMPRESS_ALGORITHM_XPRESS_HUFF ? "Xpress Huffman" : "LZMS");
// 1=compress, 2=decompress
ratio = CompressOrDecompress(engine, compress, infile, outfile);
printf(" [ file size %s by %"PRId32"%%\n",
compress == XPRESS_PACK ? "reduced" : "increased", ratio);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment