3 * Copyright (C) 2007-2020 William Morrow
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published
7 * by the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public
16 * License along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 static inline char *cstrcat(int n, ...) {
30 int len = 0; va_list va; va_start(va,n);
31 for(int i=0; i<n; ++i) len += strlen(va_arg(va,char*));
32 va_end(va); char *cp = new char[len+1], *bp = cp; va_start(va,n);
33 for(int i=0; i<n; ++i) for(char*ap=va_arg(va,char*); *ap; *bp++=*ap++);
37 static inline char *cstrdup(const char *cp) {
38 return strcpy(new char[strlen(cp)+1],cp);
42 #define lengthof(ary) ((int)(sizeof(ary)/sizeof(ary[0])))
45 static inline int butf8(const char *&cp)
47 const unsigned char *bp = (const unsigned char *)cp;
51 static const int64_t sz = 0x5433222211111111;
52 int n = v < 0 ? 0 : (sz >> (v&0x3c)) & 0x0f;
53 for( int i=n; --i>=0; ret+=*bp++ ) ret <<= 6;
54 static const uint32_t ofs[6] = {
55 0x00000000U, 0x00003080U, 0x000E2080U,
56 0x03C82080U, 0xFA082080U, 0x82082080U
60 cp = (const char *)bp;
63 static inline int butf8(unsigned int v, char *&cp)
65 unsigned char *bp = (unsigned char *)cp;
66 if( v >= 0x00000080 ) {
67 int i = v < 0x00000800 ? 2 : v < 0x00010000 ? 3 :
68 v < 0x00200000 ? 4 : v < 0x04000000 ? 5 : 6;
70 *bp++ = (v>>(6*--i)) | m;
71 while( --i >= 0 ) *bp++ = ((v>>(6*i)) & 0x3f) | 0x80;
75 int ret = bp - (unsigned char *)cp;
80 static inline int bstrcasecmp(const char *ap, const char *bp)
81 { // not really correct, but what was left after MS port
84 if( (a=butf8(ap)) >= 'A' && a <= 'Z' ) a += 'a' - 'A';
85 if( (b=butf8(bp)) >= 'A' && b <= 'Z' ) b += 'a' - 'A';
86 } while( !(ret=a-b) && a && b );
90 static inline const char *bstrcasestr(const char *src, const char *tgt)
92 int ssz = strlen(src), tsz = strlen(tgt);
94 uint32_t wtgt[tsz+1], *tp = wtgt;
97 if( wch >= 'A' && wch <= 'Z' ) wch += 'a' - 'A';
101 for( tsz=tp-wtgt; ssz>=tsz; ++src,--ssz ) {
103 int ret = 0, wch = 0;
104 for( int i=tsz; --i>=0 && !ret && (wch=butf8(cp)); ) {
105 if( wch >= 'A' && wch <= 'Z' ) wch += 'a' - 'A';
108 if( !ret ) return src;