From 126fa84b8591c3b285b7f598089451aa22447f10 Mon Sep 17 00:00:00 2001 From: FreeArtMan Date: Sat, 20 May 2017 13:43:49 +0100 Subject: Moved commands to seperate directory, moved external sources to seperate directory, updated Makefile with auto include and auto compile features --- Makefile | 78 ++-- cmd/cmd_botu.c | 46 ++ cmd/cmd_botu.h | 17 + cmd/cmd_cmd.c | 20 + cmd/cmd_cmd.h | 14 + cmd/cmd_cookie.c | 19 + cmd/cmd_cookie.h | 11 + cmd/cmd_date.c | 13 + cmd/cmd_date.h | 11 + cmd/cmd_fir.c | 621 +++++++++++++++++++++++++ cmd/cmd_fir.h | 15 + cmd/cmd_fir1p.c | 94 ++++ cmd/cmd_fir1p.h | 13 + cmd/cmd_loadavg.c | 28 ++ cmd/cmd_loadavg.h | 11 + cmd/cmd_ping.c | 13 + cmd/cmd_ping.h | 11 + cmd/cmd_rand.c | 19 + cmd/cmd_rand.h | 12 + cmd/cmd_rand_libc.c | 50 ++ cmd/cmd_rand_libc.h | 13 + cmd/cmd_rusage.c | 34 ++ cmd/cmd_rusage.h | 14 + cmd/cmd_sha1.c | 41 ++ cmd/cmd_sha1.h | 12 + cmd/cmd_sum.c | 0 cmd/cmd_sum.h | 0 cmd/cmd_uptime.c | 34 ++ cmd/cmd_uptime.h | 11 + cmd/cmd_version.c | 16 + cmd/cmd_version.h | 17 + cmd_botu.c | 46 -- cmd_botu.h | 17 - cmd_cmd.c | 20 - cmd_cmd.h | 14 - cmd_cookie.c | 19 - cmd_cookie.h | 11 - cmd_date.c | 13 - cmd_date.h | 11 - cmd_fir.c | 621 ------------------------- cmd_fir.h | 15 - cmd_fir1p.c | 94 ---- cmd_fir1p.h | 13 - cmd_loadavg.c | 28 -- cmd_loadavg.h | 11 - cmd_ping.c | 13 - cmd_ping.h | 11 - cmd_rand.c | 19 - cmd_rand.h | 12 - cmd_rand_libc.c | 50 -- cmd_rand_libc.h | 13 - cmd_rusage.c | 34 -- cmd_rusage.h | 14 - cmd_sha1.c | 41 -- cmd_sha1.h | 12 - cmd_uptime.c | 34 -- cmd_uptime.h | 11 - cmd_version.c | 16 - cmd_version.h | 17 - config_all_cmds.h | 18 + config_cmds.h | 15 +- extlibs/sds.c | 1277 +++++++++++++++++++++++++++++++++++++++++++++++++++ extlibs/sds.h | 273 +++++++++++ extlibs/sdsalloc.h | 42 ++ extlibs/sha1.c | 296 ++++++++++++ extlibs/sha1.h | 44 ++ sds.c | 1277 --------------------------------------------------- sds.h | 273 ----------- sdsalloc.h | 42 -- sha1.c | 296 ------------ sha1.h | 44 -- 71 files changed, 3226 insertions(+), 3209 deletions(-) create mode 100644 cmd/cmd_botu.c create mode 100644 cmd/cmd_botu.h create mode 100644 cmd/cmd_cmd.c create mode 100644 cmd/cmd_cmd.h create mode 100644 cmd/cmd_cookie.c create mode 100644 cmd/cmd_cookie.h create mode 100644 cmd/cmd_date.c create mode 100644 cmd/cmd_date.h create mode 100644 cmd/cmd_fir.c create mode 100644 cmd/cmd_fir.h create mode 100644 cmd/cmd_fir1p.c create mode 100644 cmd/cmd_fir1p.h create mode 100644 cmd/cmd_loadavg.c create mode 100644 cmd/cmd_loadavg.h create mode 100644 cmd/cmd_ping.c create mode 100644 cmd/cmd_ping.h create mode 100644 cmd/cmd_rand.c create mode 100644 cmd/cmd_rand.h create mode 100644 cmd/cmd_rand_libc.c create mode 100644 cmd/cmd_rand_libc.h create mode 100644 cmd/cmd_rusage.c create mode 100644 cmd/cmd_rusage.h create mode 100644 cmd/cmd_sha1.c create mode 100644 cmd/cmd_sha1.h create mode 100644 cmd/cmd_sum.c create mode 100644 cmd/cmd_sum.h create mode 100644 cmd/cmd_uptime.c create mode 100644 cmd/cmd_uptime.h create mode 100644 cmd/cmd_version.c create mode 100644 cmd/cmd_version.h delete mode 100644 cmd_botu.c delete mode 100644 cmd_botu.h delete mode 100644 cmd_cmd.c delete mode 100644 cmd_cmd.h delete mode 100644 cmd_cookie.c delete mode 100644 cmd_cookie.h delete mode 100644 cmd_date.c delete mode 100644 cmd_date.h delete mode 100644 cmd_fir.c delete mode 100644 cmd_fir.h delete mode 100644 cmd_fir1p.c delete mode 100644 cmd_fir1p.h delete mode 100644 cmd_loadavg.c delete mode 100644 cmd_loadavg.h delete mode 100644 cmd_ping.c delete mode 100644 cmd_ping.h delete mode 100644 cmd_rand.c delete mode 100644 cmd_rand.h delete mode 100644 cmd_rand_libc.c delete mode 100644 cmd_rand_libc.h delete mode 100644 cmd_rusage.c delete mode 100644 cmd_rusage.h delete mode 100644 cmd_sha1.c delete mode 100644 cmd_sha1.h delete mode 100644 cmd_uptime.c delete mode 100644 cmd_uptime.h delete mode 100644 cmd_version.c delete mode 100644 cmd_version.h create mode 100644 config_all_cmds.h create mode 100644 extlibs/sds.c create mode 100644 extlibs/sds.h create mode 100644 extlibs/sdsalloc.h create mode 100644 extlibs/sha1.c create mode 100644 extlibs/sha1.h delete mode 100644 sds.c delete mode 100644 sds.h delete mode 100644 sdsalloc.h delete mode 100644 sha1.c delete mode 100644 sha1.h diff --git a/Makefile b/Makefile index 82a9cc2..5e8b052 100644 --- a/Makefile +++ b/Makefile @@ -1,40 +1,25 @@ PROJECT=agni CC=gcc CFLAGS= +SOURCES=$(wildcard *.c) +OBJECTS=$(SOURCES:.c=.o) +LDFLAGS=-lrt -lm +INCLUDE=-I./extlibs/ -I./ -make: version - $(CC) $(CFLAGS) buf.c -c - $(CC) $(CFLAGS) mmm.c -c - $(CC) $(CFLAGS) darray.c -c - $(CC) $(CFLAGS) mq_cmd.c -c - $(CC) $(CFLAGS) mq_ntf.c -c - $(CC) $(CFLAGS) tbl_qcmd.c -c - $(CC) $(CFLAGS) util.c -c - $(CC) $(CFLAGS) sock_conn.c -c - $(CC) $(CFLAGS) irc_parse.c -c - $(CC) $(CFLAGS) mmm.c -c - $(CC) $(CFLAGS) cmd_date.c -c - $(CC) $(CFLAGS) cmd_uptime.c -c - $(CC) $(CFLAGS) cmd_version.c -c - $(CC) $(CFLAGS) cmd_ping.c -c - $(CC) $(CFLAGS) cmd_loadavg.c -c - $(CC) $(CFLAGS) cmd_rusage.c -c - $(CC) $(CFLAGS) cmd_cmd.c -c - $(CC) $(CFLAGS) sha1.c -c - $(CC) $(CFLAGS) cmd_sha1.c -c - $(CC) $(CFLAGS) cmd_cookie.c -c - $(CC) $(CFLAGS) cmd_botu.c -c - $(CC) $(CFLAGS) cmd_fir1p.c -c - $(CC) $(CFLAGS) sds.c -c - $(CC) $(CFLAGS) cmd_rand.c -c - $(CC) $(CFLAGS) cmd_rand_libc.c -c - $(CC) $(CFLAGS) cmd_fir.c -c - $(CC) $(CFLAGS) tbl_qcmd.o mq_cmd.o mq_ntf.o buf.o mmm.o darray.o util.o sock_conn.o \ - irc_parse.o mmm.c cmd_date.o cmd_uptime.o cmd_version.o cmd_ping.o cmd_loadavg.o \ - cmd_rusage.o cmd_cmd.o sha1.o cmd_sha1.o cmd_cookie.o cmd_botu.o cmd_fir1p.o sds.o \ - cmd_rand.o cmd_rand_libc.o cmd_fir.o agni.c \ - -o $(PROJECT) -std=c11 -lrt -lm +all: createcmd createextlib $(OBJECTS) $(PROJECT) +$(PROJECT): version $(SOURCES) agni.c + $(CC) $(OBJECTS) $(CFLAGS) $(LDFLAGS) -std=c11 -o $(PROJECT) + +#make: version +# $(CC) $(CFLAGS) agni.c \ +# -o $(PROJECT) -std=c11 -lrt -lm + +%.o: %.c + @echo $@ + $(CC) $(CFLAGS) $(INCLUDE) -c $< -o $(subst .c,.o,$<) + +#autogenerate version from git commit and date when it was compiled version: #could have bug if commit message have somethign bad in it rm -f version.h @@ -44,8 +29,35 @@ version: echo "#define VERSION_COMMIT \""`git log -1 --oneline`"\"">>version.h echo "#endif">>version.h +#get all C files in cmd firectory and compile all of them +CMD_SOURCES=$(wildcard cmd/*.c) +CMD_HEADERS=$(wildcard cmd/*.h) +#output header with all includes to commands +CMD_INC_HEADER=config_all_cmds.h +#cmd object files +CMD_OBJECTS=$(CMD_SOURCES:.c=.o) +#add commands objects to all objects +OBJECTS+=$(CMD_OBJECTS) +createcmd: headerscmd $(CMD_OBJECTS) + #echo $(CMD_SOURCES) + #echo $(CMD_OBJECTS) + +#generate header files with all commands in directory, to include all cmd header files in single include +headerscmd: + rm -f $(CMD_INC_HEADER) + echo "#ifndef __CONFIG_CMD_HEADERS_H">>$(CMD_INC_HEADER) + echo "#define __CONFIG_CMD_HEADERS_H">>$(CMD_INC_HEADER) + for header in $(CMD_HEADERS); do echo -e "#include \"$$header\"">>$(CMD_INC_HEADER); done + echo "#endif">>$(CMD_INC_HEADER) + +EXTLIB_SOURCES=$(wildcard extlibs/*.c) +EXTLIB_OBJECTS=$(EXTLIB_SOURCES:.c=.o) +OBJECTS+=$(EXTLIB_OBJECTS) +createextlib: $(EXTLIB_OBJECTS) + #asd + leak: valgrind --leak-check=full --track-origins=yes --log-file=log.txt ./$(PROJECT) clean: - rm -f agni *.o \ No newline at end of file + rm -f agni *.o cmd/*.o \ No newline at end of file diff --git a/cmd/cmd_botu.c b/cmd/cmd_botu.c new file mode 100644 index 0000000..f284ba9 --- /dev/null +++ b/cmd/cmd_botu.c @@ -0,0 +1,46 @@ +#include "cmd_botu.h" + +#define BILLION 1000000000L + +void *cmd_botu(void *data) +{ + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + struct timespec start; + struct stat file_stat; + uint64_t proc_sec; + + printf("BOTU\n"); + + stat("/proc/self",&file_stat); + + /* + CHECK PREDIFINED MACROSES IF SUCH FUNCTIONALITY EXCISTS OR NOT + */ + #if _POSIX_C_SOURCE < 199309L + ERROR("Dont have functionality\n"); + #endif + + fret = clock_gettime(CLOCK_REALTIME, &start); + if (fret<0) + { + perror("clock gettime"); + ret = alloc_new_str("Can get clock thread uptime\n"); + return ret; + } + + proc_sec = start.tv_sec - file_stat.st_ctim.tv_sec; + + snprintf(buf, buf_size, "%llud %lluh %llum %llus\n", + (proc_sec/(3600*24)), + (proc_sec/(3600))%24, + (proc_sec/60)%60, + proc_sec%60); + ret = alloc_new_str(buf); + + return ret; +} diff --git a/cmd/cmd_botu.h b/cmd/cmd_botu.h new file mode 100644 index 0000000..2c06230 --- /dev/null +++ b/cmd/cmd_botu.h @@ -0,0 +1,17 @@ +#ifndef __CMD_BOTU_H +#define __CMD_BOTU_H + +#include +#include +#include +#include +#include +#include +#include + +#include "util.h" +#include "debug.h" + +void *cmd_botu(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_cmd.c b/cmd/cmd_cmd.c new file mode 100644 index 0000000..e893687 --- /dev/null +++ b/cmd/cmd_cmd.c @@ -0,0 +1,20 @@ +#include "cmd_cmd.h" + +void *cmd_cmd(void *data) +{ + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("CMD\n"); + + snprintf(buf, buf_size, "%s\n", data); + + + + ret = alloc_new_str(buf); + + return ret; +} diff --git a/cmd/cmd_cmd.h b/cmd/cmd_cmd.h new file mode 100644 index 0000000..2670abd --- /dev/null +++ b/cmd/cmd_cmd.h @@ -0,0 +1,14 @@ +#ifndef __CMD_CMD_H +#define __CMD_CMD_H + +#include +#include + +#include +#include + +#include "util.h" + +void *cmd_cmd(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_cookie.c b/cmd/cmd_cookie.c new file mode 100644 index 0000000..8071e10 --- /dev/null +++ b/cmd/cmd_cookie.c @@ -0,0 +1,19 @@ +#include "cmd_cookie.h" + +void *cmd_cookie(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("COOKIE\n"); + + + snprintf(buf, buf_size, "No heroes yet\n"); + ret = alloc_new_str(buf); + + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_cookie.h b/cmd/cmd_cookie.h new file mode 100644 index 0000000..62a4779 --- /dev/null +++ b/cmd/cmd_cookie.h @@ -0,0 +1,11 @@ +#ifndef __CMD_COOKIE_H +#define __CMD_COOKIE_H + +#include +#include + +#include "util.h" + +void *cmd_cookie(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_date.c b/cmd/cmd_date.c new file mode 100644 index 0000000..ac44bd5 --- /dev/null +++ b/cmd/cmd_date.c @@ -0,0 +1,13 @@ +#include "cmd_date.h" + +void *cmd_date(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + + printf("DATE\n"); + + ret = alloc_new_str("I dont whant to date with you\n"); + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_date.h b/cmd/cmd_date.h new file mode 100644 index 0000000..0e1c9c5 --- /dev/null +++ b/cmd/cmd_date.h @@ -0,0 +1,11 @@ +#ifndef __CMD_DATE_H +#define __CMD_DATE_H + +#include +#include + +#include "util.h" + +void *cmd_date(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_fir.c b/cmd/cmd_fir.c new file mode 100644 index 0000000..95e0b53 --- /dev/null +++ b/cmd/cmd_fir.c @@ -0,0 +1,621 @@ +#include "cmd_fir.h" + +#define pi 3.14159265 + +typedef struct filter_t +{ + double fs,fc1,fc2,beta; + int n,n1; + int wtype; + int type; + int nflag; +} filter_t; + +#define FILT_LP 1 +#define FILT_HP 2 +#define FILT_BP 3 +#define FILT_BS 4 +#define FILT_CHECK(X) (((X)>=FILT_LP)&&((X)<=FILT_BS)) + +#define FILT_WIN_RECT 1 +#define FILT_WIN_HAMM 2 +#define FILT_WIN_HANN 3 +#define FILT_WIN_BLCK 4 +#define FILT_WIN_KAIS 5 +#define FILT_WIN_CHECK(X) (((X)>=FILT_WIN_RECT)&&((X)<=FILT_WIN_KAIS)) + +void sincx1_(double fc, double *sinc_h, int n1, int parity); +int filter_spec_(filter_t *filt, int type, double fs, double fc1, double fc2, int wtype, double beta, int n); +void lowpass_highpass_(filter_t *filt, double *sinc_h); +void window_func_(filter_t *filt, double *win); +void filter_output_(filter_t *filt, double *h, double *hb); +double bessel(double x); + +void filter_calc(filter_t *filt, double *hc, int hc_sz); + + + +int filter_spec_(filter_t *filt, int type, double fs, double fc1, double fc2, int wtype, double beta, int n) +{ + + /*Check input params*/ + //check sample rate + if (fs < 0) + { + ERROR("ERROR fs\n"); + return -1; + } + filt->fs = fs; + + //check filter type + if (!FILT_CHECK(type)) + { + ENL(); + return -1; + } + filt->type = type; + + if ((filt->type==FILT_LP)||(filt->type==FILT_HP)) + { + //PRINT("%f %f\n",fc1, fs); + filt->fc1 = fc1/fs; //fc2 not used + } else if ((type==FILT_BS)||(type==FILT_BP)) + { + filt->fc1 = fc1/fs; + filt->fc2 = fc2/fs; + //PRINT("%f %f %f\n", fc1, fc2, fs); + } else + { + ENL(); + return -1; + } + + //window type used + if (FILT_WIN_CHECK(wtype)) + { + if (wtype == FILT_WIN_KAIS) + { + //beta for Kaiser window + filt->beta = beta; + } + } + filt->wtype = wtype; + + /* request filter length and determine whether it is odd or even + * for N even only N/2 coefficients need be calculated, and for N odd + * only (N+1)/2 because of the symmetry in h(n). + */ + + filt->n = n; + filt->n1 = n/2; + filt->nflag = 1; + if ((filt->n - 2*filt->n1)==1) + { + filt->nflag = 0; + filt->n1 = filt->n1+1; + } + return 0; +} + +//sinc_h size as filt->n1 size +void lowpass_highpass_(filter_t *filt, double *h) +{ + int j; + + sincx1_(filt->fc1, h, filt->n1, filt->nflag); + if (filt->type == FILT_HP) + { + h[0]=1-h[0]; + for (j=0;jn1;++j) + { + h[j] = -h[j]; + //printf("%f ",sinc_h[j]); + } + } + +} + + +void bandpass_bandstop_(filter_t *filt, double *sinc_h, double *h_bp) +{ + int j; + + double fc; + + fc = filt->fc2; + sincx1_(fc, sinc_h, filt->n1, filt->nflag); + for (j=0; jn1;++j) + { + h_bp[j] = sinc_h[j]; + } + + fc = filt->fc1; + sincx1_(fc, sinc_h, filt->n1, filt->nflag); + for (j=0;jn1;++j) + { + sinc_h[j] = h_bp[j] - sinc_h[j]; + } + + if (filt->type == FILT_BS) + { + sinc_h[0] = 1 - sinc_h[0]; + for (j=1; jn1; ++j) + { + sinc_h[j] = -sinc_h[j]; + } + } +} + +/*---------------------------------------------------------------------- +* function to calculate sincx: 2FC * sin(nwc)/nwc +*/ +void sincx1_(double fc, double *h, int n1, int parity) +{ + int i,j; + double omega, p; + + omega=2*pi*fc; + h[0]=2*fc; + i=1; + if(parity==1) + { /* check for N even */ + i=0; + } + + for(j=i; jwtype) + { + case FILT_WIN_RECT: + for (j=0; jn1; ++j) + { + win[j]=1.0; + } + break; + case FILT_WIN_HAMM: + for (j=0; jn1; ++j) + { + p=filt->nflag*0.5+j; + win[j] = 0.54+(1-0.54)*cos(2*pi*p/filt->n); + } + break; + case FILT_WIN_HANN: + for (j=0; jn1; ++j) + { + p = filt->nflag*0.5 + j; + win[j] = 0.5+(1-0.5)*cos(2*pi*p/filt->n); + } + break; + case FILT_WIN_BLCK: + for (j=0; jn1; ++j) + { + p = filt->nflag*0.5 + j; + win[j] = 0.42 + + 0.5*cos(2*pi*p/(filt->n-1)) + + 0.08*cos(4*pi*p/(filt->n-1)); + } + break; + case FILT_WIN_KAIS: + x1 = filt->beta; + bd = bessel(x1); + for (j=0; jn1; ++j) + { + p = filt->nflag*0.5 + j; + rm = 2*p/(filt->n); + rm = rm*rm; + x1 = filt->beta * sqrt(1-rm); + bn = bessel(x1); + win[j] = bn/bd; + } + break; + default: + printf("Unknown window type %d\n", filt->wtype); + } +} + +/* +* +*/ +double bessel(double x) +{ + double y,t,t1,e,de,sde; + int i; + + y=x/2; + t=1.E-08; e=1; de=1; + for(i=1; i <25; ++i){ + t1=(double) i; + de=de*y/t1; + sde=de*de; + e=e+sde; + if((e*t-sde) > 0.0) + return(e); + } + ENL(); + return 0.0; +} + + +void filter_output_(filter_t *filt, double *h, double *hb) +{ + int j; + + double fs,fc,fc1,fc2; + + fs = filt->fs; + fc = filt->fc1 * filt->fs; + fc1 = filt->fc1 * filt->fs; + fc2 = filt->fc2 * filt->fs; + + switch(filt->type) + { + case FILT_LP: + printf("lowpass filter \n"); + printf("sampling frequency:\t%f\n", fs); + printf("cutoff frequency:\t%f\n", fc); + break; + case FILT_HP: + printf("highpass filter \n"); + printf("sampling frequency:\t%f\n", fs); + printf("cutoff frequency:\t%f\n", fc); + break; + case FILT_BP: + printf("bandpass filter \n"); + printf("sampling frequency:\t%f\n", fs); + printf("cutoff frequencies:\t%f\t%f\n", fc1, fc2); + break; + case FILT_BS: + printf("bandstop filter \n"); + printf("sampling frequency:\t%f\n", fs); + printf("cutoff frequencies:\t%f\t%f\n", fc1, fc2); + break; + } + printf("\n"); + + switch(filt->wtype) + { + case 1: + printf("Rectangular window \n"); + break; + case 2: + printf("Hamming window \n"); + break; + case 3: + printf("Hanning window \n"); + break; + case 4: + printf("Blackman window \n"); + break; + case 5: + printf("Kaiser window \n"); + break; + } + printf("\n"); + + printf("Impulse response coefficients\n"); + printf("\n"); + for (j=0;jn1;++j) + { + printf("h[%2d",j); + printf("] =\t%15.5e\t",h[filt->n1-j-1]); + printf(" = h[%2d",filt->n-j-1); + printf("]\n"); + hb[j]=h[filt->n1-j-1]; + hb[filt->n-j-1]=hb[j]; + } +} + +void filter_calc(filter_t *filt, double *hc, int hc_sz) +{ + int i; + double *h=NULL,*w=NULL,*hb=NULL; + filter_t loc_filt; + + memset(&loc_filt, 0, sizeof(filter_t)); + + if (filt == NULL) + { + ENL(); + return; + } + + if (hc == NULL) + { + ENL(); + return; + } + + if (hc_sz<=0) + { + ENL(); + return; + } + + //set internal structure value, precalculate coefficients + filter_spec_(&loc_filt, filt->type, filt->fs, filt->fc1, filt->fc2, filt->wtype, filt->beta, filt->n); + + h = malloc(sizeof(double) * loc_filt.n1); + if (h==NULL) + { + ENL(); + } + memset(h, 0, sizeof(double) * loc_filt.n1); + + hb = malloc(sizeof(double) * loc_filt.n); + if (hb==NULL) + { + ENL(); + } + memset(hb, 0, sizeof(double) * loc_filt.n); + + + + w = malloc(sizeof(double) * loc_filt.n1); + if (w==NULL) + { + ENL(); + } + memset(w, 0, sizeof(double) * loc_filt.n1); + + if ( + (loc_filt.type == FILT_LP) + || (loc_filt.type == FILT_HP) + ) + { + lowpass_highpass_(&loc_filt, h); + } else if ( + (loc_filt.type == FILT_BP) + || (loc_filt.type == FILT_BS) + ) + { + bandpass_bandstop_(&loc_filt, h, hb); + } else + { + ENL(); + } + + window_func_(&loc_filt, w); /* compute the window function */ + for(i=0; i < loc_filt.n1; i++) + { + h[i]=h[i]*w[i]; + } + //filter_output_(&loc_filt, h, hb); /* print the filter coefficients */ + + for (i=0; i1000000) + { + arg_fs = 1000000; //1Mhz should be enought + } else if (arg_fs<2) + { + arg_fs = 2; + } + + PNL(); + arg_fc1 = atof(tokens[2]); + if (arg_fc1>1000000.0) + { + arg_fc1 = 1000000.0; + } else if (arg_fc1<1.0) + { + arg_fc1 = 1.0; + } + + PNL(); + arg_fc1 = atof(tokens[2]); + if (arg_fc1>1000000.0) + { + arg_fc1 = 1000000.0; + } else if (arg_fs<1.0) + { + arg_fc1 = 1.0; + } + + PNL(); + arg_n = atoi(tokens[6]); + if (arg_n>63) + { + arg_n = 63; + } else if (arg_n<1) + { + arg_n = 1; + } + + PNL(); + arg_beta = atof(tokens[5]); + if (arg_beta > 1.0) + { + arg_beta = 1.0; + } else if (arg_beta < 0.0) + { + arg_beta = 0.0; + } + + PNL(); + + if (strncmp(tokens[4],"RECT",4)==0) + { + arg_wtype = FILT_WIN_RECT; + } else if (strncmp(tokens[4],"HAMM",4)==0) + { + arg_wtype = FILT_WIN_HAMM; + } else if (strncmp(tokens[4],"HANN",4)==0) + { + arg_wtype = FILT_WIN_HANN; + } else if (strncmp(tokens[4],"BLCK",4)==0) + { + arg_wtype = FILT_WIN_BLCK; + } else if (strncmp(tokens[4],"KAIS",4)==0) + { + arg_wtype = FILT_WIN_BLCK; + } else + { + arg_wtype = FILT_WIN_RECT; + } + + PNL(); + if (strncmp(tokens[0],"LP",2)==0) + { + arg_ftype = FILT_LP; + } else if (strncmp(tokens[0],"HP",2)==0) + { + arg_ftype = FILT_HP; + } else if (strncmp(tokens[0],"BP",2)==0) + { + arg_ftype = FILT_BP; + } else if (strncmp(tokens[0],"BS",2)==0) + { + arg_ftype = FILT_BS; + } else + { + arg_ftype = FILT_LP; + } + + PNL(); + //calculate + lp_coef = malloc(sizeof(double)*arg_n); + memset(lp_coef, 0, sizeof(double)*arg_n); + + PNL(); + filt.type = arg_ftype; + filt.fs = arg_fs; + filt.fc1 = arg_fc1; + filt.fc2 = arg_fc2; + filt.wtype = arg_wtype; + filt.n = arg_n; + filt.beta = arg_beta; + + PNL(); + filter_calc(&filt, lp_coef, arg_n); + + + //prepare output + for (i=0;i +#include +#include +#include + +#include "sds.h" +#include "util.h" +#include "debug.h" + +void *cmd_fir(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_fir1p.c b/cmd/cmd_fir1p.c new file mode 100644 index 0000000..b011719 --- /dev/null +++ b/cmd/cmd_fir1p.c @@ -0,0 +1,94 @@ +#include "cmd_fir1p.h" + +#define FIR_SIZE 12 + +double fir_coef[FIR_SIZE] = +{ + -0.0044384, -0.0041841, 0.0130183, 0.0746628, + 0.1720210, 0.2489204, 0.2489204, 0.1720210, + 0.0746628, 0.0130183, -0.0041841, -0.0044384 +}; + +#define MAX_INPUT_LEN 80 +#define BUFFER_LEN (FIR_SIZE-1+MAX_INPUT_LEN) +double insamp[BUFFER_LEN]; + +int fir1filter(double *coeffs, double *input, double *output, + int length, int filter_length) +{ + double acc; + double *coeffp; + double *inputp; + int n; + int k; + + memcpy(&insamp[filter_length-1], input, length*sizeof(double)); + + for (n=0; n +#include + +#include "sds.h" +#include "util.h" +#include "debug.h" + +void *cmd_fir1p(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_loadavg.c b/cmd/cmd_loadavg.c new file mode 100644 index 0000000..a9a4b28 --- /dev/null +++ b/cmd/cmd_loadavg.c @@ -0,0 +1,28 @@ +#include "cmd_loadavg.h" + +void *cmd_loadavg(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + double loadavg_d[3]; + + printf("LOADAVG\n"); + + fret = getloadavg(loadavg_d, 3); + if (fret<0) + { + ret = alloc_new_str("Cant get load avg mate\n"); + } + + printf("1M %lf 5M %lf 15M %lf\n", loadavg_d[0], loadavg_d[1], loadavg_d[2]); + snprintf(buf, buf_size,"1M %.1f 5M %.1f 15M %.1f\n", loadavg_d[0], loadavg_d[1], loadavg_d[2]); + + ret = alloc_new_str(buf); + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_loadavg.h b/cmd/cmd_loadavg.h new file mode 100644 index 0000000..d3bd9c2 --- /dev/null +++ b/cmd/cmd_loadavg.h @@ -0,0 +1,11 @@ +#ifndef __CMD_LOADAVG_H +#define __CMD_LOADAVG_H + +#include +#include + +#include "util.h" + +void *cmd_loadavg(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_ping.c b/cmd/cmd_ping.c new file mode 100644 index 0000000..a8e3c59 --- /dev/null +++ b/cmd/cmd_ping.c @@ -0,0 +1,13 @@ +#include "cmd_ping.h" + +void *cmd_ping(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + + printf("PONG\n"); + + ret = alloc_new_str("pong"); + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_ping.h b/cmd/cmd_ping.h new file mode 100644 index 0000000..fef18c6 --- /dev/null +++ b/cmd/cmd_ping.h @@ -0,0 +1,11 @@ +#ifndef __CMD_PING_H +#define __CMD_PING_H + +#include +#include + +#include "util.h" + +void *cmd_ping(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_rand.c b/cmd/cmd_rand.c new file mode 100644 index 0000000..58f2efe --- /dev/null +++ b/cmd/cmd_rand.c @@ -0,0 +1,19 @@ +#include "cmd_rand.h" + + +void *cmd_rand(void *data) +{ + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("RAND\n"); + + + snprintf(buf, buf_size, "4"); + ret = alloc_new_str(buf); + + return ret; +} diff --git a/cmd/cmd_rand.h b/cmd/cmd_rand.h new file mode 100644 index 0000000..14f5c7e --- /dev/null +++ b/cmd/cmd_rand.h @@ -0,0 +1,12 @@ +#ifndef __CMD_RAND_H +#define __CMD_RAND_H + +#include +#include + +#include "util.h" +#include "debug.h" + +void *cmd_rand(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_rand_libc.c b/cmd/cmd_rand_libc.c new file mode 100644 index 0000000..d72bc45 --- /dev/null +++ b/cmd/cmd_rand_libc.c @@ -0,0 +1,50 @@ +#include "cmd_rand_libc.h" + + +void *cmd_rand_libc(void *data) +{ + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("RAND LIBC\n"); + + int i; + int count; + int rand_val; + sds params; + sds out_result; + sds *tokens; + + if (data == NULL) + { + rand_val = rand(); + snprintf(buf, buf_size, "%d", rand_val); + } else { + //cut output to 512 + char str_integer[16]; + int rand_state; + + params = sdsnew(data); + out_result = sdsempty(); + tokens = sdssplitargs(params, &count); + for (i=0;i +#include + +#include "sds.h" +#include "util.h" +#include "debug.h" + +void *cmd_rand_libc(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_rusage.c b/cmd/cmd_rusage.c new file mode 100644 index 0000000..3dc5d21 --- /dev/null +++ b/cmd/cmd_rusage.c @@ -0,0 +1,34 @@ + +#include "cmd_rusage.h" + +void *cmd_rusage(void *data) +{ + char *ret = NULL; + int fret=-1; + + const int buf_size = 128; + char buf[buf_size+1]; + + struct rusage cur_proc_rusage; + + printf("RUSAGE\n"); + + fret = getrusage(RUSAGE_SELF, &cur_proc_rusage); + if (fret<0) + { + ret = alloc_new_str("Cant get rusage mate\n"); + } + + printf("USER %ld SYS %ld\n", + cur_proc_rusage.ru_utime.tv_sec, + cur_proc_rusage.ru_stime.tv_sec + ); + snprintf(buf, buf_size, "USER %ld SYS %ld\n", + cur_proc_rusage.ru_utime.tv_sec, + cur_proc_rusage.ru_stime.tv_sec + ); + + ret = alloc_new_str(buf); + + return ret; +} diff --git a/cmd/cmd_rusage.h b/cmd/cmd_rusage.h new file mode 100644 index 0000000..5e35317 --- /dev/null +++ b/cmd/cmd_rusage.h @@ -0,0 +1,14 @@ +#ifndef __CMD_RUSAGE_H +#define __CMD_RUSAGE_H + +#include +#include + +#include +#include + +#include "util.h" + +void *cmd_rusage(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_sha1.c b/cmd/cmd_sha1.c new file mode 100644 index 0000000..4472ed1 --- /dev/null +++ b/cmd/cmd_sha1.c @@ -0,0 +1,41 @@ +#include "cmd_sha1.h" + +void *cmd_sha1(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + int fret=-1; + + + int i; + char hash_result[21]; + char hex_result[41]; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("SHA1\n"); + + + if (param == NULL) + { + ret = alloc_new_str("No params mate\n"); + return ret; + } + + SHA1(hash_result, param, strlen(param)); + + //cool way how to convert array to string + for (i=0;i<20;i++) + { + sprintf(hex_result+(2*i), "%02x", hash_result[i]&0xff); + } + hex_result[40]=0x0; + + + snprintf(buf, buf_size, "sha1 %s\n",hex_result); + ret = alloc_new_str(buf); + + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_sha1.h b/cmd/cmd_sha1.h new file mode 100644 index 0000000..69a7bc8 --- /dev/null +++ b/cmd/cmd_sha1.h @@ -0,0 +1,12 @@ +#ifndef __CMD_SHA1_H +#define __CMD_SHA1_H + +#include +#include + +#include "util.h" +#include "sha1.h" + +void *cmd_sha1(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_sum.c b/cmd/cmd_sum.c new file mode 100644 index 0000000..e69de29 diff --git a/cmd/cmd_sum.h b/cmd/cmd_sum.h new file mode 100644 index 0000000..e69de29 diff --git a/cmd/cmd_uptime.c b/cmd/cmd_uptime.c new file mode 100644 index 0000000..6a9c963 --- /dev/null +++ b/cmd/cmd_uptime.c @@ -0,0 +1,34 @@ +#include "cmd_uptime.h" + +#define PROCFS_PATH "/proc" +#define PROCFS_UPTIME_PATH PROCFS_PATH "/uptime" + +void *cmd_uptime(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("UPTIME\n"); + + FILE *f=NULL; + double d1,d2; + int i1,i2; + + f = fopen(PROCFS_UPTIME_PATH,"r"); + fscanf(f,"%lf %lf", &d1, &d2); + fclose(f); + + printf("Readed %lf %lf\n", d1, d2); + i1 = d1; + i2 = d2; + + printf("Days %d Hours %d Minutes %d\n",i1/(3600*24),i1/(3600)%24, (i1/60)%60); + snprintf(buf, buf_size,"%dd %dh %dm\n",i1/(3600*24),i1/(3600)%24, (i1/60)%60); + + ret = alloc_new_str(buf); + + return ret; +} \ No newline at end of file diff --git a/cmd/cmd_uptime.h b/cmd/cmd_uptime.h new file mode 100644 index 0000000..3906cd2 --- /dev/null +++ b/cmd/cmd_uptime.h @@ -0,0 +1,11 @@ +#ifndef __CMD_UPTIME_H +#define __CMD_UPTIME_H + +#include +#include + +#include "util.h" + +void *cmd_uptime(void *data); + +#endif \ No newline at end of file diff --git a/cmd/cmd_version.c b/cmd/cmd_version.c new file mode 100644 index 0000000..d919c60 --- /dev/null +++ b/cmd/cmd_version.c @@ -0,0 +1,16 @@ +#include "cmd_version.h" + +void *cmd_version(void *data) +{ + char *param = (char *)data; + char *ret = NULL; + + const int buf_size = 128; + char buf[buf_size+1]; + + printf("VERSION\n"); + + snprintf(buf, buf_size, "VERSION:0.0.3" " DATE:" VERSION_DATE " COMMIT:" VERSION_COMMIT "\n"); + + ret = alloc_new_str(buf); +} \ No newline at end of file diff --git a/cmd/cmd_version.h b/cmd/cmd_version.h new file mode 100644 index 0000000..23cd639 --- /dev/null +++ b/cmd/cmd_version.h @@ -0,0 +1,17 @@ +#ifndef __CMD_VERSION_H +#define __CMD_VERSION_H + +#include +#include + +#include "util.h" + + +//Auto generated in Makefile +#include "version.h" + +void *cmd_version(void *data); + +#endif + + diff --git a/cmd_botu.c b/cmd_botu.c deleted file mode 100644 index f284ba9..0000000 --- a/cmd_botu.c +++ /dev/null @@ -1,46 +0,0 @@ -#include "cmd_botu.h" - -#define BILLION 1000000000L - -void *cmd_botu(void *data) -{ - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - struct timespec start; - struct stat file_stat; - uint64_t proc_sec; - - printf("BOTU\n"); - - stat("/proc/self",&file_stat); - - /* - CHECK PREDIFINED MACROSES IF SUCH FUNCTIONALITY EXCISTS OR NOT - */ - #if _POSIX_C_SOURCE < 199309L - ERROR("Dont have functionality\n"); - #endif - - fret = clock_gettime(CLOCK_REALTIME, &start); - if (fret<0) - { - perror("clock gettime"); - ret = alloc_new_str("Can get clock thread uptime\n"); - return ret; - } - - proc_sec = start.tv_sec - file_stat.st_ctim.tv_sec; - - snprintf(buf, buf_size, "%llud %lluh %llum %llus\n", - (proc_sec/(3600*24)), - (proc_sec/(3600))%24, - (proc_sec/60)%60, - proc_sec%60); - ret = alloc_new_str(buf); - - return ret; -} diff --git a/cmd_botu.h b/cmd_botu.h deleted file mode 100644 index 2c06230..0000000 --- a/cmd_botu.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef __CMD_BOTU_H -#define __CMD_BOTU_H - -#include -#include -#include -#include -#include -#include -#include - -#include "util.h" -#include "debug.h" - -void *cmd_botu(void *data); - -#endif \ No newline at end of file diff --git a/cmd_cmd.c b/cmd_cmd.c deleted file mode 100644 index e893687..0000000 --- a/cmd_cmd.c +++ /dev/null @@ -1,20 +0,0 @@ -#include "cmd_cmd.h" - -void *cmd_cmd(void *data) -{ - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("CMD\n"); - - snprintf(buf, buf_size, "%s\n", data); - - - - ret = alloc_new_str(buf); - - return ret; -} diff --git a/cmd_cmd.h b/cmd_cmd.h deleted file mode 100644 index 2670abd..0000000 --- a/cmd_cmd.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef __CMD_CMD_H -#define __CMD_CMD_H - -#include -#include - -#include -#include - -#include "util.h" - -void *cmd_cmd(void *data); - -#endif \ No newline at end of file diff --git a/cmd_cookie.c b/cmd_cookie.c deleted file mode 100644 index 8071e10..0000000 --- a/cmd_cookie.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "cmd_cookie.h" - -void *cmd_cookie(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("COOKIE\n"); - - - snprintf(buf, buf_size, "No heroes yet\n"); - ret = alloc_new_str(buf); - - - return ret; -} \ No newline at end of file diff --git a/cmd_cookie.h b/cmd_cookie.h deleted file mode 100644 index 62a4779..0000000 --- a/cmd_cookie.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CMD_COOKIE_H -#define __CMD_COOKIE_H - -#include -#include - -#include "util.h" - -void *cmd_cookie(void *data); - -#endif \ No newline at end of file diff --git a/cmd_date.c b/cmd_date.c deleted file mode 100644 index ac44bd5..0000000 --- a/cmd_date.c +++ /dev/null @@ -1,13 +0,0 @@ -#include "cmd_date.h" - -void *cmd_date(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - - printf("DATE\n"); - - ret = alloc_new_str("I dont whant to date with you\n"); - - return ret; -} \ No newline at end of file diff --git a/cmd_date.h b/cmd_date.h deleted file mode 100644 index 0e1c9c5..0000000 --- a/cmd_date.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CMD_DATE_H -#define __CMD_DATE_H - -#include -#include - -#include "util.h" - -void *cmd_date(void *data); - -#endif \ No newline at end of file diff --git a/cmd_fir.c b/cmd_fir.c deleted file mode 100644 index 95e0b53..0000000 --- a/cmd_fir.c +++ /dev/null @@ -1,621 +0,0 @@ -#include "cmd_fir.h" - -#define pi 3.14159265 - -typedef struct filter_t -{ - double fs,fc1,fc2,beta; - int n,n1; - int wtype; - int type; - int nflag; -} filter_t; - -#define FILT_LP 1 -#define FILT_HP 2 -#define FILT_BP 3 -#define FILT_BS 4 -#define FILT_CHECK(X) (((X)>=FILT_LP)&&((X)<=FILT_BS)) - -#define FILT_WIN_RECT 1 -#define FILT_WIN_HAMM 2 -#define FILT_WIN_HANN 3 -#define FILT_WIN_BLCK 4 -#define FILT_WIN_KAIS 5 -#define FILT_WIN_CHECK(X) (((X)>=FILT_WIN_RECT)&&((X)<=FILT_WIN_KAIS)) - -void sincx1_(double fc, double *sinc_h, int n1, int parity); -int filter_spec_(filter_t *filt, int type, double fs, double fc1, double fc2, int wtype, double beta, int n); -void lowpass_highpass_(filter_t *filt, double *sinc_h); -void window_func_(filter_t *filt, double *win); -void filter_output_(filter_t *filt, double *h, double *hb); -double bessel(double x); - -void filter_calc(filter_t *filt, double *hc, int hc_sz); - - - -int filter_spec_(filter_t *filt, int type, double fs, double fc1, double fc2, int wtype, double beta, int n) -{ - - /*Check input params*/ - //check sample rate - if (fs < 0) - { - ERROR("ERROR fs\n"); - return -1; - } - filt->fs = fs; - - //check filter type - if (!FILT_CHECK(type)) - { - ENL(); - return -1; - } - filt->type = type; - - if ((filt->type==FILT_LP)||(filt->type==FILT_HP)) - { - //PRINT("%f %f\n",fc1, fs); - filt->fc1 = fc1/fs; //fc2 not used - } else if ((type==FILT_BS)||(type==FILT_BP)) - { - filt->fc1 = fc1/fs; - filt->fc2 = fc2/fs; - //PRINT("%f %f %f\n", fc1, fc2, fs); - } else - { - ENL(); - return -1; - } - - //window type used - if (FILT_WIN_CHECK(wtype)) - { - if (wtype == FILT_WIN_KAIS) - { - //beta for Kaiser window - filt->beta = beta; - } - } - filt->wtype = wtype; - - /* request filter length and determine whether it is odd or even - * for N even only N/2 coefficients need be calculated, and for N odd - * only (N+1)/2 because of the symmetry in h(n). - */ - - filt->n = n; - filt->n1 = n/2; - filt->nflag = 1; - if ((filt->n - 2*filt->n1)==1) - { - filt->nflag = 0; - filt->n1 = filt->n1+1; - } - return 0; -} - -//sinc_h size as filt->n1 size -void lowpass_highpass_(filter_t *filt, double *h) -{ - int j; - - sincx1_(filt->fc1, h, filt->n1, filt->nflag); - if (filt->type == FILT_HP) - { - h[0]=1-h[0]; - for (j=0;jn1;++j) - { - h[j] = -h[j]; - //printf("%f ",sinc_h[j]); - } - } - -} - - -void bandpass_bandstop_(filter_t *filt, double *sinc_h, double *h_bp) -{ - int j; - - double fc; - - fc = filt->fc2; - sincx1_(fc, sinc_h, filt->n1, filt->nflag); - for (j=0; jn1;++j) - { - h_bp[j] = sinc_h[j]; - } - - fc = filt->fc1; - sincx1_(fc, sinc_h, filt->n1, filt->nflag); - for (j=0;jn1;++j) - { - sinc_h[j] = h_bp[j] - sinc_h[j]; - } - - if (filt->type == FILT_BS) - { - sinc_h[0] = 1 - sinc_h[0]; - for (j=1; jn1; ++j) - { - sinc_h[j] = -sinc_h[j]; - } - } -} - -/*---------------------------------------------------------------------- -* function to calculate sincx: 2FC * sin(nwc)/nwc -*/ -void sincx1_(double fc, double *h, int n1, int parity) -{ - int i,j; - double omega, p; - - omega=2*pi*fc; - h[0]=2*fc; - i=1; - if(parity==1) - { /* check for N even */ - i=0; - } - - for(j=i; jwtype) - { - case FILT_WIN_RECT: - for (j=0; jn1; ++j) - { - win[j]=1.0; - } - break; - case FILT_WIN_HAMM: - for (j=0; jn1; ++j) - { - p=filt->nflag*0.5+j; - win[j] = 0.54+(1-0.54)*cos(2*pi*p/filt->n); - } - break; - case FILT_WIN_HANN: - for (j=0; jn1; ++j) - { - p = filt->nflag*0.5 + j; - win[j] = 0.5+(1-0.5)*cos(2*pi*p/filt->n); - } - break; - case FILT_WIN_BLCK: - for (j=0; jn1; ++j) - { - p = filt->nflag*0.5 + j; - win[j] = 0.42 - + 0.5*cos(2*pi*p/(filt->n-1)) - + 0.08*cos(4*pi*p/(filt->n-1)); - } - break; - case FILT_WIN_KAIS: - x1 = filt->beta; - bd = bessel(x1); - for (j=0; jn1; ++j) - { - p = filt->nflag*0.5 + j; - rm = 2*p/(filt->n); - rm = rm*rm; - x1 = filt->beta * sqrt(1-rm); - bn = bessel(x1); - win[j] = bn/bd; - } - break; - default: - printf("Unknown window type %d\n", filt->wtype); - } -} - -/* -* -*/ -double bessel(double x) -{ - double y,t,t1,e,de,sde; - int i; - - y=x/2; - t=1.E-08; e=1; de=1; - for(i=1; i <25; ++i){ - t1=(double) i; - de=de*y/t1; - sde=de*de; - e=e+sde; - if((e*t-sde) > 0.0) - return(e); - } - ENL(); - return 0.0; -} - - -void filter_output_(filter_t *filt, double *h, double *hb) -{ - int j; - - double fs,fc,fc1,fc2; - - fs = filt->fs; - fc = filt->fc1 * filt->fs; - fc1 = filt->fc1 * filt->fs; - fc2 = filt->fc2 * filt->fs; - - switch(filt->type) - { - case FILT_LP: - printf("lowpass filter \n"); - printf("sampling frequency:\t%f\n", fs); - printf("cutoff frequency:\t%f\n", fc); - break; - case FILT_HP: - printf("highpass filter \n"); - printf("sampling frequency:\t%f\n", fs); - printf("cutoff frequency:\t%f\n", fc); - break; - case FILT_BP: - printf("bandpass filter \n"); - printf("sampling frequency:\t%f\n", fs); - printf("cutoff frequencies:\t%f\t%f\n", fc1, fc2); - break; - case FILT_BS: - printf("bandstop filter \n"); - printf("sampling frequency:\t%f\n", fs); - printf("cutoff frequencies:\t%f\t%f\n", fc1, fc2); - break; - } - printf("\n"); - - switch(filt->wtype) - { - case 1: - printf("Rectangular window \n"); - break; - case 2: - printf("Hamming window \n"); - break; - case 3: - printf("Hanning window \n"); - break; - case 4: - printf("Blackman window \n"); - break; - case 5: - printf("Kaiser window \n"); - break; - } - printf("\n"); - - printf("Impulse response coefficients\n"); - printf("\n"); - for (j=0;jn1;++j) - { - printf("h[%2d",j); - printf("] =\t%15.5e\t",h[filt->n1-j-1]); - printf(" = h[%2d",filt->n-j-1); - printf("]\n"); - hb[j]=h[filt->n1-j-1]; - hb[filt->n-j-1]=hb[j]; - } -} - -void filter_calc(filter_t *filt, double *hc, int hc_sz) -{ - int i; - double *h=NULL,*w=NULL,*hb=NULL; - filter_t loc_filt; - - memset(&loc_filt, 0, sizeof(filter_t)); - - if (filt == NULL) - { - ENL(); - return; - } - - if (hc == NULL) - { - ENL(); - return; - } - - if (hc_sz<=0) - { - ENL(); - return; - } - - //set internal structure value, precalculate coefficients - filter_spec_(&loc_filt, filt->type, filt->fs, filt->fc1, filt->fc2, filt->wtype, filt->beta, filt->n); - - h = malloc(sizeof(double) * loc_filt.n1); - if (h==NULL) - { - ENL(); - } - memset(h, 0, sizeof(double) * loc_filt.n1); - - hb = malloc(sizeof(double) * loc_filt.n); - if (hb==NULL) - { - ENL(); - } - memset(hb, 0, sizeof(double) * loc_filt.n); - - - - w = malloc(sizeof(double) * loc_filt.n1); - if (w==NULL) - { - ENL(); - } - memset(w, 0, sizeof(double) * loc_filt.n1); - - if ( - (loc_filt.type == FILT_LP) - || (loc_filt.type == FILT_HP) - ) - { - lowpass_highpass_(&loc_filt, h); - } else if ( - (loc_filt.type == FILT_BP) - || (loc_filt.type == FILT_BS) - ) - { - bandpass_bandstop_(&loc_filt, h, hb); - } else - { - ENL(); - } - - window_func_(&loc_filt, w); /* compute the window function */ - for(i=0; i < loc_filt.n1; i++) - { - h[i]=h[i]*w[i]; - } - //filter_output_(&loc_filt, h, hb); /* print the filter coefficients */ - - for (i=0; i1000000) - { - arg_fs = 1000000; //1Mhz should be enought - } else if (arg_fs<2) - { - arg_fs = 2; - } - - PNL(); - arg_fc1 = atof(tokens[2]); - if (arg_fc1>1000000.0) - { - arg_fc1 = 1000000.0; - } else if (arg_fc1<1.0) - { - arg_fc1 = 1.0; - } - - PNL(); - arg_fc1 = atof(tokens[2]); - if (arg_fc1>1000000.0) - { - arg_fc1 = 1000000.0; - } else if (arg_fs<1.0) - { - arg_fc1 = 1.0; - } - - PNL(); - arg_n = atoi(tokens[6]); - if (arg_n>63) - { - arg_n = 63; - } else if (arg_n<1) - { - arg_n = 1; - } - - PNL(); - arg_beta = atof(tokens[5]); - if (arg_beta > 1.0) - { - arg_beta = 1.0; - } else if (arg_beta < 0.0) - { - arg_beta = 0.0; - } - - PNL(); - - if (strncmp(tokens[4],"RECT",4)==0) - { - arg_wtype = FILT_WIN_RECT; - } else if (strncmp(tokens[4],"HAMM",4)==0) - { - arg_wtype = FILT_WIN_HAMM; - } else if (strncmp(tokens[4],"HANN",4)==0) - { - arg_wtype = FILT_WIN_HANN; - } else if (strncmp(tokens[4],"BLCK",4)==0) - { - arg_wtype = FILT_WIN_BLCK; - } else if (strncmp(tokens[4],"KAIS",4)==0) - { - arg_wtype = FILT_WIN_BLCK; - } else - { - arg_wtype = FILT_WIN_RECT; - } - - PNL(); - if (strncmp(tokens[0],"LP",2)==0) - { - arg_ftype = FILT_LP; - } else if (strncmp(tokens[0],"HP",2)==0) - { - arg_ftype = FILT_HP; - } else if (strncmp(tokens[0],"BP",2)==0) - { - arg_ftype = FILT_BP; - } else if (strncmp(tokens[0],"BS",2)==0) - { - arg_ftype = FILT_BS; - } else - { - arg_ftype = FILT_LP; - } - - PNL(); - //calculate - lp_coef = malloc(sizeof(double)*arg_n); - memset(lp_coef, 0, sizeof(double)*arg_n); - - PNL(); - filt.type = arg_ftype; - filt.fs = arg_fs; - filt.fc1 = arg_fc1; - filt.fc2 = arg_fc2; - filt.wtype = arg_wtype; - filt.n = arg_n; - filt.beta = arg_beta; - - PNL(); - filter_calc(&filt, lp_coef, arg_n); - - - //prepare output - for (i=0;i -#include -#include -#include - -#include "sds.h" -#include "util.h" -#include "debug.h" - -void *cmd_fir(void *data); - -#endif \ No newline at end of file diff --git a/cmd_fir1p.c b/cmd_fir1p.c deleted file mode 100644 index b011719..0000000 --- a/cmd_fir1p.c +++ /dev/null @@ -1,94 +0,0 @@ -#include "cmd_fir1p.h" - -#define FIR_SIZE 12 - -double fir_coef[FIR_SIZE] = -{ - -0.0044384, -0.0041841, 0.0130183, 0.0746628, - 0.1720210, 0.2489204, 0.2489204, 0.1720210, - 0.0746628, 0.0130183, -0.0041841, -0.0044384 -}; - -#define MAX_INPUT_LEN 80 -#define BUFFER_LEN (FIR_SIZE-1+MAX_INPUT_LEN) -double insamp[BUFFER_LEN]; - -int fir1filter(double *coeffs, double *input, double *output, - int length, int filter_length) -{ - double acc; - double *coeffp; - double *inputp; - int n; - int k; - - memcpy(&insamp[filter_length-1], input, length*sizeof(double)); - - for (n=0; n -#include - -#include "sds.h" -#include "util.h" -#include "debug.h" - -void *cmd_fir1p(void *data); - -#endif \ No newline at end of file diff --git a/cmd_loadavg.c b/cmd_loadavg.c deleted file mode 100644 index a9a4b28..0000000 --- a/cmd_loadavg.c +++ /dev/null @@ -1,28 +0,0 @@ -#include "cmd_loadavg.h" - -void *cmd_loadavg(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - double loadavg_d[3]; - - printf("LOADAVG\n"); - - fret = getloadavg(loadavg_d, 3); - if (fret<0) - { - ret = alloc_new_str("Cant get load avg mate\n"); - } - - printf("1M %lf 5M %lf 15M %lf\n", loadavg_d[0], loadavg_d[1], loadavg_d[2]); - snprintf(buf, buf_size,"1M %.1f 5M %.1f 15M %.1f\n", loadavg_d[0], loadavg_d[1], loadavg_d[2]); - - ret = alloc_new_str(buf); - - return ret; -} \ No newline at end of file diff --git a/cmd_loadavg.h b/cmd_loadavg.h deleted file mode 100644 index d3bd9c2..0000000 --- a/cmd_loadavg.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CMD_LOADAVG_H -#define __CMD_LOADAVG_H - -#include -#include - -#include "util.h" - -void *cmd_loadavg(void *data); - -#endif \ No newline at end of file diff --git a/cmd_ping.c b/cmd_ping.c deleted file mode 100644 index a8e3c59..0000000 --- a/cmd_ping.c +++ /dev/null @@ -1,13 +0,0 @@ -#include "cmd_ping.h" - -void *cmd_ping(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - - printf("PONG\n"); - - ret = alloc_new_str("pong"); - - return ret; -} \ No newline at end of file diff --git a/cmd_ping.h b/cmd_ping.h deleted file mode 100644 index fef18c6..0000000 --- a/cmd_ping.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CMD_PING_H -#define __CMD_PING_H - -#include -#include - -#include "util.h" - -void *cmd_ping(void *data); - -#endif \ No newline at end of file diff --git a/cmd_rand.c b/cmd_rand.c deleted file mode 100644 index 58f2efe..0000000 --- a/cmd_rand.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "cmd_rand.h" - - -void *cmd_rand(void *data) -{ - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("RAND\n"); - - - snprintf(buf, buf_size, "4"); - ret = alloc_new_str(buf); - - return ret; -} diff --git a/cmd_rand.h b/cmd_rand.h deleted file mode 100644 index 14f5c7e..0000000 --- a/cmd_rand.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __CMD_RAND_H -#define __CMD_RAND_H - -#include -#include - -#include "util.h" -#include "debug.h" - -void *cmd_rand(void *data); - -#endif \ No newline at end of file diff --git a/cmd_rand_libc.c b/cmd_rand_libc.c deleted file mode 100644 index d72bc45..0000000 --- a/cmd_rand_libc.c +++ /dev/null @@ -1,50 +0,0 @@ -#include "cmd_rand_libc.h" - - -void *cmd_rand_libc(void *data) -{ - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("RAND LIBC\n"); - - int i; - int count; - int rand_val; - sds params; - sds out_result; - sds *tokens; - - if (data == NULL) - { - rand_val = rand(); - snprintf(buf, buf_size, "%d", rand_val); - } else { - //cut output to 512 - char str_integer[16]; - int rand_state; - - params = sdsnew(data); - out_result = sdsempty(); - tokens = sdssplitargs(params, &count); - for (i=0;i -#include - -#include "sds.h" -#include "util.h" -#include "debug.h" - -void *cmd_rand_libc(void *data); - -#endif \ No newline at end of file diff --git a/cmd_rusage.c b/cmd_rusage.c deleted file mode 100644 index 3dc5d21..0000000 --- a/cmd_rusage.c +++ /dev/null @@ -1,34 +0,0 @@ - -#include "cmd_rusage.h" - -void *cmd_rusage(void *data) -{ - char *ret = NULL; - int fret=-1; - - const int buf_size = 128; - char buf[buf_size+1]; - - struct rusage cur_proc_rusage; - - printf("RUSAGE\n"); - - fret = getrusage(RUSAGE_SELF, &cur_proc_rusage); - if (fret<0) - { - ret = alloc_new_str("Cant get rusage mate\n"); - } - - printf("USER %ld SYS %ld\n", - cur_proc_rusage.ru_utime.tv_sec, - cur_proc_rusage.ru_stime.tv_sec - ); - snprintf(buf, buf_size, "USER %ld SYS %ld\n", - cur_proc_rusage.ru_utime.tv_sec, - cur_proc_rusage.ru_stime.tv_sec - ); - - ret = alloc_new_str(buf); - - return ret; -} diff --git a/cmd_rusage.h b/cmd_rusage.h deleted file mode 100644 index 5e35317..0000000 --- a/cmd_rusage.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef __CMD_RUSAGE_H -#define __CMD_RUSAGE_H - -#include -#include - -#include -#include - -#include "util.h" - -void *cmd_rusage(void *data); - -#endif \ No newline at end of file diff --git a/cmd_sha1.c b/cmd_sha1.c deleted file mode 100644 index 4472ed1..0000000 --- a/cmd_sha1.c +++ /dev/null @@ -1,41 +0,0 @@ -#include "cmd_sha1.h" - -void *cmd_sha1(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - int fret=-1; - - - int i; - char hash_result[21]; - char hex_result[41]; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("SHA1\n"); - - - if (param == NULL) - { - ret = alloc_new_str("No params mate\n"); - return ret; - } - - SHA1(hash_result, param, strlen(param)); - - //cool way how to convert array to string - for (i=0;i<20;i++) - { - sprintf(hex_result+(2*i), "%02x", hash_result[i]&0xff); - } - hex_result[40]=0x0; - - - snprintf(buf, buf_size, "sha1 %s\n",hex_result); - ret = alloc_new_str(buf); - - - return ret; -} \ No newline at end of file diff --git a/cmd_sha1.h b/cmd_sha1.h deleted file mode 100644 index 69a7bc8..0000000 --- a/cmd_sha1.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __CMD_SHA1_H -#define __CMD_SHA1_H - -#include -#include - -#include "util.h" -#include "sha1.h" - -void *cmd_sha1(void *data); - -#endif \ No newline at end of file diff --git a/cmd_uptime.c b/cmd_uptime.c deleted file mode 100644 index 6a9c963..0000000 --- a/cmd_uptime.c +++ /dev/null @@ -1,34 +0,0 @@ -#include "cmd_uptime.h" - -#define PROCFS_PATH "/proc" -#define PROCFS_UPTIME_PATH PROCFS_PATH "/uptime" - -void *cmd_uptime(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("UPTIME\n"); - - FILE *f=NULL; - double d1,d2; - int i1,i2; - - f = fopen(PROCFS_UPTIME_PATH,"r"); - fscanf(f,"%lf %lf", &d1, &d2); - fclose(f); - - printf("Readed %lf %lf\n", d1, d2); - i1 = d1; - i2 = d2; - - printf("Days %d Hours %d Minutes %d\n",i1/(3600*24),i1/(3600)%24, (i1/60)%60); - snprintf(buf, buf_size,"%dd %dh %dm\n",i1/(3600*24),i1/(3600)%24, (i1/60)%60); - - ret = alloc_new_str(buf); - - return ret; -} \ No newline at end of file diff --git a/cmd_uptime.h b/cmd_uptime.h deleted file mode 100644 index 3906cd2..0000000 --- a/cmd_uptime.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CMD_UPTIME_H -#define __CMD_UPTIME_H - -#include -#include - -#include "util.h" - -void *cmd_uptime(void *data); - -#endif \ No newline at end of file diff --git a/cmd_version.c b/cmd_version.c deleted file mode 100644 index d919c60..0000000 --- a/cmd_version.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "cmd_version.h" - -void *cmd_version(void *data) -{ - char *param = (char *)data; - char *ret = NULL; - - const int buf_size = 128; - char buf[buf_size+1]; - - printf("VERSION\n"); - - snprintf(buf, buf_size, "VERSION:0.0.3" " DATE:" VERSION_DATE " COMMIT:" VERSION_COMMIT "\n"); - - ret = alloc_new_str(buf); -} \ No newline at end of file diff --git a/cmd_version.h b/cmd_version.h deleted file mode 100644 index 23cd639..0000000 --- a/cmd_version.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef __CMD_VERSION_H -#define __CMD_VERSION_H - -#include -#include - -#include "util.h" - - -//Auto generated in Makefile -#include "version.h" - -void *cmd_version(void *data); - -#endif - - diff --git a/config_all_cmds.h b/config_all_cmds.h new file mode 100644 index 0000000..8847d7d --- /dev/null +++ b/config_all_cmds.h @@ -0,0 +1,18 @@ +#ifndef __CONFIG_CMD_HEADERS_H +#define __CONFIG_CMD_HEADERS_H +#include "cmd/cmd_rand.h" +#include "cmd/cmd_cmd.h" +#include "cmd/cmd_rusage.h" +#include "cmd/cmd_version.h" +#include "cmd/cmd_cookie.h" +#include "cmd/cmd_sha1.h" +#include "cmd/cmd_fir1p.h" +#include "cmd/cmd_loadavg.h" +#include "cmd/cmd_uptime.h" +#include "cmd/cmd_rand_libc.h" +#include "cmd/cmd_botu.h" +#include "cmd/cmd_ping.h" +#include "cmd/cmd_fir.h" +#include "cmd/cmd_sum.h" +#include "cmd/cmd_date.h" +#endif diff --git a/config_cmds.h b/config_cmds.h index c206ca6..9adfe7a 100644 --- a/config_cmds.h +++ b/config_cmds.h @@ -9,20 +9,7 @@ typedef struct single_cmd_def //list all include files with commands -#include "cmd_date.h" -#include "cmd_uptime.h" -#include "cmd_version.h" -#include "cmd_ping.h" -#include "cmd_loadavg.h" -#include "cmd_rusage.h" -#include "cmd_cmd.h" -#include "cmd_sha1.h" -#include "cmd_cookie.h" -#include "cmd_botu.h" -#include "cmd_fir1p.h" -#include "cmd_rand.h" -#include "cmd_rand_libc.h" -#include "cmd_fir.h" +#include "config_all_cmds.h" //some commands have aliases for compat with some developerslv bots //nothing else comaptible will be added, as its not about "standarts" diff --git a/extlibs/sds.c b/extlibs/sds.c new file mode 100644 index 0000000..eafa13c --- /dev/null +++ b/extlibs/sds.c @@ -0,0 +1,1277 @@ +/* SDSLib 2.0 -- A C dynamic strings library + * + * Copyright (c) 2006-2015, Salvatore Sanfilippo + * Copyright (c) 2015, Oran Agra + * Copyright (c) 2015, Redis Labs, Inc + * 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 Redis 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 OWNER 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 +#include +#include +#include +#include +#include +#include "sds.h" +#include "sdsalloc.h" + +static inline int sdsHdrSize(char type) { + switch(type&SDS_TYPE_MASK) { + case SDS_TYPE_5: + return sizeof(struct sdshdr5); + case SDS_TYPE_8: + return sizeof(struct sdshdr8); + case SDS_TYPE_16: + return sizeof(struct sdshdr16); + case SDS_TYPE_32: + return sizeof(struct sdshdr32); + case SDS_TYPE_64: + return sizeof(struct sdshdr64); + } + return 0; +} + +static inline char sdsReqType(size_t string_size) { + if (string_size < 1<<5) + return SDS_TYPE_5; + if (string_size < 1<<8) + return SDS_TYPE_8; + if (string_size < 1<<16) + return SDS_TYPE_16; +#if (LONG_MAX == LLONG_MAX) + if (string_size < 1ll<<32) + return SDS_TYPE_32; +#endif + return SDS_TYPE_64; +} + +/* Create a new sds string with the content specified by the 'init' pointer + * and 'initlen'. + * If NULL is used for 'init' the string is initialized with zero bytes. + * + * The string is always null-termined (all the sds strings are, always) so + * even if you create an sds string with: + * + * mystring = sdsnewlen("abc",3); + * + * You can print the string with printf() as there is an implicit \0 at the + * end of the string. However the string is binary safe and can contain + * \0 characters in the middle, as the length is stored in the sds header. */ +sds sdsnewlen(const void *init, size_t initlen) { + void *sh; + sds s; + char type = sdsReqType(initlen); + /* Empty strings are usually created in order to append. Use type 8 + * since type 5 is not good at this. */ + if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8; + int hdrlen = sdsHdrSize(type); + unsigned char *fp; /* flags pointer. */ + + sh = s_malloc(hdrlen+initlen+1); + if (!init) + memset(sh, 0, hdrlen+initlen+1); + if (sh == NULL) return NULL; + s = (char*)sh+hdrlen; + fp = ((unsigned char*)s)-1; + switch(type) { + case SDS_TYPE_5: { + *fp = type | (initlen << SDS_TYPE_BITS); + break; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8,s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16,s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32,s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64,s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + } + if (initlen && init) + memcpy(s, init, initlen); + s[initlen] = '\0'; + return s; +} + +/* Create an empty (zero length) sds string. Even in this case the string + * always has an implicit null term. */ +sds sdsempty(void) { + return sdsnewlen("",0); +} + +/* Create a new sds string starting from a null terminated C string. */ +sds sdsnew(const char *init) { + size_t initlen = (init == NULL) ? 0 : strlen(init); + return sdsnewlen(init, initlen); +} + +/* Duplicate an sds string. */ +sds sdsdup(const sds s) { + return sdsnewlen(s, sdslen(s)); +} + +/* Free an sds string. No operation is performed if 's' is NULL. */ +void sdsfree(sds s) { + if (s == NULL) return; + s_free((char*)s-sdsHdrSize(s[-1])); +} + +/* Set the sds string length to the length as obtained with strlen(), so + * considering as content only up to the first null term character. + * + * This function is useful when the sds string is hacked manually in some + * way, like in the following example: + * + * s = sdsnew("foobar"); + * s[2] = '\0'; + * sdsupdatelen(s); + * printf("%d\n", sdslen(s)); + * + * The output will be "2", but if we comment out the call to sdsupdatelen() + * the output will be "6" as the string was modified but the logical length + * remains 6 bytes. */ +void sdsupdatelen(sds s) { + int reallen = strlen(s); + sdssetlen(s, reallen); +} + +/* Modify an sds string in-place to make it empty (zero length). + * However all the existing buffer is not discarded but set as free space + * so that next append operations will not require allocations up to the + * number of bytes previously available. */ +void sdsclear(sds s) { + sdssetlen(s, 0); + s[0] = '\0'; +} + +/* Enlarge the free space at the end of the sds string so that the caller + * is sure that after calling this function can overwrite up to addlen + * bytes after the end of the string, plus one more byte for nul term. + * + * Note: this does not change the *length* of the sds string as returned + * by sdslen(), but only the free buffer space we have. */ +sds sdsMakeRoomFor(sds s, size_t addlen) { + void *sh, *newsh; + size_t avail = sdsavail(s); + size_t len, newlen; + char type, oldtype = s[-1] & SDS_TYPE_MASK; + int hdrlen; + + /* Return ASAP if there is enough space left. */ + if (avail >= addlen) return s; + + len = sdslen(s); + sh = (char*)s-sdsHdrSize(oldtype); + newlen = (len+addlen); + if (newlen < SDS_MAX_PREALLOC) + newlen *= 2; + else + newlen += SDS_MAX_PREALLOC; + + type = sdsReqType(newlen); + + /* Don't use type 5: the user is appending to the string and type 5 is + * not able to remember empty space, so sdsMakeRoomFor() must be called + * at every appending operation. */ + if (type == SDS_TYPE_5) type = SDS_TYPE_8; + + hdrlen = sdsHdrSize(type); + if (oldtype==type) { + newsh = s_realloc(sh, hdrlen+newlen+1); + if (newsh == NULL) return NULL; + s = (char*)newsh+hdrlen; + } else { + /* Since the header size changes, need to move the string forward, + * and can't use realloc */ + newsh = s_malloc(hdrlen+newlen+1); + if (newsh == NULL) return NULL; + memcpy((char*)newsh+hdrlen, s, len+1); + s_free(sh); + s = (char*)newsh+hdrlen; + s[-1] = type; + sdssetlen(s, len); + } + sdssetalloc(s, newlen); + return s; +} + +/* Reallocate the sds string so that it has no free space at the end. The + * contained string remains not altered, but next concatenation operations + * will require a reallocation. + * + * After the call, the passed sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. */ +sds sdsRemoveFreeSpace(sds s) { + void *sh, *newsh; + char type, oldtype = s[-1] & SDS_TYPE_MASK; + int hdrlen; + size_t len = sdslen(s); + sh = (char*)s-sdsHdrSize(oldtype); + + type = sdsReqType(len); + hdrlen = sdsHdrSize(type); + if (oldtype==type) { + newsh = s_realloc(sh, hdrlen+len+1); + if (newsh == NULL) return NULL; + s = (char*)newsh+hdrlen; + } else { + newsh = s_malloc(hdrlen+len+1); + if (newsh == NULL) return NULL; + memcpy((char*)newsh+hdrlen, s, len+1); + s_free(sh); + s = (char*)newsh+hdrlen; + s[-1] = type; + sdssetlen(s, len); + } + sdssetalloc(s, len); + return s; +} + +/* Return the total size of the allocation of the specifed sds string, + * including: + * 1) The sds header before the pointer. + * 2) The string. + * 3) The free buffer at the end if any. + * 4) The implicit null term. + */ +size_t sdsAllocSize(sds s) { + size_t alloc = sdsalloc(s); + return sdsHdrSize(s[-1])+alloc+1; +} + +/* Return the pointer of the actual SDS allocation (normally SDS strings + * are referenced by the start of the string buffer). */ +void *sdsAllocPtr(sds s) { + return (void*) (s-sdsHdrSize(s[-1])); +} + +/* Increment the sds length and decrements the left free space at the + * end of the string according to 'incr'. Also set the null term + * in the new end of the string. + * + * This function is used in order to fix the string length after the + * user calls sdsMakeRoomFor(), writes something after the end of + * the current string, and finally needs to set the new length. + * + * Note: it is possible to use a negative increment in order to + * right-trim the string. + * + * Usage example: + * + * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the + * following schema, to cat bytes coming from the kernel to the end of an + * sds string without copying into an intermediate buffer: + * + * oldlen = sdslen(s); + * s = sdsMakeRoomFor(s, BUFFER_SIZE); + * nread = read(fd, s+oldlen, BUFFER_SIZE); + * ... check for nread <= 0 and handle it ... + * sdsIncrLen(s, nread); + */ +void sdsIncrLen(sds s, int incr) { + unsigned char flags = s[-1]; + size_t len; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: { + unsigned char *fp = ((unsigned char*)s)-1; + unsigned char oldlen = SDS_TYPE_5_LEN(flags); + assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr))); + *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS); + len = oldlen+incr; + break; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8,s); + assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16,s); + assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32,s); + assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64,s); + assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr))); + len = (sh->len += incr); + break; + } + default: len = 0; /* Just to avoid compilation warnings. */ + } + s[len] = '\0'; +} + +/* Grow the sds to have the specified length. Bytes that were not part of + * the original length of the sds will be set to zero. + * + * if the specified length is smaller than the current length, no operation + * is performed. */ +sds sdsgrowzero(sds s, size_t len) { + size_t curlen = sdslen(s); + + if (len <= curlen) return s; + s = sdsMakeRoomFor(s,len-curlen); + if (s == NULL) return NULL; + + /* Make sure added region doesn't contain garbage */ + memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ + sdssetlen(s, len); + return s; +} + +/* Append the specified binary-safe string pointed by 't' of 'len' bytes to the + * end of the specified sds string 's'. + * + * After the call, the passed sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. */ +sds sdscatlen(sds s, const void *t, size_t len) { + size_t curlen = sdslen(s); + + s = sdsMakeRoomFor(s,len); + if (s == NULL) return NULL; + memcpy(s+curlen, t, len); + sdssetlen(s, curlen+len); + s[curlen+len] = '\0'; + return s; +} + +/* Append the specified null termianted C string to the sds string 's'. + * + * After the call, the passed sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. */ +sds sdscat(sds s, const char *t) { + return sdscatlen(s, t, strlen(t)); +} + +/* Append the specified sds 't' to the existing sds 's'. + * + * After the call, the modified sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. */ +sds sdscatsds(sds s, const sds t) { + return sdscatlen(s, t, sdslen(t)); +} + +/* Destructively modify the sds string 's' to hold the specified binary + * safe string pointed by 't' of length 'len' bytes. */ +sds sdscpylen(sds s, const char *t, size_t len) { + if (sdsalloc(s) < len) { + s = sdsMakeRoomFor(s,len-sdslen(s)); + if (s == NULL) return NULL; + } + memcpy(s, t, len); + s[len] = '\0'; + sdssetlen(s, len); + return s; +} + +/* Like sdscpylen() but 't' must be a null-termined string so that the length + * of the string is obtained with strlen(). */ +sds sdscpy(sds s, const char *t) { + return sdscpylen(s, t, strlen(t)); +} + +/* Helper for sdscatlonglong() doing the actual number -> string + * conversion. 's' must point to a string with room for at least + * SDS_LLSTR_SIZE bytes. + * + * The function returns the length of the null-terminated string + * representation stored at 's'. */ +#define SDS_LLSTR_SIZE 21 +int sdsll2str(char *s, long long value) { + char *p, aux; + unsigned long long v; + size_t l; + + /* Generate the string representation, this method produces + * an reversed string. */ + v = (value < 0) ? -value : value; + p = s; + do { + *p++ = '0'+(v%10); + v /= 10; + } while(v); + if (value < 0) *p++ = '-'; + + /* Compute length and add null term. */ + l = p-s; + *p = '\0'; + + /* Reverse the string. */ + p--; + while(s < p) { + aux = *s; + *s = *p; + *p = aux; + s++; + p--; + } + return l; +} + +/* Identical sdsll2str(), but for unsigned long long type. */ +int sdsull2str(char *s, unsigned long long v) { + char *p, aux; + size_t l; + + /* Generate the string representation, this method produces + * an reversed string. */ + p = s; + do { + *p++ = '0'+(v%10); + v /= 10; + } while(v); + + /* Compute length and add null term. */ + l = p-s; + *p = '\0'; + + /* Reverse the string. */ + p--; + while(s < p) { + aux = *s; + *s = *p; + *p = aux; + s++; + p--; + } + return l; +} + +/* Create an sds string from a long long value. It is much faster than: + * + * sdscatprintf(sdsempty(),"%lld\n", value); + */ +sds sdsfromlonglong(long long value) { + char buf[SDS_LLSTR_SIZE]; + int len = sdsll2str(buf,value); + + return sdsnewlen(buf,len); +} + +/* Like sdscatprintf() but gets va_list instead of being variadic. */ +sds sdscatvprintf(sds s, const char *fmt, va_list ap) { + va_list cpy; + char staticbuf[1024], *buf = staticbuf, *t; + size_t buflen = strlen(fmt)*2; + + /* We try to start using a static buffer for speed. + * If not possible we revert to heap allocation. */ + if (buflen > sizeof(staticbuf)) { + buf = s_malloc(buflen); + if (buf == NULL) return NULL; + } else { + buflen = sizeof(staticbuf); + } + + /* Try with buffers two times bigger every time we fail to + * fit the string in the current buffer size. */ + while(1) { + buf[buflen-2] = '\0'; + va_copy(cpy,ap); + vsnprintf(buf, buflen, fmt, cpy); + va_end(cpy); + if (buf[buflen-2] != '\0') { + if (buf != staticbuf) s_free(buf); + buflen *= 2; + buf = s_malloc(buflen); + if (buf == NULL) return NULL; + continue; + } + break; + } + + /* Finally concat the obtained string to the SDS string and return it. */ + t = sdscat(s, buf); + if (buf != staticbuf) s_free(buf); + return t; +} + +/* Append to the sds string 's' a string obtained using printf-alike format + * specifier. + * + * After the call, the modified sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. + * + * Example: + * + * s = sdsnew("Sum is: "); + * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b). + * + * Often you need to create a string from scratch with the printf-alike + * format. When this is the need, just use sdsempty() as the target string: + * + * s = sdscatprintf(sdsempty(), "... your format ...", args); + */ +sds sdscatprintf(sds s, const char *fmt, ...) { + va_list ap; + char *t; + va_start(ap, fmt); + t = sdscatvprintf(s,fmt,ap); + va_end(ap); + return t; +} + +/* This function is similar to sdscatprintf, but much faster as it does + * not rely on sprintf() family functions implemented by the libc that + * are often very slow. Moreover directly handling the sds string as + * new data is concatenated provides a performance improvement. + * + * However this function only handles an incompatible subset of printf-alike + * format specifiers: + * + * %s - C String + * %S - SDS string + * %i - signed int + * %I - 64 bit signed integer (long long, int64_t) + * %u - unsigned int + * %U - 64 bit unsigned integer (unsigned long long, uint64_t) + * %% - Verbatim "%" character. + */ +sds sdscatfmt(sds s, char const *fmt, ...) { + size_t initlen = sdslen(s); + const char *f = fmt; + int i; + va_list ap; + + va_start(ap,fmt); + f = fmt; /* Next format specifier byte to process. */ + i = initlen; /* Position of the next byte to write to dest str. */ + while(*f) { + char next, *str; + size_t l; + long long num; + unsigned long long unum; + + /* Make sure there is always space for at least 1 char. */ + if (sdsavail(s)==0) { + s = sdsMakeRoomFor(s,1); + } + + switch(*f) { + case '%': + next = *(f+1); + f++; + switch(next) { + case 's': + case 'S': + str = va_arg(ap,char*); + l = (next == 's') ? strlen(str) : sdslen(str); + if (sdsavail(s) < l) { + s = sdsMakeRoomFor(s,l); + } + memcpy(s+i,str,l); + sdsinclen(s,l); + i += l; + break; + case 'i': + case 'I': + if (next == 'i') + num = va_arg(ap,int); + else + num = va_arg(ap,long long); + { + char buf[SDS_LLSTR_SIZE]; + l = sdsll2str(buf,num); + if (sdsavail(s) < l) { + s = sdsMakeRoomFor(s,l); + } + memcpy(s+i,buf,l); + sdsinclen(s,l); + i += l; + } + break; + case 'u': + case 'U': + if (next == 'u') + unum = va_arg(ap,unsigned int); + else + unum = va_arg(ap,unsigned long long); + { + char buf[SDS_LLSTR_SIZE]; + l = sdsull2str(buf,unum); + if (sdsavail(s) < l) { + s = sdsMakeRoomFor(s,l); + } + memcpy(s+i,buf,l); + sdsinclen(s,l); + i += l; + } + break; + default: /* Handle %% and generally %. */ + s[i++] = next; + sdsinclen(s,1); + break; + } + break; + default: + s[i++] = *f; + sdsinclen(s,1); + break; + } + f++; + } + va_end(ap); + + /* Add null-term */ + s[i] = '\0'; + return s; +} + +/* Remove the part of the string from left and from right composed just of + * contiguous characters found in 'cset', that is a null terminted C string. + * + * After the call, the modified sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. + * + * Example: + * + * s = sdsnew("AA...AA.a.aa.aHelloWorld :::"); + * s = sdstrim(s,"Aa. :"); + * printf("%s\n", s); + * + * Output will be just "Hello World". + */ +sds sdstrim(sds s, const char *cset) { + char *start, *end, *sp, *ep; + size_t len; + + sp = start = s; + ep = end = s+sdslen(s)-1; + while(sp <= end && strchr(cset, *sp)) sp++; + while(ep > sp && strchr(cset, *ep)) ep--; + len = (sp > ep) ? 0 : ((ep-sp)+1); + if (s != sp) memmove(s, sp, len); + s[len] = '\0'; + sdssetlen(s,len); + return s; +} + +/* Turn the string into a smaller (or equal) string containing only the + * substring specified by the 'start' and 'end' indexes. + * + * start and end can be negative, where -1 means the last character of the + * string, -2 the penultimate character, and so forth. + * + * The interval is inclusive, so the start and end characters will be part + * of the resulting string. + * + * The string is modified in-place. + * + * Example: + * + * s = sdsnew("Hello World"); + * sdsrange(s,1,-1); => "ello World" + */ +void sdsrange(sds s, int start, int end) { + size_t newlen, len = sdslen(s); + + if (len == 0) return; + if (start < 0) { + start = len+start; + if (start < 0) start = 0; + } + if (end < 0) { + end = len+end; + if (end < 0) end = 0; + } + newlen = (start > end) ? 0 : (end-start)+1; + if (newlen != 0) { + if (start >= (signed)len) { + newlen = 0; + } else if (end >= (signed)len) { + end = len-1; + newlen = (start > end) ? 0 : (end-start)+1; + } + } else { + start = 0; + } + if (start && newlen) memmove(s, s+start, newlen); + s[newlen] = 0; + sdssetlen(s,newlen); +} + +/* Apply tolower() to every character of the sds string 's'. */ +void sdstolower(sds s) { + int len = sdslen(s), j; + + for (j = 0; j < len; j++) s[j] = tolower(s[j]); +} + +/* Apply toupper() to every character of the sds string 's'. */ +void sdstoupper(sds s) { + int len = sdslen(s), j; + + for (j = 0; j < len; j++) s[j] = toupper(s[j]); +} + +/* Compare two sds strings s1 and s2 with memcmp(). + * + * Return value: + * + * positive if s1 > s2. + * negative if s1 < s2. + * 0 if s1 and s2 are exactly the same binary string. + * + * If two strings share exactly the same prefix, but one of the two has + * additional characters, the longer string is considered to be greater than + * the smaller one. */ +int sdscmp(const sds s1, const sds s2) { + size_t l1, l2, minlen; + int cmp; + + l1 = sdslen(s1); + l2 = sdslen(s2); + minlen = (l1 < l2) ? l1 : l2; + cmp = memcmp(s1,s2,minlen); + if (cmp == 0) return l1-l2; + return cmp; +} + +/* Split 's' with separator in 'sep'. An array + * of sds strings is returned. *count will be set + * by reference to the number of tokens returned. + * + * On out of memory, zero length string, zero length + * separator, NULL is returned. + * + * Note that 'sep' is able to split a string using + * a multi-character separator. For example + * sdssplit("foo_-_bar","_-_"); will return two + * elements "foo" and "bar". + * + * This version of the function is binary-safe but + * requires length arguments. sdssplit() is just the + * same function but for zero-terminated strings. + */ +sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) { + int elements = 0, slots = 5, start = 0, j; + sds *tokens; + + if (seplen < 1 || len < 0) return NULL; + + tokens = s_malloc(sizeof(sds)*slots); + if (tokens == NULL) return NULL; + + if (len == 0) { + *count = 0; + return tokens; + } + for (j = 0; j < (len-(seplen-1)); j++) { + /* make sure there is room for the next element and the final one */ + if (slots < elements+2) { + sds *newtokens; + + slots *= 2; + newtokens = s_realloc(tokens,sizeof(sds)*slots); + if (newtokens == NULL) goto cleanup; + tokens = newtokens; + } + /* search the separator */ + if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { + tokens[elements] = sdsnewlen(s+start,j-start); + if (tokens[elements] == NULL) goto cleanup; + elements++; + start = j+seplen; + j = j+seplen-1; /* skip the separator */ + } + } + /* Add the final element. We are sure there is room in the tokens array. */ + tokens[elements] = sdsnewlen(s+start,len-start); + if (tokens[elements] == NULL) goto cleanup; + elements++; + *count = elements; + return tokens; + +cleanup: + { + int i; + for (i = 0; i < elements; i++) sdsfree(tokens[i]); + s_free(tokens); + *count = 0; + return NULL; + } +} + +/* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ +void sdsfreesplitres(sds *tokens, int count) { + if (!tokens) return; + while(count--) + sdsfree(tokens[count]); + s_free(tokens); +} + +/* Append to the sds string "s" an escaped string representation where + * all the non-printable characters (tested with isprint()) are turned into + * escapes in the form "\n\r\a...." or "\x". + * + * After the call, the modified sds string is no longer valid and all the + * references must be substituted with the new pointer returned by the call. */ +sds sdscatrepr(sds s, const char *p, size_t len) { + s = sdscatlen(s,"\"",1); + while(len--) { + switch(*p) { + case '\\': + case '"': + s = sdscatprintf(s,"\\%c",*p); + break; + case '\n': s = sdscatlen(s,"\\n",2); break; + case '\r': s = sdscatlen(s,"\\r",2); break; + case '\t': s = sdscatlen(s,"\\t",2); break; + case '\a': s = sdscatlen(s,"\\a",2); break; + case '\b': s = sdscatlen(s,"\\b",2); break; + default: + if (isprint(*p)) + s = sdscatprintf(s,"%c",*p); + else + s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); + break; + } + p++; + } + return sdscatlen(s,"\"",1); +} + +/* Helper function for sdssplitargs() that returns non zero if 'c' + * is a valid hex digit. */ +int is_hex_digit(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F'); +} + +/* Helper function for sdssplitargs() that converts a hex digit into an + * integer from 0 to 15 */ +int hex_digit_to_int(char c) { + switch(c) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + case 'a': case 'A': return 10; + case 'b': case 'B': return 11; + case 'c': case 'C': return 12; + case 'd': case 'D': return 13; + case 'e': case 'E': return 14; + case 'f': case 'F': return 15; + default: return 0; + } +} + +/* Split a line into arguments, where every argument can be in the + * following programming-language REPL-alike form: + * + * foo bar "newline are supported\n" and "\xff\x00otherstuff" + * + * The number of arguments is stored into *argc, and an array + * of sds is returned. + * + * The caller should free the resulting array of sds strings with + * sdsfreesplitres(). + * + * Note that sdscatrepr() is able to convert back a string into + * a quoted string in the same format sdssplitargs() is able to parse. + * + * The function returns the allocated tokens on success, even when the + * input string is empty, or NULL if the input contains unbalanced + * quotes or closed quotes followed by non space characters + * as in: "foo"bar or "foo' + */ +sds *sdssplitargs(const char *line, int *argc) { + const char *p = line; + char *current = NULL; + char **vector = NULL; + + *argc = 0; + while(1) { + /* skip blanks */ + while(*p && isspace(*p)) p++; + if (*p) { + /* get a token */ + int inq=0; /* set to 1 if we are in "quotes" */ + int insq=0; /* set to 1 if we are in 'single quotes' */ + int done=0; + + if (current == NULL) current = sdsempty(); + while(!done) { + if (inq) { + if (*p == '\\' && *(p+1) == 'x' && + is_hex_digit(*(p+2)) && + is_hex_digit(*(p+3))) + { + unsigned char byte; + + byte = (hex_digit_to_int(*(p+2))*16)+ + hex_digit_to_int(*(p+3)); + current = sdscatlen(current,(char*)&byte,1); + p += 3; + } else if (*p == '\\' && *(p+1)) { + char c; + + p++; + switch(*p) { + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'b': c = '\b'; break; + case 'a': c = '\a'; break; + default: c = *p; break; + } + current = sdscatlen(current,&c,1); + } else if (*p == '"') { + /* closing quote must be followed by a space or + * nothing at all. */ + if (*(p+1) && !isspace(*(p+1))) goto err; + done=1; + } else if (!*p) { + /* unterminated quotes */ + goto err; + } else { + current = sdscatlen(current,p,1); + } + } else if (insq) { + if (*p == '\\' && *(p+1) == '\'') { + p++; + current = sdscatlen(current,"'",1); + } else if (*p == '\'') { + /* closing quote must be followed by a space or + * nothing at all. */ + if (*(p+1) && !isspace(*(p+1))) goto err; + done=1; + } else if (!*p) { + /* unterminated quotes */ + goto err; + } else { + current = sdscatlen(current,p,1); + } + } else { + switch(*p) { + case ' ': + case '\n': + case '\r': + case '\t': + case '\0': + done=1; + break; + case '"': + inq=1; + break; + case '\'': + insq=1; + break; + default: + current = sdscatlen(current,p,1); + break; + } + } + if (*p) p++; + } + /* add the token to the vector */ + vector = s_realloc(vector,((*argc)+1)*sizeof(char*)); + vector[*argc] = current; + (*argc)++; + current = NULL; + } else { + /* Even on empty input string return something not NULL. */ + if (vector == NULL) vector = s_malloc(sizeof(void*)); + return vector; + } + } + +err: + while((*argc)--) + sdsfree(vector[*argc]); + s_free(vector); + if (current) sdsfree(current); + *argc = 0; + return NULL; +} + +/* Modify the string substituting all the occurrences of the set of + * characters specified in the 'from' string to the corresponding character + * in the 'to' array. + * + * For instance: sdsmapchars(mystring, "ho", "01", 2) + * will have the effect of turning the string "hello" into "0ell1". + * + * The function returns the sds string pointer, that is always the same + * as the input pointer since no resize is needed. */ +sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) { + size_t j, i, l = sdslen(s); + + for (j = 0; j < l; j++) { + for (i = 0; i < setlen; i++) { + if (s[j] == from[i]) { + s[j] = to[i]; + break; + } + } + } + return s; +} + +/* Join an array of C strings using the specified separator (also a C string). + * Returns the result as an sds string. */ +sds sdsjoin(char **argv, int argc, char *sep) { + sds join = sdsempty(); + int j; + + for (j = 0; j < argc; j++) { + join = sdscat(join, argv[j]); + if (j != argc-1) join = sdscat(join,sep); + } + return join; +} + +/* Like sdsjoin, but joins an array of SDS strings. */ +sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) { + sds join = sdsempty(); + int j; + + for (j = 0; j < argc; j++) { + join = sdscatsds(join, argv[j]); + if (j != argc-1) join = sdscatlen(join,sep,seplen); + } + return join; +} + +/* Wrappers to the allocators used by SDS. Note that SDS will actually + * just use the macros defined into sdsalloc.h in order to avoid to pay + * the overhead of function calls. Here we define these wrappers only for + * the programs SDS is linked to, if they want to touch the SDS internals + * even if they use a different allocator. */ +void *sds_malloc(size_t size) { return s_malloc(size); } +void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); } +void sds_free(void *ptr) { s_free(ptr); } + +#if defined(SDS_TEST_MAIN) +#include +#include "testhelp.h" +#include "limits.h" + +#define UNUSED(x) (void)(x) +int sdsTest(void) { + { + sds x = sdsnew("foo"), y; + + test_cond("Create a string and obtain the length", + sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) + + sdsfree(x); + x = sdsnewlen("foo",2); + test_cond("Create a string with specified length", + sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) + + x = sdscat(x,"bar"); + test_cond("Strings concatenation", + sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); + + x = sdscpy(x,"a"); + test_cond("sdscpy() against an originally longer string", + sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) + + x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); + test_cond("sdscpy() against an originally shorter string", + sdslen(x) == 33 && + memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) + + sdsfree(x); + x = sdscatprintf(sdsempty(),"%d",123); + test_cond("sdscatprintf() seems working in the base case", + sdslen(x) == 3 && memcmp(x,"123\0",4) == 0) + + sdsfree(x); + x = sdsnew("--"); + x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX); + test_cond("sdscatfmt() seems working in the base case", + sdslen(x) == 60 && + memcmp(x,"--Hello Hi! World -9223372036854775808," + "9223372036854775807--",60) == 0) + printf("[%s]\n",x); + + sdsfree(x); + x = sdsnew("--"); + x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX); + test_cond("sdscatfmt() seems working with unsigned numbers", + sdslen(x) == 35 && + memcmp(x,"--4294967295,18446744073709551615--",35) == 0) + + sdsfree(x); + x = sdsnew(" x "); + sdstrim(x," x"); + test_cond("sdstrim() works when all chars match", + sdslen(x) == 0) + + sdsfree(x); + x = sdsnew(" x "); + sdstrim(x," "); + test_cond("sdstrim() works when a single char remains", + sdslen(x) == 1 && x[0] == 'x') + + sdsfree(x); + x = sdsnew("xxciaoyyy"); + sdstrim(x,"xy"); + test_cond("sdstrim() correctly trims characters", + sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) + + y = sdsdup(x); + sdsrange(y,1,1); + test_cond("sdsrange(...,1,1)", + sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) + + sdsfree(y); + y = sdsdup(x); + sdsrange(y,1,-1); + test_cond("sdsrange(...,1,-1)", + sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) + + sdsfree(y); + y = sdsdup(x); + sdsrange(y,-2,-1); + test_cond("sdsrange(...,-2,-1)", + sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) + + sdsfree(y); + y = sdsdup(x); + sdsrange(y,2,1); + test_cond("sdsrange(...,2,1)", + sdslen(y) == 0 && memcmp(y,"\0",1) == 0) + + sdsfree(y); + y = sdsdup(x); + sdsrange(y,1,100); + test_cond("sdsrange(...,1,100)", + sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) + + sdsfree(y); + y = sdsdup(x); + sdsrange(y,100,100); + test_cond("sdsrange(...,100,100)", + sdslen(y) == 0 && memcmp(y,"\0",1) == 0) + + sdsfree(y); + sdsfree(x); + x = sdsnew("foo"); + y = sdsnew("foa"); + test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) + + sdsfree(y); + sdsfree(x); + x = sdsnew("bar"); + y = sdsnew("bar"); + test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) + + sdsfree(y); + sdsfree(x); + x = sdsnew("aar"); + y = sdsnew("bar"); + test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) + + sdsfree(y); + sdsfree(x); + x = sdsnewlen("\a\n\0foo\r",7); + y = sdscatrepr(sdsempty(),x,sdslen(x)); + test_cond("sdscatrepr(...data...)", + memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0) + + { + unsigned int oldfree; + char *p; + int step = 10, j, i; + + sdsfree(x); + sdsfree(y); + x = sdsnew("0"); + test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0); + + /* Run the test a few times in order to hit the first two + * SDS header types. */ + for (i = 0; i < 10; i++) { + int oldlen = sdslen(x); + x = sdsMakeRoomFor(x,step); + int type = x[-1]&SDS_TYPE_MASK; + + test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen); + if (type != SDS_TYPE_5) { + test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step); + oldfree = sdsavail(x); + } + p = x+oldlen; + for (j = 0; j < step; j++) { + p[j] = 'A'+j; + } + sdsIncrLen(x,step); + } + test_cond("sdsMakeRoomFor() content", + memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0); + test_cond("sdsMakeRoomFor() final length",sdslen(x)==101); + + sdsfree(x); + } + } + test_report() + return 0; +} +#endif + +#ifdef SDS_TEST_MAIN +int main(void) { + return sdsTest(); +} +#endif diff --git a/extlibs/sds.h b/extlibs/sds.h new file mode 100644 index 0000000..394f8b5 --- /dev/null +++ b/extlibs/sds.h @@ -0,0 +1,273 @@ +/* SDSLib 2.0 -- A C dynamic strings library + * + * Copyright (c) 2006-2015, Salvatore Sanfilippo + * Copyright (c) 2015, Oran Agra + * Copyright (c) 2015, Redis Labs, Inc + * 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 Redis 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 OWNER 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 __SDS_H +#define __SDS_H + +#define SDS_MAX_PREALLOC (1024*1024) + +#include +#include +#include + +typedef char *sds; + +/* Note: sdshdr5 is never used, we just access the flags byte directly. + * However is here to document the layout of type 5 SDS strings. */ +struct __attribute__ ((__packed__)) sdshdr5 { + unsigned char flags; /* 3 lsb of type, and 5 msb of string length */ + char buf[]; +}; +struct __attribute__ ((__packed__)) sdshdr8 { + uint8_t len; /* used */ + uint8_t alloc; /* excluding the header and null terminator */ + unsigned char flags; /* 3 lsb of type, 5 unused bits */ + char buf[]; +}; +struct __attribute__ ((__packed__)) sdshdr16 { + uint16_t len; /* used */ + uint16_t alloc; /* excluding the header and null terminator */ + unsigned char flags; /* 3 lsb of type, 5 unused bits */ + char buf[]; +}; +struct __attribute__ ((__packed__)) sdshdr32 { + uint32_t len; /* used */ + uint32_t alloc; /* excluding the header and null terminator */ + unsigned char flags; /* 3 lsb of type, 5 unused bits */ + char buf[]; +}; +struct __attribute__ ((__packed__)) sdshdr64 { + uint64_t len; /* used */ + uint64_t alloc; /* excluding the header and null terminator */ + unsigned char flags; /* 3 lsb of type, 5 unused bits */ + char buf[]; +}; + +#define SDS_TYPE_5 0 +#define SDS_TYPE_8 1 +#define SDS_TYPE_16 2 +#define SDS_TYPE_32 3 +#define SDS_TYPE_64 4 +#define SDS_TYPE_MASK 7 +#define SDS_TYPE_BITS 3 +#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T))); +#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T)))) +#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS) + +static inline size_t sdslen(const sds s) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: + return SDS_TYPE_5_LEN(flags); + case SDS_TYPE_8: + return SDS_HDR(8,s)->len; + case SDS_TYPE_16: + return SDS_HDR(16,s)->len; + case SDS_TYPE_32: + return SDS_HDR(32,s)->len; + case SDS_TYPE_64: + return SDS_HDR(64,s)->len; + } + return 0; +} + +static inline size_t sdsavail(const sds s) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: { + return 0; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8,s); + return sh->alloc - sh->len; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16,s); + return sh->alloc - sh->len; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32,s); + return sh->alloc - sh->len; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64,s); + return sh->alloc - sh->len; + } + } + return 0; +} + +static inline void sdssetlen(sds s, size_t newlen) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: + { + unsigned char *fp = ((unsigned char*)s)-1; + *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); + } + break; + case SDS_TYPE_8: + SDS_HDR(8,s)->len = newlen; + break; + case SDS_TYPE_16: + SDS_HDR(16,s)->len = newlen; + break; + case SDS_TYPE_32: + SDS_HDR(32,s)->len = newlen; + break; + case SDS_TYPE_64: + SDS_HDR(64,s)->len = newlen; + break; + } +} + +static inline void sdsinclen(sds s, size_t inc) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: + { + unsigned char *fp = ((unsigned char*)s)-1; + unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc; + *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); + } + break; + case SDS_TYPE_8: + SDS_HDR(8,s)->len += inc; + break; + case SDS_TYPE_16: + SDS_HDR(16,s)->len += inc; + break; + case SDS_TYPE_32: + SDS_HDR(32,s)->len += inc; + break; + case SDS_TYPE_64: + SDS_HDR(64,s)->len += inc; + break; + } +} + +/* sdsalloc() = sdsavail() + sdslen() */ +static inline size_t sdsalloc(const sds s) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: + return SDS_TYPE_5_LEN(flags); + case SDS_TYPE_8: + return SDS_HDR(8,s)->alloc; + case SDS_TYPE_16: + return SDS_HDR(16,s)->alloc; + case SDS_TYPE_32: + return SDS_HDR(32,s)->alloc; + case SDS_TYPE_64: + return SDS_HDR(64,s)->alloc; + } + return 0; +} + +static inline void sdssetalloc(sds s, size_t newlen) { + unsigned char flags = s[-1]; + switch(flags&SDS_TYPE_MASK) { + case SDS_TYPE_5: + /* Nothing to do, this type has no total allocation info. */ + break; + case SDS_TYPE_8: + SDS_HDR(8,s)->alloc = newlen; + break; + case SDS_TYPE_16: + SDS_HDR(16,s)->alloc = newlen; + break; + case SDS_TYPE_32: + SDS_HDR(32,s)->alloc = newlen; + break; + case SDS_TYPE_64: + SDS_HDR(64,s)->alloc = newlen; + break; + } +} + +sds sdsnewlen(const void *init, size_t initlen); +sds sdsnew(const char *init); +sds sdsempty(void); +sds sdsdup(const sds s); +void sdsfree(sds s); +sds sdsgrowzero(sds s, size_t len); +sds sdscatlen(sds s, const void *t, size_t len); +sds sdscat(sds s, const char *t); +sds sdscatsds(sds s, const sds t); +sds sdscpylen(sds s, const char *t, size_t len); +sds sdscpy(sds s, const char *t); + +sds sdscatvprintf(sds s, const char *fmt, va_list ap); +#ifdef __GNUC__ +sds sdscatprintf(sds s, const char *fmt, ...) + __attribute__((format(printf, 2, 3))); +#else +sds sdscatprintf(sds s, const char *fmt, ...); +#endif + +sds sdscatfmt(sds s, char const *fmt, ...); +sds sdstrim(sds s, const char *cset); +void sdsrange(sds s, int start, int end); +void sdsupdatelen(sds s); +void sdsclear(sds s); +int sdscmp(const sds s1, const sds s2); +sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count); +void sdsfreesplitres(sds *tokens, int count); +void sdstolower(sds s); +void sdstoupper(sds s); +sds sdsfromlonglong(long long value); +sds sdscatrepr(sds s, const char *p, size_t len); +sds *sdssplitargs(const char *line, int *argc); +sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen); +sds sdsjoin(char **argv, int argc, char *sep); +sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen); + +/* Low level functions exposed to the user API */ +sds sdsMakeRoomFor(sds s, size_t addlen); +void sdsIncrLen(sds s, int incr); +sds sdsRemoveFreeSpace(sds s); +size_t sdsAllocSize(sds s); +void *sdsAllocPtr(sds s); + +/* Export the allocator used by SDS to the program using SDS. + * Sometimes the program SDS is linked to, may use a different set of + * allocators, but may want to allocate or free things that SDS will + * respectively free or allocate. */ +void *sds_malloc(size_t size); +void *sds_realloc(void *ptr, size_t size); +void sds_free(void *ptr); + +#ifdef REDIS_TEST +int sdsTest(int argc, char *argv[]); +#endif + +#endif diff --git a/extlibs/sdsalloc.h b/extlibs/sdsalloc.h new file mode 100644 index 0000000..f43023c --- /dev/null +++ b/extlibs/sdsalloc.h @@ -0,0 +1,42 @@ +/* SDSLib 2.0 -- A C dynamic strings library + * + * Copyright (c) 2006-2015, Salvatore Sanfilippo + * Copyright (c) 2015, Oran Agra + * Copyright (c) 2015, Redis Labs, Inc + * 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 Redis 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 OWNER 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. + */ + +/* SDS allocator selection. + * + * This file is used in order to change the SDS allocator at compile time. + * Just define the following defines to what you want to use. Also add + * the include of your alternate allocator if needed (not needed in order + * to use the default libc allocator). */ + +#define s_malloc malloc +#define s_realloc realloc +#define s_free free diff --git a/extlibs/sha1.c b/extlibs/sha1.c new file mode 100644 index 0000000..c2bf174 --- /dev/null +++ b/extlibs/sha1.c @@ -0,0 +1,296 @@ +/* +SHA-1 in C +By Steve Reid +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#define SHA1HANDSOFF + +#include +#include + +/* for uint32_t */ +#include + +#include "sha1.h" + + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#elif BYTE_ORDER == BIG_ENDIAN +#define blk0(i) block->l[i] +#else +#error "Endianness not defined!" +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + + +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] +) +{ + uint32_t a, b, c, d, e; + + typedef union + { + unsigned char c[64]; + uint32_t l[16]; + } CHAR64LONG16; + +#ifdef SHA1HANDSOFF + CHAR64LONG16 block[1]; /* use array to appear as a pointer */ + + memcpy(block, buffer, 64); +#else + /* The following had better never be used because it causes the + * pointer-to-const buffer to be cast into a pointer to non-const. + * And the result is written through. I threw a "const" in, hoping + * this will cause a diagnostic. + */ + CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +#ifdef SHA1HANDSOFF + memset(block, '\0', sizeof(block)); +#endif +} + + +/* SHA1Init - Initialize new context */ + +void SHA1Init( + SHA1_CTX * context +) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void SHA1Update( + SHA1_CTX * context, + const unsigned char *data, + uint32_t len +) +{ + uint32_t i; + + uint32_t j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) + context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + SHA1Transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) + { + SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void SHA1Final( + unsigned char digest[20], + SHA1_CTX * context +) +{ + unsigned i; + + unsigned char finalcount[8]; + + unsigned char c; + +#if 0 /* untested "improvement" by DHR */ + /* Convert context->count to a sequence of bytes + * in finalcount. Second element first, but + * big-endian order within element. + * But we do it all backwards. + */ + unsigned char *fcp = &finalcount[8]; + + for (i = 0; i < 2; i++) + { + uint32_t t = context->count[i]; + + int j; + + for (j = 0; j < 4; t >>= 8, j++) + *--fcp = (unsigned char) t} +#else + for (i = 0; i < 8; i++) + { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ + } +#endif + c = 0200; + SHA1Update(context, &c, 1); + while ((context->count[0] & 504) != 448) + { + c = 0000; + SHA1Update(context, &c, 1); + } + SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ + for (i = 0; i < 20; i++) + { + digest[i] = (unsigned char) + ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + /* Wipe variables */ + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void SHA1( + char *hash_out, + const char *str, + int len) +{ + SHA1_CTX ctx; + unsigned int ii; + + SHA1Init(&ctx); + for (ii=0; ii + 100% Public Domain + */ + +#include "stdint.h" + +typedef struct +{ + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; +} SHA1_CTX; + +void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] + ); + +void SHA1Init( + SHA1_CTX * context + ); + +void SHA1Update( + SHA1_CTX * context, + const unsigned char *data, + uint32_t len + ); + +void SHA1Final( + unsigned char digest[20], + SHA1_CTX * context + ); + +void SHA1( + char *hash_out, + const char *str, + int len); + +#endif /* SHA1_H */ diff --git a/sds.c b/sds.c deleted file mode 100644 index eafa13c..0000000 --- a/sds.c +++ /dev/null @@ -1,1277 +0,0 @@ -/* SDSLib 2.0 -- A C dynamic strings library - * - * Copyright (c) 2006-2015, Salvatore Sanfilippo - * Copyright (c) 2015, Oran Agra - * Copyright (c) 2015, Redis Labs, Inc - * 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 Redis 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 OWNER 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 -#include -#include -#include -#include -#include -#include "sds.h" -#include "sdsalloc.h" - -static inline int sdsHdrSize(char type) { - switch(type&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return sizeof(struct sdshdr5); - case SDS_TYPE_8: - return sizeof(struct sdshdr8); - case SDS_TYPE_16: - return sizeof(struct sdshdr16); - case SDS_TYPE_32: - return sizeof(struct sdshdr32); - case SDS_TYPE_64: - return sizeof(struct sdshdr64); - } - return 0; -} - -static inline char sdsReqType(size_t string_size) { - if (string_size < 1<<5) - return SDS_TYPE_5; - if (string_size < 1<<8) - return SDS_TYPE_8; - if (string_size < 1<<16) - return SDS_TYPE_16; -#if (LONG_MAX == LLONG_MAX) - if (string_size < 1ll<<32) - return SDS_TYPE_32; -#endif - return SDS_TYPE_64; -} - -/* Create a new sds string with the content specified by the 'init' pointer - * and 'initlen'. - * If NULL is used for 'init' the string is initialized with zero bytes. - * - * The string is always null-termined (all the sds strings are, always) so - * even if you create an sds string with: - * - * mystring = sdsnewlen("abc",3); - * - * You can print the string with printf() as there is an implicit \0 at the - * end of the string. However the string is binary safe and can contain - * \0 characters in the middle, as the length is stored in the sds header. */ -sds sdsnewlen(const void *init, size_t initlen) { - void *sh; - sds s; - char type = sdsReqType(initlen); - /* Empty strings are usually created in order to append. Use type 8 - * since type 5 is not good at this. */ - if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8; - int hdrlen = sdsHdrSize(type); - unsigned char *fp; /* flags pointer. */ - - sh = s_malloc(hdrlen+initlen+1); - if (!init) - memset(sh, 0, hdrlen+initlen+1); - if (sh == NULL) return NULL; - s = (char*)sh+hdrlen; - fp = ((unsigned char*)s)-1; - switch(type) { - case SDS_TYPE_5: { - *fp = type | (initlen << SDS_TYPE_BITS); - break; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - } - if (initlen && init) - memcpy(s, init, initlen); - s[initlen] = '\0'; - return s; -} - -/* Create an empty (zero length) sds string. Even in this case the string - * always has an implicit null term. */ -sds sdsempty(void) { - return sdsnewlen("",0); -} - -/* Create a new sds string starting from a null terminated C string. */ -sds sdsnew(const char *init) { - size_t initlen = (init == NULL) ? 0 : strlen(init); - return sdsnewlen(init, initlen); -} - -/* Duplicate an sds string. */ -sds sdsdup(const sds s) { - return sdsnewlen(s, sdslen(s)); -} - -/* Free an sds string. No operation is performed if 's' is NULL. */ -void sdsfree(sds s) { - if (s == NULL) return; - s_free((char*)s-sdsHdrSize(s[-1])); -} - -/* Set the sds string length to the length as obtained with strlen(), so - * considering as content only up to the first null term character. - * - * This function is useful when the sds string is hacked manually in some - * way, like in the following example: - * - * s = sdsnew("foobar"); - * s[2] = '\0'; - * sdsupdatelen(s); - * printf("%d\n", sdslen(s)); - * - * The output will be "2", but if we comment out the call to sdsupdatelen() - * the output will be "6" as the string was modified but the logical length - * remains 6 bytes. */ -void sdsupdatelen(sds s) { - int reallen = strlen(s); - sdssetlen(s, reallen); -} - -/* Modify an sds string in-place to make it empty (zero length). - * However all the existing buffer is not discarded but set as free space - * so that next append operations will not require allocations up to the - * number of bytes previously available. */ -void sdsclear(sds s) { - sdssetlen(s, 0); - s[0] = '\0'; -} - -/* Enlarge the free space at the end of the sds string so that the caller - * is sure that after calling this function can overwrite up to addlen - * bytes after the end of the string, plus one more byte for nul term. - * - * Note: this does not change the *length* of the sds string as returned - * by sdslen(), but only the free buffer space we have. */ -sds sdsMakeRoomFor(sds s, size_t addlen) { - void *sh, *newsh; - size_t avail = sdsavail(s); - size_t len, newlen; - char type, oldtype = s[-1] & SDS_TYPE_MASK; - int hdrlen; - - /* Return ASAP if there is enough space left. */ - if (avail >= addlen) return s; - - len = sdslen(s); - sh = (char*)s-sdsHdrSize(oldtype); - newlen = (len+addlen); - if (newlen < SDS_MAX_PREALLOC) - newlen *= 2; - else - newlen += SDS_MAX_PREALLOC; - - type = sdsReqType(newlen); - - /* Don't use type 5: the user is appending to the string and type 5 is - * not able to remember empty space, so sdsMakeRoomFor() must be called - * at every appending operation. */ - if (type == SDS_TYPE_5) type = SDS_TYPE_8; - - hdrlen = sdsHdrSize(type); - if (oldtype==type) { - newsh = s_realloc(sh, hdrlen+newlen+1); - if (newsh == NULL) return NULL; - s = (char*)newsh+hdrlen; - } else { - /* Since the header size changes, need to move the string forward, - * and can't use realloc */ - newsh = s_malloc(hdrlen+newlen+1); - if (newsh == NULL) return NULL; - memcpy((char*)newsh+hdrlen, s, len+1); - s_free(sh); - s = (char*)newsh+hdrlen; - s[-1] = type; - sdssetlen(s, len); - } - sdssetalloc(s, newlen); - return s; -} - -/* Reallocate the sds string so that it has no free space at the end. The - * contained string remains not altered, but next concatenation operations - * will require a reallocation. - * - * After the call, the passed sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. */ -sds sdsRemoveFreeSpace(sds s) { - void *sh, *newsh; - char type, oldtype = s[-1] & SDS_TYPE_MASK; - int hdrlen; - size_t len = sdslen(s); - sh = (char*)s-sdsHdrSize(oldtype); - - type = sdsReqType(len); - hdrlen = sdsHdrSize(type); - if (oldtype==type) { - newsh = s_realloc(sh, hdrlen+len+1); - if (newsh == NULL) return NULL; - s = (char*)newsh+hdrlen; - } else { - newsh = s_malloc(hdrlen+len+1); - if (newsh == NULL) return NULL; - memcpy((char*)newsh+hdrlen, s, len+1); - s_free(sh); - s = (char*)newsh+hdrlen; - s[-1] = type; - sdssetlen(s, len); - } - sdssetalloc(s, len); - return s; -} - -/* Return the total size of the allocation of the specifed sds string, - * including: - * 1) The sds header before the pointer. - * 2) The string. - * 3) The free buffer at the end if any. - * 4) The implicit null term. - */ -size_t sdsAllocSize(sds s) { - size_t alloc = sdsalloc(s); - return sdsHdrSize(s[-1])+alloc+1; -} - -/* Return the pointer of the actual SDS allocation (normally SDS strings - * are referenced by the start of the string buffer). */ -void *sdsAllocPtr(sds s) { - return (void*) (s-sdsHdrSize(s[-1])); -} - -/* Increment the sds length and decrements the left free space at the - * end of the string according to 'incr'. Also set the null term - * in the new end of the string. - * - * This function is used in order to fix the string length after the - * user calls sdsMakeRoomFor(), writes something after the end of - * the current string, and finally needs to set the new length. - * - * Note: it is possible to use a negative increment in order to - * right-trim the string. - * - * Usage example: - * - * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the - * following schema, to cat bytes coming from the kernel to the end of an - * sds string without copying into an intermediate buffer: - * - * oldlen = sdslen(s); - * s = sdsMakeRoomFor(s, BUFFER_SIZE); - * nread = read(fd, s+oldlen, BUFFER_SIZE); - * ... check for nread <= 0 and handle it ... - * sdsIncrLen(s, nread); - */ -void sdsIncrLen(sds s, int incr) { - unsigned char flags = s[-1]; - size_t len; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: { - unsigned char *fp = ((unsigned char*)s)-1; - unsigned char oldlen = SDS_TYPE_5_LEN(flags); - assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr))); - *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS); - len = oldlen+incr; - break; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr))); - len = (sh->len += incr); - break; - } - default: len = 0; /* Just to avoid compilation warnings. */ - } - s[len] = '\0'; -} - -/* Grow the sds to have the specified length. Bytes that were not part of - * the original length of the sds will be set to zero. - * - * if the specified length is smaller than the current length, no operation - * is performed. */ -sds sdsgrowzero(sds s, size_t len) { - size_t curlen = sdslen(s); - - if (len <= curlen) return s; - s = sdsMakeRoomFor(s,len-curlen); - if (s == NULL) return NULL; - - /* Make sure added region doesn't contain garbage */ - memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ - sdssetlen(s, len); - return s; -} - -/* Append the specified binary-safe string pointed by 't' of 'len' bytes to the - * end of the specified sds string 's'. - * - * After the call, the passed sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. */ -sds sdscatlen(sds s, const void *t, size_t len) { - size_t curlen = sdslen(s); - - s = sdsMakeRoomFor(s,len); - if (s == NULL) return NULL; - memcpy(s+curlen, t, len); - sdssetlen(s, curlen+len); - s[curlen+len] = '\0'; - return s; -} - -/* Append the specified null termianted C string to the sds string 's'. - * - * After the call, the passed sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. */ -sds sdscat(sds s, const char *t) { - return sdscatlen(s, t, strlen(t)); -} - -/* Append the specified sds 't' to the existing sds 's'. - * - * After the call, the modified sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. */ -sds sdscatsds(sds s, const sds t) { - return sdscatlen(s, t, sdslen(t)); -} - -/* Destructively modify the sds string 's' to hold the specified binary - * safe string pointed by 't' of length 'len' bytes. */ -sds sdscpylen(sds s, const char *t, size_t len) { - if (sdsalloc(s) < len) { - s = sdsMakeRoomFor(s,len-sdslen(s)); - if (s == NULL) return NULL; - } - memcpy(s, t, len); - s[len] = '\0'; - sdssetlen(s, len); - return s; -} - -/* Like sdscpylen() but 't' must be a null-termined string so that the length - * of the string is obtained with strlen(). */ -sds sdscpy(sds s, const char *t) { - return sdscpylen(s, t, strlen(t)); -} - -/* Helper for sdscatlonglong() doing the actual number -> string - * conversion. 's' must point to a string with room for at least - * SDS_LLSTR_SIZE bytes. - * - * The function returns the length of the null-terminated string - * representation stored at 's'. */ -#define SDS_LLSTR_SIZE 21 -int sdsll2str(char *s, long long value) { - char *p, aux; - unsigned long long v; - size_t l; - - /* Generate the string representation, this method produces - * an reversed string. */ - v = (value < 0) ? -value : value; - p = s; - do { - *p++ = '0'+(v%10); - v /= 10; - } while(v); - if (value < 0) *p++ = '-'; - - /* Compute length and add null term. */ - l = p-s; - *p = '\0'; - - /* Reverse the string. */ - p--; - while(s < p) { - aux = *s; - *s = *p; - *p = aux; - s++; - p--; - } - return l; -} - -/* Identical sdsll2str(), but for unsigned long long type. */ -int sdsull2str(char *s, unsigned long long v) { - char *p, aux; - size_t l; - - /* Generate the string representation, this method produces - * an reversed string. */ - p = s; - do { - *p++ = '0'+(v%10); - v /= 10; - } while(v); - - /* Compute length and add null term. */ - l = p-s; - *p = '\0'; - - /* Reverse the string. */ - p--; - while(s < p) { - aux = *s; - *s = *p; - *p = aux; - s++; - p--; - } - return l; -} - -/* Create an sds string from a long long value. It is much faster than: - * - * sdscatprintf(sdsempty(),"%lld\n", value); - */ -sds sdsfromlonglong(long long value) { - char buf[SDS_LLSTR_SIZE]; - int len = sdsll2str(buf,value); - - return sdsnewlen(buf,len); -} - -/* Like sdscatprintf() but gets va_list instead of being variadic. */ -sds sdscatvprintf(sds s, const char *fmt, va_list ap) { - va_list cpy; - char staticbuf[1024], *buf = staticbuf, *t; - size_t buflen = strlen(fmt)*2; - - /* We try to start using a static buffer for speed. - * If not possible we revert to heap allocation. */ - if (buflen > sizeof(staticbuf)) { - buf = s_malloc(buflen); - if (buf == NULL) return NULL; - } else { - buflen = sizeof(staticbuf); - } - - /* Try with buffers two times bigger every time we fail to - * fit the string in the current buffer size. */ - while(1) { - buf[buflen-2] = '\0'; - va_copy(cpy,ap); - vsnprintf(buf, buflen, fmt, cpy); - va_end(cpy); - if (buf[buflen-2] != '\0') { - if (buf != staticbuf) s_free(buf); - buflen *= 2; - buf = s_malloc(buflen); - if (buf == NULL) return NULL; - continue; - } - break; - } - - /* Finally concat the obtained string to the SDS string and return it. */ - t = sdscat(s, buf); - if (buf != staticbuf) s_free(buf); - return t; -} - -/* Append to the sds string 's' a string obtained using printf-alike format - * specifier. - * - * After the call, the modified sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. - * - * Example: - * - * s = sdsnew("Sum is: "); - * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b). - * - * Often you need to create a string from scratch with the printf-alike - * format. When this is the need, just use sdsempty() as the target string: - * - * s = sdscatprintf(sdsempty(), "... your format ...", args); - */ -sds sdscatprintf(sds s, const char *fmt, ...) { - va_list ap; - char *t; - va_start(ap, fmt); - t = sdscatvprintf(s,fmt,ap); - va_end(ap); - return t; -} - -/* This function is similar to sdscatprintf, but much faster as it does - * not rely on sprintf() family functions implemented by the libc that - * are often very slow. Moreover directly handling the sds string as - * new data is concatenated provides a performance improvement. - * - * However this function only handles an incompatible subset of printf-alike - * format specifiers: - * - * %s - C String - * %S - SDS string - * %i - signed int - * %I - 64 bit signed integer (long long, int64_t) - * %u - unsigned int - * %U - 64 bit unsigned integer (unsigned long long, uint64_t) - * %% - Verbatim "%" character. - */ -sds sdscatfmt(sds s, char const *fmt, ...) { - size_t initlen = sdslen(s); - const char *f = fmt; - int i; - va_list ap; - - va_start(ap,fmt); - f = fmt; /* Next format specifier byte to process. */ - i = initlen; /* Position of the next byte to write to dest str. */ - while(*f) { - char next, *str; - size_t l; - long long num; - unsigned long long unum; - - /* Make sure there is always space for at least 1 char. */ - if (sdsavail(s)==0) { - s = sdsMakeRoomFor(s,1); - } - - switch(*f) { - case '%': - next = *(f+1); - f++; - switch(next) { - case 's': - case 'S': - str = va_arg(ap,char*); - l = (next == 's') ? strlen(str) : sdslen(str); - if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - } - memcpy(s+i,str,l); - sdsinclen(s,l); - i += l; - break; - case 'i': - case 'I': - if (next == 'i') - num = va_arg(ap,int); - else - num = va_arg(ap,long long); - { - char buf[SDS_LLSTR_SIZE]; - l = sdsll2str(buf,num); - if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - } - memcpy(s+i,buf,l); - sdsinclen(s,l); - i += l; - } - break; - case 'u': - case 'U': - if (next == 'u') - unum = va_arg(ap,unsigned int); - else - unum = va_arg(ap,unsigned long long); - { - char buf[SDS_LLSTR_SIZE]; - l = sdsull2str(buf,unum); - if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - } - memcpy(s+i,buf,l); - sdsinclen(s,l); - i += l; - } - break; - default: /* Handle %% and generally %. */ - s[i++] = next; - sdsinclen(s,1); - break; - } - break; - default: - s[i++] = *f; - sdsinclen(s,1); - break; - } - f++; - } - va_end(ap); - - /* Add null-term */ - s[i] = '\0'; - return s; -} - -/* Remove the part of the string from left and from right composed just of - * contiguous characters found in 'cset', that is a null terminted C string. - * - * After the call, the modified sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. - * - * Example: - * - * s = sdsnew("AA...AA.a.aa.aHelloWorld :::"); - * s = sdstrim(s,"Aa. :"); - * printf("%s\n", s); - * - * Output will be just "Hello World". - */ -sds sdstrim(sds s, const char *cset) { - char *start, *end, *sp, *ep; - size_t len; - - sp = start = s; - ep = end = s+sdslen(s)-1; - while(sp <= end && strchr(cset, *sp)) sp++; - while(ep > sp && strchr(cset, *ep)) ep--; - len = (sp > ep) ? 0 : ((ep-sp)+1); - if (s != sp) memmove(s, sp, len); - s[len] = '\0'; - sdssetlen(s,len); - return s; -} - -/* Turn the string into a smaller (or equal) string containing only the - * substring specified by the 'start' and 'end' indexes. - * - * start and end can be negative, where -1 means the last character of the - * string, -2 the penultimate character, and so forth. - * - * The interval is inclusive, so the start and end characters will be part - * of the resulting string. - * - * The string is modified in-place. - * - * Example: - * - * s = sdsnew("Hello World"); - * sdsrange(s,1,-1); => "ello World" - */ -void sdsrange(sds s, int start, int end) { - size_t newlen, len = sdslen(s); - - if (len == 0) return; - if (start < 0) { - start = len+start; - if (start < 0) start = 0; - } - if (end < 0) { - end = len+end; - if (end < 0) end = 0; - } - newlen = (start > end) ? 0 : (end-start)+1; - if (newlen != 0) { - if (start >= (signed)len) { - newlen = 0; - } else if (end >= (signed)len) { - end = len-1; - newlen = (start > end) ? 0 : (end-start)+1; - } - } else { - start = 0; - } - if (start && newlen) memmove(s, s+start, newlen); - s[newlen] = 0; - sdssetlen(s,newlen); -} - -/* Apply tolower() to every character of the sds string 's'. */ -void sdstolower(sds s) { - int len = sdslen(s), j; - - for (j = 0; j < len; j++) s[j] = tolower(s[j]); -} - -/* Apply toupper() to every character of the sds string 's'. */ -void sdstoupper(sds s) { - int len = sdslen(s), j; - - for (j = 0; j < len; j++) s[j] = toupper(s[j]); -} - -/* Compare two sds strings s1 and s2 with memcmp(). - * - * Return value: - * - * positive if s1 > s2. - * negative if s1 < s2. - * 0 if s1 and s2 are exactly the same binary string. - * - * If two strings share exactly the same prefix, but one of the two has - * additional characters, the longer string is considered to be greater than - * the smaller one. */ -int sdscmp(const sds s1, const sds s2) { - size_t l1, l2, minlen; - int cmp; - - l1 = sdslen(s1); - l2 = sdslen(s2); - minlen = (l1 < l2) ? l1 : l2; - cmp = memcmp(s1,s2,minlen); - if (cmp == 0) return l1-l2; - return cmp; -} - -/* Split 's' with separator in 'sep'. An array - * of sds strings is returned. *count will be set - * by reference to the number of tokens returned. - * - * On out of memory, zero length string, zero length - * separator, NULL is returned. - * - * Note that 'sep' is able to split a string using - * a multi-character separator. For example - * sdssplit("foo_-_bar","_-_"); will return two - * elements "foo" and "bar". - * - * This version of the function is binary-safe but - * requires length arguments. sdssplit() is just the - * same function but for zero-terminated strings. - */ -sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) { - int elements = 0, slots = 5, start = 0, j; - sds *tokens; - - if (seplen < 1 || len < 0) return NULL; - - tokens = s_malloc(sizeof(sds)*slots); - if (tokens == NULL) return NULL; - - if (len == 0) { - *count = 0; - return tokens; - } - for (j = 0; j < (len-(seplen-1)); j++) { - /* make sure there is room for the next element and the final one */ - if (slots < elements+2) { - sds *newtokens; - - slots *= 2; - newtokens = s_realloc(tokens,sizeof(sds)*slots); - if (newtokens == NULL) goto cleanup; - tokens = newtokens; - } - /* search the separator */ - if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { - tokens[elements] = sdsnewlen(s+start,j-start); - if (tokens[elements] == NULL) goto cleanup; - elements++; - start = j+seplen; - j = j+seplen-1; /* skip the separator */ - } - } - /* Add the final element. We are sure there is room in the tokens array. */ - tokens[elements] = sdsnewlen(s+start,len-start); - if (tokens[elements] == NULL) goto cleanup; - elements++; - *count = elements; - return tokens; - -cleanup: - { - int i; - for (i = 0; i < elements; i++) sdsfree(tokens[i]); - s_free(tokens); - *count = 0; - return NULL; - } -} - -/* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ -void sdsfreesplitres(sds *tokens, int count) { - if (!tokens) return; - while(count--) - sdsfree(tokens[count]); - s_free(tokens); -} - -/* Append to the sds string "s" an escaped string representation where - * all the non-printable characters (tested with isprint()) are turned into - * escapes in the form "\n\r\a...." or "\x". - * - * After the call, the modified sds string is no longer valid and all the - * references must be substituted with the new pointer returned by the call. */ -sds sdscatrepr(sds s, const char *p, size_t len) { - s = sdscatlen(s,"\"",1); - while(len--) { - switch(*p) { - case '\\': - case '"': - s = sdscatprintf(s,"\\%c",*p); - break; - case '\n': s = sdscatlen(s,"\\n",2); break; - case '\r': s = sdscatlen(s,"\\r",2); break; - case '\t': s = sdscatlen(s,"\\t",2); break; - case '\a': s = sdscatlen(s,"\\a",2); break; - case '\b': s = sdscatlen(s,"\\b",2); break; - default: - if (isprint(*p)) - s = sdscatprintf(s,"%c",*p); - else - s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); - break; - } - p++; - } - return sdscatlen(s,"\"",1); -} - -/* Helper function for sdssplitargs() that returns non zero if 'c' - * is a valid hex digit. */ -int is_hex_digit(char c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || - (c >= 'A' && c <= 'F'); -} - -/* Helper function for sdssplitargs() that converts a hex digit into an - * integer from 0 to 15 */ -int hex_digit_to_int(char c) { - switch(c) { - case '0': return 0; - case '1': return 1; - case '2': return 2; - case '3': return 3; - case '4': return 4; - case '5': return 5; - case '6': return 6; - case '7': return 7; - case '8': return 8; - case '9': return 9; - case 'a': case 'A': return 10; - case 'b': case 'B': return 11; - case 'c': case 'C': return 12; - case 'd': case 'D': return 13; - case 'e': case 'E': return 14; - case 'f': case 'F': return 15; - default: return 0; - } -} - -/* Split a line into arguments, where every argument can be in the - * following programming-language REPL-alike form: - * - * foo bar "newline are supported\n" and "\xff\x00otherstuff" - * - * The number of arguments is stored into *argc, and an array - * of sds is returned. - * - * The caller should free the resulting array of sds strings with - * sdsfreesplitres(). - * - * Note that sdscatrepr() is able to convert back a string into - * a quoted string in the same format sdssplitargs() is able to parse. - * - * The function returns the allocated tokens on success, even when the - * input string is empty, or NULL if the input contains unbalanced - * quotes or closed quotes followed by non space characters - * as in: "foo"bar or "foo' - */ -sds *sdssplitargs(const char *line, int *argc) { - const char *p = line; - char *current = NULL; - char **vector = NULL; - - *argc = 0; - while(1) { - /* skip blanks */ - while(*p && isspace(*p)) p++; - if (*p) { - /* get a token */ - int inq=0; /* set to 1 if we are in "quotes" */ - int insq=0; /* set to 1 if we are in 'single quotes' */ - int done=0; - - if (current == NULL) current = sdsempty(); - while(!done) { - if (inq) { - if (*p == '\\' && *(p+1) == 'x' && - is_hex_digit(*(p+2)) && - is_hex_digit(*(p+3))) - { - unsigned char byte; - - byte = (hex_digit_to_int(*(p+2))*16)+ - hex_digit_to_int(*(p+3)); - current = sdscatlen(current,(char*)&byte,1); - p += 3; - } else if (*p == '\\' && *(p+1)) { - char c; - - p++; - switch(*p) { - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'b': c = '\b'; break; - case 'a': c = '\a'; break; - default: c = *p; break; - } - current = sdscatlen(current,&c,1); - } else if (*p == '"') { - /* closing quote must be followed by a space or - * nothing at all. */ - if (*(p+1) && !isspace(*(p+1))) goto err; - done=1; - } else if (!*p) { - /* unterminated quotes */ - goto err; - } else { - current = sdscatlen(current,p,1); - } - } else if (insq) { - if (*p == '\\' && *(p+1) == '\'') { - p++; - current = sdscatlen(current,"'",1); - } else if (*p == '\'') { - /* closing quote must be followed by a space or - * nothing at all. */ - if (*(p+1) && !isspace(*(p+1))) goto err; - done=1; - } else if (!*p) { - /* unterminated quotes */ - goto err; - } else { - current = sdscatlen(current,p,1); - } - } else { - switch(*p) { - case ' ': - case '\n': - case '\r': - case '\t': - case '\0': - done=1; - break; - case '"': - inq=1; - break; - case '\'': - insq=1; - break; - default: - current = sdscatlen(current,p,1); - break; - } - } - if (*p) p++; - } - /* add the token to the vector */ - vector = s_realloc(vector,((*argc)+1)*sizeof(char*)); - vector[*argc] = current; - (*argc)++; - current = NULL; - } else { - /* Even on empty input string return something not NULL. */ - if (vector == NULL) vector = s_malloc(sizeof(void*)); - return vector; - } - } - -err: - while((*argc)--) - sdsfree(vector[*argc]); - s_free(vector); - if (current) sdsfree(current); - *argc = 0; - return NULL; -} - -/* Modify the string substituting all the occurrences of the set of - * characters specified in the 'from' string to the corresponding character - * in the 'to' array. - * - * For instance: sdsmapchars(mystring, "ho", "01", 2) - * will have the effect of turning the string "hello" into "0ell1". - * - * The function returns the sds string pointer, that is always the same - * as the input pointer since no resize is needed. */ -sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) { - size_t j, i, l = sdslen(s); - - for (j = 0; j < l; j++) { - for (i = 0; i < setlen; i++) { - if (s[j] == from[i]) { - s[j] = to[i]; - break; - } - } - } - return s; -} - -/* Join an array of C strings using the specified separator (also a C string). - * Returns the result as an sds string. */ -sds sdsjoin(char **argv, int argc, char *sep) { - sds join = sdsempty(); - int j; - - for (j = 0; j < argc; j++) { - join = sdscat(join, argv[j]); - if (j != argc-1) join = sdscat(join,sep); - } - return join; -} - -/* Like sdsjoin, but joins an array of SDS strings. */ -sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) { - sds join = sdsempty(); - int j; - - for (j = 0; j < argc; j++) { - join = sdscatsds(join, argv[j]); - if (j != argc-1) join = sdscatlen(join,sep,seplen); - } - return join; -} - -/* Wrappers to the allocators used by SDS. Note that SDS will actually - * just use the macros defined into sdsalloc.h in order to avoid to pay - * the overhead of function calls. Here we define these wrappers only for - * the programs SDS is linked to, if they want to touch the SDS internals - * even if they use a different allocator. */ -void *sds_malloc(size_t size) { return s_malloc(size); } -void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); } -void sds_free(void *ptr) { s_free(ptr); } - -#if defined(SDS_TEST_MAIN) -#include -#include "testhelp.h" -#include "limits.h" - -#define UNUSED(x) (void)(x) -int sdsTest(void) { - { - sds x = sdsnew("foo"), y; - - test_cond("Create a string and obtain the length", - sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) - - sdsfree(x); - x = sdsnewlen("foo",2); - test_cond("Create a string with specified length", - sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) - - x = sdscat(x,"bar"); - test_cond("Strings concatenation", - sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); - - x = sdscpy(x,"a"); - test_cond("sdscpy() against an originally longer string", - sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) - - x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); - test_cond("sdscpy() against an originally shorter string", - sdslen(x) == 33 && - memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) - - sdsfree(x); - x = sdscatprintf(sdsempty(),"%d",123); - test_cond("sdscatprintf() seems working in the base case", - sdslen(x) == 3 && memcmp(x,"123\0",4) == 0) - - sdsfree(x); - x = sdsnew("--"); - x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX); - test_cond("sdscatfmt() seems working in the base case", - sdslen(x) == 60 && - memcmp(x,"--Hello Hi! World -9223372036854775808," - "9223372036854775807--",60) == 0) - printf("[%s]\n",x); - - sdsfree(x); - x = sdsnew("--"); - x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX); - test_cond("sdscatfmt() seems working with unsigned numbers", - sdslen(x) == 35 && - memcmp(x,"--4294967295,18446744073709551615--",35) == 0) - - sdsfree(x); - x = sdsnew(" x "); - sdstrim(x," x"); - test_cond("sdstrim() works when all chars match", - sdslen(x) == 0) - - sdsfree(x); - x = sdsnew(" x "); - sdstrim(x," "); - test_cond("sdstrim() works when a single char remains", - sdslen(x) == 1 && x[0] == 'x') - - sdsfree(x); - x = sdsnew("xxciaoyyy"); - sdstrim(x,"xy"); - test_cond("sdstrim() correctly trims characters", - sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) - - y = sdsdup(x); - sdsrange(y,1,1); - test_cond("sdsrange(...,1,1)", - sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) - - sdsfree(y); - y = sdsdup(x); - sdsrange(y,1,-1); - test_cond("sdsrange(...,1,-1)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) - - sdsfree(y); - y = sdsdup(x); - sdsrange(y,-2,-1); - test_cond("sdsrange(...,-2,-1)", - sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) - - sdsfree(y); - y = sdsdup(x); - sdsrange(y,2,1); - test_cond("sdsrange(...,2,1)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) - - sdsfree(y); - y = sdsdup(x); - sdsrange(y,1,100); - test_cond("sdsrange(...,1,100)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) - - sdsfree(y); - y = sdsdup(x); - sdsrange(y,100,100); - test_cond("sdsrange(...,100,100)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("foo"); - y = sdsnew("foa"); - test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("bar"); - y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("aar"); - y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) - - sdsfree(y); - sdsfree(x); - x = sdsnewlen("\a\n\0foo\r",7); - y = sdscatrepr(sdsempty(),x,sdslen(x)); - test_cond("sdscatrepr(...data...)", - memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0) - - { - unsigned int oldfree; - char *p; - int step = 10, j, i; - - sdsfree(x); - sdsfree(y); - x = sdsnew("0"); - test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0); - - /* Run the test a few times in order to hit the first two - * SDS header types. */ - for (i = 0; i < 10; i++) { - int oldlen = sdslen(x); - x = sdsMakeRoomFor(x,step); - int type = x[-1]&SDS_TYPE_MASK; - - test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen); - if (type != SDS_TYPE_5) { - test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step); - oldfree = sdsavail(x); - } - p = x+oldlen; - for (j = 0; j < step; j++) { - p[j] = 'A'+j; - } - sdsIncrLen(x,step); - } - test_cond("sdsMakeRoomFor() content", - memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0); - test_cond("sdsMakeRoomFor() final length",sdslen(x)==101); - - sdsfree(x); - } - } - test_report() - return 0; -} -#endif - -#ifdef SDS_TEST_MAIN -int main(void) { - return sdsTest(); -} -#endif diff --git a/sds.h b/sds.h deleted file mode 100644 index 394f8b5..0000000 --- a/sds.h +++ /dev/null @@ -1,273 +0,0 @@ -/* SDSLib 2.0 -- A C dynamic strings library - * - * Copyright (c) 2006-2015, Salvatore Sanfilippo - * Copyright (c) 2015, Oran Agra - * Copyright (c) 2015, Redis Labs, Inc - * 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 Redis 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 OWNER 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 __SDS_H -#define __SDS_H - -#define SDS_MAX_PREALLOC (1024*1024) - -#include -#include -#include - -typedef char *sds; - -/* Note: sdshdr5 is never used, we just access the flags byte directly. - * However is here to document the layout of type 5 SDS strings. */ -struct __attribute__ ((__packed__)) sdshdr5 { - unsigned char flags; /* 3 lsb of type, and 5 msb of string length */ - char buf[]; -}; -struct __attribute__ ((__packed__)) sdshdr8 { - uint8_t len; /* used */ - uint8_t alloc; /* excluding the header and null terminator */ - unsigned char flags; /* 3 lsb of type, 5 unused bits */ - char buf[]; -}; -struct __attribute__ ((__packed__)) sdshdr16 { - uint16_t len; /* used */ - uint16_t alloc; /* excluding the header and null terminator */ - unsigned char flags; /* 3 lsb of type, 5 unused bits */ - char buf[]; -}; -struct __attribute__ ((__packed__)) sdshdr32 { - uint32_t len; /* used */ - uint32_t alloc; /* excluding the header and null terminator */ - unsigned char flags; /* 3 lsb of type, 5 unused bits */ - char buf[]; -}; -struct __attribute__ ((__packed__)) sdshdr64 { - uint64_t len; /* used */ - uint64_t alloc; /* excluding the header and null terminator */ - unsigned char flags; /* 3 lsb of type, 5 unused bits */ - char buf[]; -}; - -#define SDS_TYPE_5 0 -#define SDS_TYPE_8 1 -#define SDS_TYPE_16 2 -#define SDS_TYPE_32 3 -#define SDS_TYPE_64 4 -#define SDS_TYPE_MASK 7 -#define SDS_TYPE_BITS 3 -#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T))); -#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T)))) -#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS) - -static inline size_t sdslen(const sds s) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return SDS_TYPE_5_LEN(flags); - case SDS_TYPE_8: - return SDS_HDR(8,s)->len; - case SDS_TYPE_16: - return SDS_HDR(16,s)->len; - case SDS_TYPE_32: - return SDS_HDR(32,s)->len; - case SDS_TYPE_64: - return SDS_HDR(64,s)->len; - } - return 0; -} - -static inline size_t sdsavail(const sds s) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: { - return 0; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - return sh->alloc - sh->len; - } - } - return 0; -} - -static inline void sdssetlen(sds s, size_t newlen) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - { - unsigned char *fp = ((unsigned char*)s)-1; - *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); - } - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->len = newlen; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->len = newlen; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->len = newlen; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->len = newlen; - break; - } -} - -static inline void sdsinclen(sds s, size_t inc) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - { - unsigned char *fp = ((unsigned char*)s)-1; - unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc; - *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); - } - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->len += inc; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->len += inc; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->len += inc; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->len += inc; - break; - } -} - -/* sdsalloc() = sdsavail() + sdslen() */ -static inline size_t sdsalloc(const sds s) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return SDS_TYPE_5_LEN(flags); - case SDS_TYPE_8: - return SDS_HDR(8,s)->alloc; - case SDS_TYPE_16: - return SDS_HDR(16,s)->alloc; - case SDS_TYPE_32: - return SDS_HDR(32,s)->alloc; - case SDS_TYPE_64: - return SDS_HDR(64,s)->alloc; - } - return 0; -} - -static inline void sdssetalloc(sds s, size_t newlen) { - unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - /* Nothing to do, this type has no total allocation info. */ - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->alloc = newlen; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->alloc = newlen; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->alloc = newlen; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->alloc = newlen; - break; - } -} - -sds sdsnewlen(const void *init, size_t initlen); -sds sdsnew(const char *init); -sds sdsempty(void); -sds sdsdup(const sds s); -void sdsfree(sds s); -sds sdsgrowzero(sds s, size_t len); -sds sdscatlen(sds s, const void *t, size_t len); -sds sdscat(sds s, const char *t); -sds sdscatsds(sds s, const sds t); -sds sdscpylen(sds s, const char *t, size_t len); -sds sdscpy(sds s, const char *t); - -sds sdscatvprintf(sds s, const char *fmt, va_list ap); -#ifdef __GNUC__ -sds sdscatprintf(sds s, const char *fmt, ...) - __attribute__((format(printf, 2, 3))); -#else -sds sdscatprintf(sds s, const char *fmt, ...); -#endif - -sds sdscatfmt(sds s, char const *fmt, ...); -sds sdstrim(sds s, const char *cset); -void sdsrange(sds s, int start, int end); -void sdsupdatelen(sds s); -void sdsclear(sds s); -int sdscmp(const sds s1, const sds s2); -sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count); -void sdsfreesplitres(sds *tokens, int count); -void sdstolower(sds s); -void sdstoupper(sds s); -sds sdsfromlonglong(long long value); -sds sdscatrepr(sds s, const char *p, size_t len); -sds *sdssplitargs(const char *line, int *argc); -sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen); -sds sdsjoin(char **argv, int argc, char *sep); -sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen); - -/* Low level functions exposed to the user API */ -sds sdsMakeRoomFor(sds s, size_t addlen); -void sdsIncrLen(sds s, int incr); -sds sdsRemoveFreeSpace(sds s); -size_t sdsAllocSize(sds s); -void *sdsAllocPtr(sds s); - -/* Export the allocator used by SDS to the program using SDS. - * Sometimes the program SDS is linked to, may use a different set of - * allocators, but may want to allocate or free things that SDS will - * respectively free or allocate. */ -void *sds_malloc(size_t size); -void *sds_realloc(void *ptr, size_t size); -void sds_free(void *ptr); - -#ifdef REDIS_TEST -int sdsTest(int argc, char *argv[]); -#endif - -#endif diff --git a/sdsalloc.h b/sdsalloc.h deleted file mode 100644 index f43023c..0000000 --- a/sdsalloc.h +++ /dev/null @@ -1,42 +0,0 @@ -/* SDSLib 2.0 -- A C dynamic strings library - * - * Copyright (c) 2006-2015, Salvatore Sanfilippo - * Copyright (c) 2015, Oran Agra - * Copyright (c) 2015, Redis Labs, Inc - * 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 Redis 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 OWNER 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. - */ - -/* SDS allocator selection. - * - * This file is used in order to change the SDS allocator at compile time. - * Just define the following defines to what you want to use. Also add - * the include of your alternate allocator if needed (not needed in order - * to use the default libc allocator). */ - -#define s_malloc malloc -#define s_realloc realloc -#define s_free free diff --git a/sha1.c b/sha1.c deleted file mode 100644 index c2bf174..0000000 --- a/sha1.c +++ /dev/null @@ -1,296 +0,0 @@ -/* -SHA-1 in C -By Steve Reid -100% Public Domain - -Test Vectors (from FIPS PUB 180-1) -"abc" - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D -"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 -A million repetitions of "a" - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F -*/ - -/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ -/* #define SHA1HANDSOFF * Copies data before messing with it. */ - -#define SHA1HANDSOFF - -#include -#include - -/* for uint32_t */ -#include - -#include "sha1.h" - - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* blk0() and blk() perform the initial expand. */ -/* I got the idea of expanding during the round function from SSLeay */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#elif BYTE_ORDER == BIG_ENDIAN -#define blk0(i) block->l[i] -#else -#error "Endianness not defined!" -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - - -/* Hash a single 512-bit block. This is the core of the algorithm. */ - -void SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] -) -{ - uint32_t a, b, c, d, e; - - typedef union - { - unsigned char c[64]; - uint32_t l[16]; - } CHAR64LONG16; - -#ifdef SHA1HANDSOFF - CHAR64LONG16 block[1]; /* use array to appear as a pointer */ - - memcpy(block, buffer, 64); -#else - /* The following had better never be used because it causes the - * pointer-to-const buffer to be cast into a pointer to non-const. - * And the result is written through. I threw a "const" in, hoping - * this will cause a diagnostic. - */ - CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; -#endif - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a, b, c, d, e, 0); - R0(e, a, b, c, d, 1); - R0(d, e, a, b, c, 2); - R0(c, d, e, a, b, 3); - R0(b, c, d, e, a, 4); - R0(a, b, c, d, e, 5); - R0(e, a, b, c, d, 6); - R0(d, e, a, b, c, 7); - R0(c, d, e, a, b, 8); - R0(b, c, d, e, a, 9); - R0(a, b, c, d, e, 10); - R0(e, a, b, c, d, 11); - R0(d, e, a, b, c, 12); - R0(c, d, e, a, b, 13); - R0(b, c, d, e, a, 14); - R0(a, b, c, d, e, 15); - R1(e, a, b, c, d, 16); - R1(d, e, a, b, c, 17); - R1(c, d, e, a, b, 18); - R1(b, c, d, e, a, 19); - R2(a, b, c, d, e, 20); - R2(e, a, b, c, d, 21); - R2(d, e, a, b, c, 22); - R2(c, d, e, a, b, 23); - R2(b, c, d, e, a, 24); - R2(a, b, c, d, e, 25); - R2(e, a, b, c, d, 26); - R2(d, e, a, b, c, 27); - R2(c, d, e, a, b, 28); - R2(b, c, d, e, a, 29); - R2(a, b, c, d, e, 30); - R2(e, a, b, c, d, 31); - R2(d, e, a, b, c, 32); - R2(c, d, e, a, b, 33); - R2(b, c, d, e, a, 34); - R2(a, b, c, d, e, 35); - R2(e, a, b, c, d, 36); - R2(d, e, a, b, c, 37); - R2(c, d, e, a, b, 38); - R2(b, c, d, e, a, 39); - R3(a, b, c, d, e, 40); - R3(e, a, b, c, d, 41); - R3(d, e, a, b, c, 42); - R3(c, d, e, a, b, 43); - R3(b, c, d, e, a, 44); - R3(a, b, c, d, e, 45); - R3(e, a, b, c, d, 46); - R3(d, e, a, b, c, 47); - R3(c, d, e, a, b, 48); - R3(b, c, d, e, a, 49); - R3(a, b, c, d, e, 50); - R3(e, a, b, c, d, 51); - R3(d, e, a, b, c, 52); - R3(c, d, e, a, b, 53); - R3(b, c, d, e, a, 54); - R3(a, b, c, d, e, 55); - R3(e, a, b, c, d, 56); - R3(d, e, a, b, c, 57); - R3(c, d, e, a, b, 58); - R3(b, c, d, e, a, 59); - R4(a, b, c, d, e, 60); - R4(e, a, b, c, d, 61); - R4(d, e, a, b, c, 62); - R4(c, d, e, a, b, 63); - R4(b, c, d, e, a, 64); - R4(a, b, c, d, e, 65); - R4(e, a, b, c, d, 66); - R4(d, e, a, b, c, 67); - R4(c, d, e, a, b, 68); - R4(b, c, d, e, a, 69); - R4(a, b, c, d, e, 70); - R4(e, a, b, c, d, 71); - R4(d, e, a, b, c, 72); - R4(c, d, e, a, b, 73); - R4(b, c, d, e, a, 74); - R4(a, b, c, d, e, 75); - R4(e, a, b, c, d, 76); - R4(d, e, a, b, c, 77); - R4(c, d, e, a, b, 78); - R4(b, c, d, e, a, 79); - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Wipe variables */ - a = b = c = d = e = 0; -#ifdef SHA1HANDSOFF - memset(block, '\0', sizeof(block)); -#endif -} - - -/* SHA1Init - Initialize new context */ - -void SHA1Init( - SHA1_CTX * context -) -{ - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* Run your data through this. */ - -void SHA1Update( - SHA1_CTX * context, - const unsigned char *data, - uint32_t len -) -{ - uint32_t i; - - uint32_t j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1]++; - context->count[1] += (len >> 29); - j = (j >> 3) & 63; - if ((j + len) > 63) - { - memcpy(&context->buffer[j], data, (i = 64 - j)); - SHA1Transform(context->state, context->buffer); - for (; i + 63 < len; i += 64) - { - SHA1Transform(context->state, &data[i]); - } - j = 0; - } - else - i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* Add padding and return the message digest. */ - -void SHA1Final( - unsigned char digest[20], - SHA1_CTX * context -) -{ - unsigned i; - - unsigned char finalcount[8]; - - unsigned char c; - -#if 0 /* untested "improvement" by DHR */ - /* Convert context->count to a sequence of bytes - * in finalcount. Second element first, but - * big-endian order within element. - * But we do it all backwards. - */ - unsigned char *fcp = &finalcount[8]; - - for (i = 0; i < 2; i++) - { - uint32_t t = context->count[i]; - - int j; - - for (j = 0; j < 4; t >>= 8, j++) - *--fcp = (unsigned char) t} -#else - for (i = 0; i < 8; i++) - { - finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ - } -#endif - c = 0200; - SHA1Update(context, &c, 1); - while ((context->count[0] & 504) != 448) - { - c = 0000; - SHA1Update(context, &c, 1); - } - SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++) - { - digest[i] = (unsigned char) - ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); - } - /* Wipe variables */ - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} - -void SHA1( - char *hash_out, - const char *str, - int len) -{ - SHA1_CTX ctx; - unsigned int ii; - - SHA1Init(&ctx); - for (ii=0; ii - 100% Public Domain - */ - -#include "stdint.h" - -typedef struct -{ - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; -} SHA1_CTX; - -void SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] - ); - -void SHA1Init( - SHA1_CTX * context - ); - -void SHA1Update( - SHA1_CTX * context, - const unsigned char *data, - uint32_t len - ); - -void SHA1Final( - unsigned char digest[20], - SHA1_CTX * context - ); - -void SHA1( - char *hash_out, - const char *str, - int len); - -#endif /* SHA1_H */ -- cgit v1.2.3