stringcompression.txt
snippets · 1.6 KB · 2010-03-30
String compression: compress and decompress strings in memory (note on how to free).
Download « Back to the snippets list
/*
This code will allow you to compress an decompress strings into memory.
It is important to note how you must free.
string_compress() will not free what you pass to it. It will return a malloced
string that you are responsable for.
string_uncompress() will not free what you pass to it. It will return a static
buffer that does not need be freed. In fact, if you do it will crash.
This is only useful for large strings like descriptions. It has a good compression
rate. If you are interested in saving ram on your text based game you might consider
it. I added it into my mud for rooms and character descriptions. It has saved a few megs.
If you want to talk to me about compression send me a message on aim at jeffreybasurto or
email me at auadmin@feltain.org.
Thanks,
Runter
*/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "merc.h"
#include "zlib.h"
char *string_compress(char *string) {
int len = strlen(string)+1, comprLen = MSL+MSL;
static char compr[MSL+MSL];
char *ptr;
int i;
memset(compr, 0, MSL+MSL);
compress((Bytef*)compr, (uLong *)&comprLen, (const Bytef*)string, len);
ptr = (char *)malloc(comprLen+1);
for(i = 0;i < comprLen;++i) {
ptr[i] = compr[i];
}
ptr[i] = 0;
return ptr;
}
char *string_uncompress(char *string) {
int comprLen = MSL+MSL;
char *ptr;
static char uncompr[MSL+MSL];
int uncomprLen = MSL+MSL;
memset(uncompr, 0, MSL+MSL);
uncompress((Bytef*) uncompr, (uLong*)&uncomprLen, (Bytef*)string, comprLen);
return uncompr;
}