C Snippets

/* Some handy functions Public domain by Ron Spain in 2019 http://ronspain.crabdance.com die - reports any error message and kills the program mal - allocates memory safely, dies with message on failure mal2 - mal with extra argument for size multiplier fop - safe form of fopen, opens file or dies with error msg same args as fopen, returns a FILE pointer rtrim - trims white space from the right side of a string (no return value) hash - returns a 32-bit hash of a string, fast but simple, not for security capPercent - returns the percentage of capital letters out of all letters in a string as an integer 0-100 slower - lower the case of a whole string (no return value) smix - raises the case of the first letter of each word, lowers the case of every other letter (no return value) eos - returns a pointer to the end of the string */ typedef uint8_t U1; typedef uint16_t U2; typedef uint32_t U4; typedef int8_t I1; typedef int16_t I2; typedef int32_t I4; typedef U1 bool; void die(char*s){ fputs("\n\n\t\t-= FATAL ERROR =-\n",stderr); if(s)perror(s); fputs("\n",stderr); exit(1); abort();/* Should never be reached */ } void*mal(unsigned n){ char*p; p=malloc(n); if(!p)die("malloc"); return p; } void*mal2(unsigned a,unsigned b){ return mal(a*b); } FILE*fop(char*a,char*b){ FILE*f; f=fopen(a,b); if(!f)die(a); return f; } void rtrim(char*s){ unsigned n; if(!s)return;/* remove for speed */ n=strlen(s); while(n&&isspace(s[--n]))s[n]='\0'; } U4 hash(char*s){ U4 n=0; while(*s){ n=n*31+*s; ++s; } return n; } unsigned capPercent(char*s){ U4 c=0,n=0; while(*s){ if(isalpha(*s)){ if(isupper(*s))++c; ++n; } ++s; } if(n)n=c*100/n; return n; } void slower(char*s){ while(*s){ *s=tolower(*s); ++s; } } void smix(char*s){ bool b=1; while(*s){ if(!isalpha(*s))b=1; else if(!b)*s=tolower(*s); else{ *s=toupper(*s); b=0; } ++s; } } char*eos(char*s){ unsigned n; if(!s)return 0; n=strlen(s); return s+n; } /* EOF */