forked from sigatrev/Stepmania-3.95
/
RageUtil.cpp
1572 lines (1301 loc) · 34.4 KB
/
RageUtil.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "global.h"
#include "RageUtil.h"
#include "RageMath.h"
#include "RageLog.h"
#include "RageFile.h"
#include <numeric>
#include <ctime>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
int randseed = time(NULL);
// From "Numerical Recipes in C".
float RandomFloat( int &seed )
{
const int MASK = 123459876;
seed ^= MASK;
const int IA = 16807;
const int IM = 2147483647;
const int IQ = 127773;
const int IR = 2836;
long k = seed / IQ;
seed = IA*(seed-k*IQ)-IR*k;
if( seed < 0 )
seed += IM;
const float AM = .999999f / IM;
float ans = AM * seed;
seed ^= MASK;
return ans;
}
RandomGen::RandomGen( unsigned long seed_ )
{
seed = seed_;
if(seed == 0)
seed = time(NULL);
}
int RandomGen::operator() ( int maximum )
{
return int(RandomFloat( seed ) * maximum);
}
void fapproach( float& val, float other_val, float to_move )
{
ASSERT_M( to_move >= 0, ssprintf("to_move: %f", to_move) );
if( val == other_val )
return;
float fDelta = other_val - val;
float fSign = fDelta / fabsf( fDelta );
float fToMove = fSign*to_move;
if( fabsf(fToMove) > fabsf(fDelta) )
fToMove = fDelta; // snap
val += fToMove;
}
/* Return a positive x mod y. */
float fmodfp(float x, float y)
{
x = fmodf(x, y); /* x is [-y,y] */
x += y; /* x is [0,y*2] */
x = fmodf(x, y); /* x is [0,y] */
return x;
}
int power_of_two(int input)
{
int value = 1;
while ( value < input ) value <<= 1;
return value;
}
bool IsAnInt( const CString &s )
{
if( !s.size() )
return false;
for( int i=0; s[i]; i++ )
if( s[i] < '0' || s[i] > '9' )
return false;
return true;
}
bool IsHexVal( const CString &s )
{
if( !s.size() )
return false;
for( int i=0; s[i]; i++ )
if( !(s[i] >= '0' && s[i] <= '9') &&
!(toupper(s[i]) >= 'A' && toupper(s[i]) <= 'F'))
return false;
return true;
}
float HHMMSSToSeconds( const CString &sHHMMSS )
{
CStringArray arrayBits;
split( sHHMMSS, ":", arrayBits, false );
while( arrayBits.size() < 3 )
arrayBits.insert(arrayBits.begin(), "0" ); // pad missing bits
float fSeconds = 0;
fSeconds += atoi( arrayBits[0] ) * 60 * 60;
fSeconds += atoi( arrayBits[1] ) * 60;
fSeconds += strtof( arrayBits[2], NULL );
return fSeconds;
}
CString SecondsToHHMMSS( float fSecs )
{
const int iMinsDisplay = (int)fSecs/60;
const int iSecsDisplay = (int)fSecs - iMinsDisplay*60;
CString sReturn = ssprintf( "%02d:%02d:%02d", iMinsDisplay/60, iMinsDisplay%60, iSecsDisplay );
return sReturn;
}
CString SecondsToMMSSMsMs( float fSecs )
{
const int iMinsDisplay = (int)fSecs/60;
const int iSecsDisplay = (int)fSecs - iMinsDisplay*60;
const int iLeftoverDisplay = (int) ( (fSecs - iMinsDisplay*60 - iSecsDisplay) * 100 );
CString sReturn = ssprintf( "%02d:%02d.%02d", iMinsDisplay, iSecsDisplay, min(99,iLeftoverDisplay) );
return sReturn;
}
CString SecondsToMSSMsMs( float fSecs )
{
const int iMinsDisplay = (int)fSecs/60;
const int iSecsDisplay = (int)fSecs - iMinsDisplay*60;
const int iLeftoverDisplay = (int) ( (fSecs - iMinsDisplay*60 - iSecsDisplay) * 100 );
CString sReturn = ssprintf( "%01d:%02d.%02d", iMinsDisplay, iSecsDisplay, min(99,iLeftoverDisplay) );
return sReturn;
}
#include "LuaFunctions.h"
#include "LuaManager.h"
LuaFunction( SecondsToMSSMsMs, SecondsToMSSMsMs( FArg(1) ) )
CString SecondsToMMSSMsMsMs( float fSecs )
{
const int iMinsDisplay = (int)fSecs/60;
const int iSecsDisplay = (int)fSecs - iMinsDisplay*60;
const int iLeftoverDisplay = (int) ( (fSecs - iMinsDisplay*60 - iSecsDisplay) * 1000 );
CString sReturn = ssprintf( "%02d:%02d.%03d", iMinsDisplay, iSecsDisplay, min(999,iLeftoverDisplay) );
return sReturn;
}
CString PrettyPercent( float fNumerator, float fDenominator)
{
return ssprintf("%0.2f%%",fNumerator/fDenominator*100);
}
CString Commify( int iNum )
{
CString sNum = ssprintf("%d",iNum);
CString sReturn;
for( unsigned i=0; i<sNum.length(); i++ )
{
char cDigit = sNum[sNum.length()-1-i];
if( i!=0 && i%3 == 0 )
sReturn = ',' + sReturn;
sReturn = cDigit + sReturn;
}
return sReturn;
}
CString FormatNumberAndSuffix( int i )
{
CString sSuffix;
switch( i%10 )
{
case 1: sSuffix = "st"; break;
case 2: sSuffix = "nd"; break;
case 3: sSuffix = "rd"; break;
default: sSuffix = "th"; break;
}
// "11th", "113th", etc.
if( ((i%100) / 10) == 1 )
sSuffix = "th";
return ssprintf("%i", i) + sSuffix;
}
struct tm GetLocalTime()
{
const time_t t = time(NULL);
struct tm tm;
localtime_r( &t, &tm );
return tm;
}
CString ssprintf( const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
return vssprintf(fmt, va);
}
CString vssprintf( const char *fmt, va_list argList)
{
CString str;
str.FormatV(fmt, argList);
return str;
}
#ifdef WIN32
#ifdef _XBOX
# include <D3DX8Core.h>
#else
# include <windows.h>
# include <dxerr8.h>
# if defined(_MSC_VER) && !defined(_XBOX)
# pragma comment(lib, "dxerr8.lib")
# endif
#endif
CString hr_ssprintf( int hr, const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
CString s = vssprintf( fmt, va );
va_end(va);
#ifdef _XBOX
char szError[1024] = "";
D3DXGetErrorString( hr, szError, sizeof(szError) );
#else
const char *szError = DXGetErrorString8( hr );
#endif
return s + ssprintf( " (%s)", szError );
}
CString werr_ssprintf( int err, const char *fmt, ...)
{
char buf[1024] = "";
#ifndef _XBOX
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
0, err, 0, buf, sizeof(buf), NULL);
#endif
/* Why is FormatMessage returning text ending with \r\n? */
CString text = buf;
text.Replace( "\n", "" );
text.Replace( "\r", " " ); /* foo\r\nbar -> foo bar */
TrimRight( text ); /* "foo\r\n" -> "foo" */
va_list va;
va_start(va, fmt);
CString s = vssprintf( fmt, va );
va_end(va);
return s += ssprintf( " (%s)", text.c_str() );
}
CString ConvertWstringToACP( wstring s )
{
if( s.empty() )
return "";
int iBytes = WideCharToMultiByte( CP_ACP, 0, s.data(), s.size(),
NULL, 0, NULL, FALSE );
ASSERT_M( iBytes > 0, werr_ssprintf( GetLastError(), "WideCharToMultiByte" ).c_str() );
CString ret;
WideCharToMultiByte( CP_ACP, 0, s.data(), s.size(),
ret.GetBuf( iBytes ), iBytes, NULL, FALSE );
ret.RelBuf( iBytes );
return ret;
}
CString ConvertUTF8ToACP( CString s )
{
return ConvertWstringToACP( CStringToWstring(s) );
}
#endif
CString join( const CString &Deliminator, const CStringArray& Source)
{
if( Source.empty() )
return "";
CString csTmp;
// Loop through the Array and Append the Deliminator
for( unsigned iNum = 0; iNum < Source.size()-1; iNum++ ) {
csTmp += Source[iNum];
csTmp += Deliminator;
}
csTmp += Source.back();
return csTmp;
}
CString join( const CString &Delimitor, CStringArray::const_iterator begin, CStringArray::const_iterator end )
{
if( begin == end )
return "";
CString ret;
while( begin != end )
{
ret += *begin;
++begin;
if( begin != end )
ret += Delimitor;
}
return ret;
}
template <class S>
static int DelimitorLength( const S &Delimitor )
{
return Delimitor.size();
}
static int DelimitorLength( char Delimitor )
{
return 1;
}
static int DelimitorLength( wchar_t Delimitor )
{
return 1;
}
template <class S, class C>
void do_split( const S &Source, const C Delimitor, vector<S> &AddIt, const bool bIgnoreEmpty )
{
/* Short-circuit if the source is empty; we want to return an empty vector if
* the string is empty, even if bIgnoreEmpty is true. */
if( Source.empty() )
return;
size_t startpos = 0;
do {
size_t pos;
pos = Source.find( Delimitor, startpos );
if( pos == Source.npos )
pos = Source.size();
if( pos-startpos > 0 || !bIgnoreEmpty )
{
/* Optimization: if we're copying the whole string, avoid substr; this
* allows this copy to be refcounted, which is much faster. */
if( startpos == 0 && pos-startpos == Source.size() )
AddIt.push_back(Source);
else
{
const S AddCString = Source.substr(startpos, pos-startpos);
AddIt.push_back(AddCString);
}
}
startpos = pos+DelimitorLength(Delimitor);
} while ( startpos <= Source.size() );
}
void split( const CString &Source, const CString &Delimitor, CStringArray &AddIt, const bool bIgnoreEmpty )
{
if( Delimitor.size() == 1 )
do_split( Source, Delimitor[0], AddIt, bIgnoreEmpty );
else
do_split( Source, Delimitor, AddIt, bIgnoreEmpty );
}
void split( const wstring &Source, const wstring &Delimitor, vector<wstring> &AddIt, const bool bIgnoreEmpty )
{
if( Delimitor.size() == 1 )
do_split( Source, Delimitor[0], AddIt, bIgnoreEmpty );
else
do_split( Source, Delimitor, AddIt, bIgnoreEmpty );
}
/* Use:
CString str="a,b,c";
int start = 0, size = -1;
while( 1 )
{
do_split( str, ",", begin, size );
if( begin == str.end() )
break;
str[begin] = 'Q';
}
*/
template <class S>
void do_split( const S &Source, const S &Delimitor, int &begin, int &size, int len, const bool bIgnoreEmpty )
{
if( size != -1 )
{
/* Start points to the beginning of the last delimiter. Move it up. */
begin += size+Delimitor.size();
begin = min( begin, len );
}
size = 0;
if( bIgnoreEmpty )
{
/* Skip delims. */
while( begin + Delimitor.size() < Source.size() &&
!Source.compare( begin, Delimitor.size(), Delimitor ) )
++begin;
}
/* Where's the string function to find within a substring? C++ strings apparently
* are missing that ... */
size_t pos;
if( Delimitor.size() == 1 )
pos = Source.find( Delimitor[0], begin );
else
pos = Source.find( Delimitor, begin );
if( pos == Source.npos || (int) pos > len )
pos = len;
size = pos - begin;
}
void split( const CString &Source, const CString &Delimitor, int &begin, int &size, int len, const bool bIgnoreEmpty )
{
do_split( Source, Delimitor, begin, size, len, bIgnoreEmpty );
}
void split( const wstring &Source, const wstring &Delimitor, int &begin, int &size, int len, const bool bIgnoreEmpty )
{
do_split( Source, Delimitor, begin, size, len, bIgnoreEmpty );
}
void split( const CString &Source, const CString &Delimitor, int &begin, int &size, const bool bIgnoreEmpty )
{
do_split( Source, Delimitor, begin, size, Source.size(), bIgnoreEmpty );
}
void split( const wstring &Source, const wstring &Delimitor, int &begin, int &size, const bool bIgnoreEmpty )
{
do_split( Source, Delimitor, begin, size, Source.size(), bIgnoreEmpty );
}
/*
* foo\fum\ -> "foo\fum\", "", ""
* c:\foo\bar.txt -> "c:\foo\", "bar", ".txt"
* \\foo\fum -> "\\foo\", "fum", ""
*/
void splitpath( const CString &Path, CString& Dir, CString& Filename, CString& Ext )
{
Dir = Filename = Ext = "";
CStringArray mat;
/* One level of escapes for the regex, one for C. Ew.
* This is really:
* ^(.*[\\/])?(.*)$ */
static Regex sep("^(.*[\\\\/])?(.*)$");
bool check = sep.Compare(Path, mat);
ASSERT(check);
Dir = mat[0];
const CString Base = mat[1];
/* ^(.*)(\.[^\.]+)$ */
static Regex SplitExt("^(.*)(\\.[^\\.]+)$");
if( SplitExt.Compare(Base, mat) )
{
Filename = mat[0];
Ext = mat[1];
} else
Filename = Base;
}
/* "foo.bar", "baz" -> "foo.baz"
* "foo", "baz" -> "foo.baz"
* "foo.bar", "" -> "foo" */
CString SetExtension( const CString &path, const CString &ext )
{
CString Dir, FName, OldExt;
splitpath( path, Dir, FName, OldExt );
return Dir + FName + (ext.size()? ".":"") + ext;
}
CString GetExtension( const CString &sPath )
{
size_t pos = sPath.rfind( '.' );
if( pos == sPath.npos )
return "";
size_t slash = sPath.find( '/', pos );
if( slash != sPath.npos )
return ""; /* rare: path/dir.ext/fn */
return sPath.substr( pos+1, sPath.size()-pos+1 );
}
CString GetFileNameWithoutExtension( const CString &sPath )
{
CString sThrowAway, sFName;
splitpath( sPath, sThrowAway, sFName, sThrowAway );
return sFName;
}
CString GetCwd()
{
#ifdef _XBOX
return SYS_BASE_PATH;
#else
char buf[PATH_MAX];
bool ret = getcwd(buf, PATH_MAX) != NULL;
ASSERT(ret);
return buf;
#endif
}
/*
* Calculate a standard CRC32. iCRC should be initialized to 0.
* References:
* http://www.theorem.com/java/CRC32.java,
* http://www.faqs.org/rfcs/rfc1952.html
*/
void CRC32( unsigned int &iCRC, const void *pVoidBuffer, size_t iSize )
{
static unsigned tab[256];
static bool initted = false;
if( !initted )
{
initted = true;
const unsigned POLY = 0xEDB88320;
for( int i = 0; i < 256; ++i )
{
tab[i] = i;
for( int j = 0; j < 8; ++j )
{
if( tab[i] & 1 )
tab[i] = (tab[i] >> 1) ^ POLY;
else
tab[i] >>= 1;
}
}
}
iCRC ^= 0xFFFFFFFF;
const char *pBuffer = (const char *) pVoidBuffer;
for( unsigned i = 0; i < iSize; ++i )
iCRC = (iCRC >> 8) ^ tab[(iCRC ^ pBuffer[i]) & 0xFF];
iCRC ^= 0xFFFFFFFF;
}
unsigned int GetHashForString ( const CString &s )
{
unsigned crc = 0;
CRC32( crc, s.data(), s.size() );
return crc;
}
/* Return true if "dir" is empty or does not exist. */
bool DirectoryIsEmpty( const CString &dir )
{
if(dir == "")
return true;
if(!DoesFileExist(dir))
return true;
CStringArray asFileNames;
GetDirListing( dir, asFileNames );
return asFileNames.empty();
}
bool CompareCStringsAsc(const CString &str1, const CString &str2)
{
return str1.CompareNoCase( str2 ) < 0;
}
bool CompareCStringsDesc(const CString &str1, const CString &str2)
{
return str1.CompareNoCase( str2 ) > 0;
}
void SortCStringArray( CStringArray &arrayCStrings, const bool bSortAscending )
{
sort( arrayCStrings.begin(), arrayCStrings.end(),
bSortAscending?CompareCStringsAsc:CompareCStringsDesc);
}
float calc_mean(const float *start, const float *end)
{
return accumulate(start, end, 0.f) / distance(start, end);
}
float calc_stddev(const float *start, const float *end)
{
/* Calculate the mean. */
float mean = calc_mean(start, end);
/* Calculate stddev. */
float dev = 0.0f;
for( const float *i=start; i != end; ++i )
dev += (*i - mean) * (*i - mean);
dev /= distance(start, end) - 1;
dev = sqrtf(dev);
return dev;
}
void TrimLeft(CString &str, const char *s)
{
int n = 0;
while(n < int(str.size()) && strchr(s, str[n]))
n++;
str.erase(str.begin(), str.begin()+n);
}
void TrimRight(CString &str, const char *s)
{
int n = str.size();
while(n > 0 && strchr(s, str[n-1]))
n--;
/* Delete from n to the end. If n == str.size(), nothing is deleted;
* if n == 0, the whole string is erased. */
str.erase(str.begin()+n, str.end());
}
void StripCrnl(CString &s)
{
while( s.size() && (s[s.size()-1] == '\r' || s[s.size()-1] == '\n') )
s.erase(s.size()-1);
}
/* path is a .redir pathname. Read it and return the real one. */
CString DerefRedir(const CString &_path)
{
CString path = _path;
for( int i=0; i<100; i++ )
{
if( GetExtension(path) != "redir" )
{
return path;
}
CString sNewFileName;
GetFileContents( path, sNewFileName, true );
/* Empty is invalid. */
if( sNewFileName == "" )
return "";
FixSlashesInPlace( sNewFileName );
CString path2 = Dirname(path) + sNewFileName;
CollapsePath( path2 );
path2 += "*";
vector<CString> matches;
GetDirListing( path2, matches, false, true );
if( matches.empty() )
RageException::Throw( "The redirect '%s' references a file '%s' which doesn't exist.", path.c_str(), path2.c_str() );
else if( matches.size() > 1 )
RageException::Throw( "The redirect '%s' references a file '%s' with multiple matches.", path.c_str(), path2.c_str() );
path = matches[0];
}
RageException::Throw( "Circular redirect '%s'", path.c_str() );
}
bool GetFileContents( const CString &sPath, CString &sOut, bool bOneLine )
{
/* Don't warn if the file doesn't exist, but do warn if it exists and fails to open. */
if( !IsAFile(sPath) )
return false;
RageFile file;
if( !file.Open(sPath) )
{
LOG->Warn( "GetFileContents(%s): %s", sPath.c_str(), file.GetError().c_str() );
return false;
}
CString sData;
int iGot;
if( bOneLine )
iGot = file.GetLine( sData );
else
iGot = file.Read( sData, file.GetFileSize() );
if( iGot == -1 )
{
LOG->Warn( "GetFileContents(%s): %s", sPath.c_str(), file.GetError().c_str() );
return false;
}
if( bOneLine )
StripCrnl( sData );
sOut = sData;
return true;
}
#if 1
/* PCRE */
#include "pcre/pcre.h"
void Regex::Compile()
{
const char *error;
int offset;
reg = pcre_compile(pattern.c_str(), PCRE_CASELESS, &error, &offset, NULL);
if(reg == NULL)
RageException::Throw("Invalid regex: '%s' (%s)", pattern.c_str(), error);
int ret = pcre_fullinfo( (pcre *) reg, NULL, PCRE_INFO_CAPTURECOUNT, &backrefs);
ASSERT(ret >= 0);
backrefs++;
ASSERT(backrefs < 128);
}
void Regex::Set(const CString &str)
{
Release();
pattern=str;
Compile();
}
void Regex::Release()
{
pcre_free(reg);
reg = NULL;
pattern = "";
}
Regex::Regex(const CString &str)
{
reg = NULL;
Set(str);
}
Regex::Regex(const Regex &rhs)
{
reg = NULL;
Set(rhs.pattern);
}
Regex &Regex::operator=(const Regex &rhs)
{
if(this != &rhs) Set(rhs.pattern);
return *this;
}
Regex::~Regex()
{
Release();
}
bool Regex::Compare(const CString &str)
{
int mat[128*3];
int ret = pcre_exec( (pcre *) reg, NULL,
str.data(), str.size(), 0, 0, mat, 128*3);
if( ret < -1 )
RageException::Throw("Unexpected return from pcre_exec('%s'): %i",
pattern.c_str(), ret);
return ret >= 0;
}
bool Regex::Compare(const CString &str, vector<CString> &matches)
{
matches.clear();
int mat[128*3];
int ret = pcre_exec( (pcre *) reg, NULL,
str.data(), str.size(), 0, 0, mat, 128*3);
if( ret < -1 )
RageException::Throw("Unexpected return from pcre_exec('%s'): %i",
pattern.c_str(), ret);
if(ret == -1)
return false;
for(unsigned i = 1; i < backrefs; ++i)
{
const int start = mat[i*2], end = mat[i*2+1];
if(start == -1)
matches.push_back(""); /* no match */
else
matches.push_back(str.substr(start, end - start));
}
return true;
}
#else
/* GNU regex */
#include "regex.h"
void Regex::Compile()
{
reg = new regex_t;
int ret = regcomp((regex_t *) reg, pattern.c_str(), REG_EXTENDED|REG_ICASE);
if(ret != 0)
RageException::Throw("Invalid regex: '%s'", pattern.c_str());
/* Count the number of backreferences. */
backrefs = 0;
for(int i = 0; i < int(pattern.size()); ++i)
if(pattern[i] == '(') backrefs++;
ASSERT(backrefs+1 < 128);
}
void Regex::Set(const CString &str)
{
Release();
pattern=str;
Compile();
}
void Regex::Release()
{
delete (regex_t *)reg;
reg = NULL;
pattern = "";
}
Regex::Regex(const CString &str)
{
reg = NULL;
Set(str);
}
Regex::Regex(const Regex &rhs)
{
reg = NULL;
Set(rhs.pattern);
}
Regex &Regex::operator=(const Regex &rhs)
{
if(this != &rhs) Set(rhs.pattern);
return *this;
}
Regex::~Regex()
{
Release();
}
bool Regex::Compare(const CString &str)
{
return regexec((regex_t *) reg, str.c_str(), 0, NULL, 0) != REG_NOMATCH;
}
bool Regex::Compare(const CString &str, vector<CString> &matches)
{
matches.clear();
regmatch_t mat[128];
int ret = regexec((regex_t *) reg, str.c_str(), 128, mat, 0);
if(ret == REG_NOMATCH)
return false;
for(unsigned i = 1; i < backrefs+1; ++i)
{
if(mat[i].rm_so == -1)
matches.push_back(""); /* no match */
else
matches.push_back(str.substr(mat[i].rm_so, mat[i].rm_eo - mat[i].rm_so));
}
return true;
}
#endif
/* Given a UTF-8 byte, return the length of the codepoint (if a start code)
* or 0 if it's a continuation byte. */
int utf8_get_char_len( char p )
{
if( !(p & 0x80) ) return 1; /* 0xxxxxxx - 1 */
if( !(p & 0x40) ) return 1; /* 10xxxxxx - continuation */
if( !(p & 0x20) ) return 2; /* 110xxxxx */
if( !(p & 0x10) ) return 3; /* 1110xxxx */
if( !(p & 0x08) ) return 4; /* 11110xxx */
if( !(p & 0x04) ) return 5; /* 111110xx */
if( !(p & 0x02) ) return 6; /* 1111110x */
return 1; /* 1111111x */
}
static inline bool is_utf8_continuation_byte( char c )
{
return (c & 0xC0) == 0x80;
}
/* Decode one codepoint at start; advance start and place the result in ch. If
* the encoded string is invalid, false is returned. */
bool utf8_to_wchar_ec( const CString &s, unsigned &start, wchar_t &ch )
{
if( start >= s.size() )
return false;
if( is_utf8_continuation_byte( s[start] ) || /* misplaced continuation byte */
(s[start] & 0xFE) == 0xFE ) /* 0xFE, 0xFF */
{
start += 1;
return false;
}
int len = utf8_get_char_len( s[start] );
const int first_byte_mask[] = { -1, 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01 };
ch = wchar_t(s[start] & first_byte_mask[len]);
for( int i = 1; i < len; ++i )
{
if( start+i >= s.size() )
{
/* We expected a continuation byte, but didn't get one. Return error, and point
* start at the unexpected byte; it's probably a new sequence. */
start += i;
return false;
}
char byte = s[start+i];
if( !is_utf8_continuation_byte(byte) )
{
/* We expected a continuation byte, but didn't get one. Return error, and point
* start at the unexpected byte; it's probably a new sequence. */
start += i;
return false;
}
ch = (ch << 6) | byte & 0x3F;
}
bool bValid = true;
{
unsigned c1 = (unsigned) s[start] & 0xFF;
unsigned c2 = (unsigned) s[start+1] & 0xFF;
int c = (c1 << 8) + c2;
if( (c & 0xFE00) == 0xC000 ||
(c & 0xFFE0) == 0xE080 ||
(c & 0xFFF0) == 0xF080 ||
(c & 0xFFF8) == 0xF880 ||
(c & 0xFFFC) == 0xFC80 )
{
bValid = false;
}
}
if( ch == 0xFFFE || ch == 0xFFFF )
bValid = false;
start += len;
return bValid;
}
/* Like utf8_to_wchar_ec, but only does enough error checking to prevent crashing. */
bool utf8_to_wchar( const CString &s, unsigned &start, wchar_t &ch )
{
if( start >= s.size() )