summary refs log tree commit diff stats
path: root/nim/strutils.pas
blob: d70fdd8c321dc2d0a061008debfffb586e5329d0 (plain) (blame)
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
//
//
//           The Nimrod Compiler
//        (c) Copyright 2008 Andreas Rumpf
//
//    See the file "copying.txt", included in this
//    distribution, for details about the copyright.
//
unit strutils;

interface

{$include 'config.inc'}

uses
  sysutils, nsystem;

type
  EInvalidFormatStr = class(Exception)
  end;

const
  StrStart = 1;

function normalize(const s: string): string;
function cmpIgnoreStyle(const x, y: string): int;
function cmp(const x, y: string): int;
function cmpIgnoreCase(const x, y: string): int;

function format(const f: string; const args: array of string): string;

function toHex(x: BiggestInt; len: int): string;
function toOctal(value: Char): string;
function toOct(x: BiggestInt; len: int): string;
function toBin(x: BiggestInt; len: int): string;


procedure addChar(var s: string; c: Char);
function toInt(const s: string): int;
function toBiggestInt(const s: string): BiggestInt;

function toString(i: BiggestInt): string; overload;

//function toString(i: int): string; overload;
function ToStringF(const r: Real): string; overload;
function ToString(b: Boolean): string; overload;

function IntToStr(i: BiggestInt; minChars: int): string;

function findSubStr(const sub, s: string; start: int = 1): int;
function replaceStr(const s, search, by: string): string;
procedure deleteStr(var s: string; first, last: int);

function ToLower(const s: string): string;
function toUpper(c: Char): Char; overload;
function toUpper(s: string): string; overload;

function parseInt(const s: string): int;
function parseBiggestInt(const s: string): BiggestInt;
function ParseFloat(const s: string; checkEnd: Boolean = True): Real;

function repeatChar(count: int; c: Char = ' '): string;

type
  TStringSeq = array of string;
  TCharSet = set of Char;
function splitSeq(const s: string; const seps: TCharSet): TStringSeq;

function startsWith(const s, prefix: string): bool;
function endsWith(const s, postfix: string): bool;

const
  WhiteSpace = [' ', #9..#13];

function strip(const s: string; const chars: TCharSet = WhiteSpace): string;
function allCharsInSet(const s: string; const theSet: TCharSet): bool;

function quoteIfSpaceExists(const s: string): string;

implementation

function quoteIfSpaceExists(const s: string): string;
begin
  if (findSubStr(' ', s) >= strStart) and (s[strStart] <> '"') then
    result := '"' +{&} s +{&} '"'
  else
    result := s
end;

function allCharsInSet(const s: string; const theSet: TCharSet): bool;
var
  i: int;
begin
  for i := strStart to length(s)+strStart-1 do
    if not (s[i] in theSet) then begin result := false; exit end;
  result := true
end;

function strip(const s: string; const chars: TCharSet = WhiteSpace): string;
var
  a, b, last: int;
begin
  a := strStart;
  last := length(s) + strStart - 1;
  while (a <= last) and (s[a] in chars) do inc(a);
  b := last;
  while (b >= strStart) and (s[b] in chars) do dec(b);
  if a <= b then
    result := ncopy(s, a, b)
  else
    result := '';
end;

function startsWith(const s, prefix: string): bool;
var
  i, j: int;
begin
  result := false;
  if length(s) >= length(prefix) then begin
    i := 1;
    j := 1;
    while (i <= length(s)) and (j <= length(prefix)) do begin
      if s[i] <> prefix[j] then exit;
      inc(i);
      inc(j);
    end;
    result := j > length(prefix);
  end
end;

function endsWith(const s, postfix: string): bool;
var
  i, j: int;
begin
  result := false;
  if length(s) >= length(postfix) then begin
    i := length(s);
    j := length(postfix);
    while (i >= 1) and (j >= 1) do begin
      if s[i] <> postfix[j] then exit;
      dec(i);
      dec(j);
    end;
    result := j = 0;
  end
end;

function splitSeq(const s: string; const seps: TCharSet): TStringSeq;
var
  first, last, len: int;
begin
  first := 1;
  last := 1;
  setLength(result, 0);
  while last <= length(s) do begin
    while (last <= length(s)) and (s[last] in seps) do inc(last);
    first := last;
    while (last <= length(s)) and not (s[last] in seps) do inc(last);
    len := length(result);
    setLength(result, len+1);
    result[len] := ncopy(s, first, last-1);
  end
end;

function repeatChar(count: int; c: Char = ' '): string;
var
  i: int;
begin
  result := newString(count);
  for i := strStart to count+strStart-1 do result[i] := c
end;

function cmp(const x, y: string): int;
var
  aa, bb: char;
  a, b: PChar;
  i, j: int;
begin
  i := 0;
  j := 0;
  a := PChar(x); // this is correct even for x = ''
  b := PChar(y);
  repeat
    aa := a[i];
    bb := b[j];
    result := ord(aa) - ord(bb);
    if (result <> 0) or (aa = #0) then break;
    inc(i);
    inc(j);
  until false
end;

procedure deleteStr(var s: string; first, last: int);
begin
  delete(s, first, last - first + 1);
end;

function toUpper(c: Char): Char;
begin
  if (c >= 'a') and (c <= 'z') then
    result := Chr(Ord(c) - Ord('a') + Ord('A'))
  else
    result := c
end;

function ToString(b: Boolean): string;
begin
  if b then result := 'true'
  else result := 'false'
end;

function toOctal(value: Char): string;
var
  i: int;
  val: int;
begin
  val := ord(value);
  result := newString(3);
  for i := strStart+2 downto strStart do begin
    result[i] := Chr(val mod 8 + ord('0'));
    val := val div 8
  end;
end;

function ToLower(const s: string): string;
var
  i: int;
begin
  result := '';
  for i := strStart to length(s)+StrStart-1 do
    if s[i] in ['A'..'Z'] then
      result := result + Chr(Ord(s[i]) + Ord('a') - Ord('A'))
    else
      result := result + s[i]
end;

function toUpper(s: string): string;
var
  i: int;
begin
  result := '';
  for i := strStart to length(s)+StrStart-1 do
    if s[i] in ['a'..'z'] then
      result := result + Chr(Ord(s[i]) - Ord('a') + Ord('A'))
    else
      result := result + s[i]
end;

function findSubStr(const sub, s: string; start: int = 1): int;
var
  i, j, M, N: int;
begin
  M := length(sub); N := length(s);
  i := start; j := 1;
  if i > N then
    result := 0
  else begin
    repeat
      if s[i] = sub[j] then begin
        Inc(i); Inc(j);
      end
      else begin
        i := i - j + 2;
        j := 1
      end
    until (j > M) or (i > N);
    if j > M then result := i - M
    else result := 0
  end
end;

function replaceStr(const s, search, by: string): string;
var
  i, j: int;
begin
  result := '';
  i := 1;
  repeat
    j := findSubStr(search, s, i);
    if j = 0 then begin
      // copy the rest:
      result := result + copy(s, i, length(s) - i + 1);
      break
    end;
    result := result + copy(s, i, j - i) + by;
    i := j + length(search)
  until false
end;

function ToStringF(const r: Real): string;
var
  i: int;
begin
  result := sysutils.format('%g', [r]);
  i := pos(',', result);
  if i > 0 then result[i] := '.' // long standing bug!
  else if (cmpIgnoreStyle(result, 'nan') = 0) then // BUGFIX
    result := 'NAN'
  else if (cmpIgnoreStyle(result, 'inf') = 0) or
          (cmpIgnoreStyle(result, '+inf') = 0) then
      // FPC 2.1.1 seems to write +Inf ..., so here we go
    result := 'INF'
  else if (cmpIgnoreStyle(result, '-inf') = 0) then
    result := '-INF' // another BUGFIX
  else if pos('.', result) = 0 then
    result := result + '.0'
end;

function toInt(const s: string): int;
var
  code: int;
begin
  Val(s, result, code)
end;

function toHex(x: BiggestInt; len: int): string;
const
  HexChars: array [0..$F] of Char = '0123456789ABCDEF';
var
  j: int;
  mask, shift: BiggestInt;
begin
  assert(len > 0);
  SetLength(result, len);
  mask := $F;
  shift := 0;
  for j := len + strStart-1 downto strStart do begin
    result[j] := HexChars[(x and mask) shr shift];
    shift := shift + 4;
    mask := mask shl 4;
  end;
end;

function toOct(x: BiggestInt; len: int): string;
var
  j: int;
  mask, shift: BiggestInt;
begin
  assert(len > 0);
  result := newString(len);
  mask := 7;
  shift := 0;
  for j := len + strStart-1 downto strStart do begin
    result[j] := chr(((x and mask) shr shift) + ord('0'));
    shift := shift + 3;
    mask := mask shl 3;
  end;
end;

function toBin(x: BiggestInt; len: int): string;
var
  j: int;
  mask, shift: BiggestInt;
begin
  assert(len > 0);
  result := newString(len);
  mask := 1;
  shift := 0;
  for j := len + strStart-1 downto strStart do begin
    result[j] := chr(((x and mask) shr shift) + ord('0'));
    shift := shift + 1;
    mask := mask shl 1;
  end;
end;

procedure addChar(var s: string; c: Char);
{@ignore}
// delphi produces suboptimal code for "s := s + c"
{$ifndef fpc}
var
  len: int;
{$endif}
{@emit}
begin
{@ignore}
{$ifdef fpc}
  s := s + c
{$else}
  {$ifopt H+}
  len := length(s);
  setLength(s, len + 1);
  PChar(Pointer(s))[len] := c
  {$else}
  s := s + c
  {$endif}
{$endif}
{@emit
  s &= c
}
end;

function IntToStr(i: BiggestInt; minChars: int): string;
var
  j: int;
begin
  result := sysutils.IntToStr(i);
  for j := 1 to minChars - length(result) do
    result := '0' + result;
end;

function toBiggestInt(const s: string): BiggestInt;
begin
{$ifdef dephi}
  result := '';
  str(i : 1, result);
{$else}
  result := StrToInt64(s);
{$endif}
end;

function toString(i: BiggestInt): string; overload;
begin
  result := sysUtils.intToStr(i);
end;

function normalize(const s: string): string;
var
  i: int;
begin
  result := '';
  for i := strStart to length(s)+StrStart-1 do
    if s[i] in ['A'..'Z'] then
      result := result + Chr(Ord(s[i]) + Ord('a') - Ord('A'))
    else if s[i] <> '_' then
      result := result + s[i]
end;

function cmpIgnoreCase(const x, y: string): int;
var
  aa, bb: char;
  a, b: PChar;
  i, j: int;
begin
  i := 0;
  j := 0;
  a := PChar(x); // this is correct even for x = ''
  b := PChar(y);
  repeat
    aa := a[i];
    bb := b[j];
    if aa in ['A'..'Z'] then aa := Chr(Ord(aa) + Ord('a') - Ord('A'));
    if bb in ['A'..'Z'] then bb := Chr(Ord(bb) + Ord('a') - Ord('A'));
    result := ord(aa) - ord(bb);
    if (result <> 0) or (a[i] = #0) then break;
    inc(i);
    inc(j);
  until false
end;

function cmpIgnoreStyle(const x, y: string): int;
// this is a hotspot in the compiler!
// it took 14% of total runtime!
// So we optimize the heck out of it!
var
  aa, bb: char;
  a, b: PChar;
  i, j: int;
begin
  i := 0;
  j := 0;
  a := PChar(x); // this is correct even for x = ''
  b := PChar(y);
  repeat
    while a[i] = '_' do inc(i);
    while b[j] = '_' do inc(j);
    aa := a[i];
    bb := b[j];
    if aa in ['A'..'Z'] then aa := Chr(Ord(aa) + Ord('a') - Ord('A'));
    if bb in ['A'..'Z'] then bb := Chr(Ord(bb) + Ord('a') - Ord('A'));
    result := ord(aa) - ord(bb);
    if (result <> 0) or (a[i] = #0) then break;
    inc(i);
    inc(j);
  until false
end;

function find(const x: string; const inArray: array of string): int;
var
  i: int;
  y: string;
begin
  y := normalize(x);
  i := 0;
  while i < high(inArray) do begin
    if y = normalize(inArray[i]) then begin
      result := i; exit
    end;
    inc(i, 2); // increment by 2, else a security whole!
  end;
  result := -1
end;

function format(const f: string; const args: array of string): string;
const
  PatternChars = ['a'..'z', 'A'..'Z', '0'..'9', '_', #128..#255];
var
  i, j, x: int;
begin
  result := '';
  i := 1;
  while i <= length(f) do
    if f[i] = '$' then begin
      case f[i+1] of
        '$': begin
          result := result + '$';
          inc(i, 2);
        end;
        '1'..'9': begin
          result := result + args[ord(f[i+1]) - ord('0') - 1];
          inc(i, 2);
        end;
        '{': begin
          j := i+1;
          while (j <= length(f)) and (f[j] <> '}') do inc(j);
          x := find(ncopy(f, i+2, j-1), args);
          if (x >= 0) and (x < high(args)) then result := result + args[x+1]
          else raise EInvalidFormatStr.create('');
          i := j+1
        end;
        'a'..'z', 'A'..'Z', #128..#255, '_': begin
          j := i+1;
          while (j <= length(f)) and (f[j] in PatternChars) do inc(j);
          x := find(ncopy(f, i+1, j-1), args);
          if (x >= 0) and (x < high(args)) then result := result + args[x+1]
          else raise EInvalidFormatStr.create(ncopy(f, i+1, j-1));
          i := j
        end
        else raise EInvalidFormatStr.create('');
      end
    end
    else begin
      result := result + f[i];
      inc(i)
    end
end;

{@ignore}
{$ifopt Q-} {$Q+}
{$else}     {$define Q_off}
{$endif}
{@emit}
// this must be compiled with overflow checking turned on:
function rawParseInt(const a: string; var index: int): BiggestInt;
// index contains the start position at proc entry; end position will be
// in index before the proc returns; index = -1 on error (no number at all)
var
  i: int;
  sign: BiggestInt;
  s: string;
begin
  s := a + #0; // to avoid the sucking range check errors
  i := index; // a local i is more efficient than accessing an in out parameter
  sign := 1;
  if s[i] = '+' then inc(i)
  else if s[i] = '-' then begin
    inc(i);
    sign := -1
  end;

  if s[i] in ['0'..'9'] then begin
    result := 0;
    while s[i] in ['0'..'9'] do begin
      result := result * 10 + ord(s[i]) - ord('0');
      inc(i);
      while s[i] = '_' do inc(i) // underscores are allowed and ignored
    end;
    result := result * sign;
    index := i; // store index back
  end
  else begin
    index := -1;
    result := 0
  end
end;
{@ignore}
{$ifdef Q_off}
{$Q-} // turn it off again!!!
{$endif}
{@emit}

function parseInt(const s: string): int;
var
  index: int;
  res: BiggestInt;
begin
  index := strStart;
  res := rawParseInt(s, index);
  if index = -1 then
    raise EInvalidValue.create('')
{$ifdef cpu32}
  //else if (res < low(int)) or (res > high(int)) then
  //  raise EOverflow.create('')
{$endif}
  else
    result := int(res) // convert to smaller int type
end;

function parseBiggestInt(const s: string): BiggestInt;
var
  index: int;
  res: BiggestInt;
begin
  index := strStart;
  result := rawParseInt(s, index);
  if index = -1 then raise EInvalidValue.create('')
end;

{@ignore}
{$ifopt Q+} {$Q-}
{$else}     {$define Q_on}
{$endif}
{@emit}
// this function must be computed without overflow checking
function parseNimInt(const a: string): biggestInt;
var
  i: int;
begin
  i := StrStart;
  result := rawParseInt(a, i);
  if i = -1 then raise EInvalidValue.create('');
end;

function ParseFloat(const s: string; checkEnd: Boolean = True): Real;
var
  hd, esign, sign: Real;
  exponent, i, code: int;
  flags: cardinal;
begin
  result := 0.0;
  code := 1;
  exponent := 0;
  esign := 1;
  flags := 0;
  sign := 1;
  case s[code] of
    '+': inc(code);
    '-': begin
      sign := -1;
      inc(code);
    end;
  end;
  while (code <= Length(s)) and (s[code] in ['0'..'9']) do begin
   { Read int part }
    flags := flags or 1;
    result := result * 10.0 + toFloat(ord(s[code])-ord('0'));
    inc(code);
    while (code <= length(s)) and (s[code] = '_') do inc(code);
  end;
  { Decimal ? }
  if (length(s) >= code) and (s[code] = '.') then begin
    hd := 1.0;
    inc(code);
    while (length(s)>=code) and (s[code] in ['0'..'9']) do begin
      { Read fractional part. }
      flags := flags or 2;
      result := result * 10.0 + toFloat(ord(s[code])-ord('0'));
      hd := hd * 10.0;
      inc(code);
      while (code <= length(s)) and (s[code] = '_') do inc(code);
    end;
    result := result / hd;
  end;
  { Again, read int and fractional part }
  if flags = 0 then
    raise EInvalidValue.create('');
 { Exponent ? }
  if (length(s) >= code) and (upcase(s[code]) = 'E') then begin
    inc(code);
    if Length(s) >= code then
      if s[code] = '+' then
        inc(code)
      else
        if s[code] = '-' then begin
          esign := -1;
          inc(code);
        end;
    if (length(s) < code) or not (s[code] in ['0'..'9']) then
      raise EInvalidValue.create('');
    while (length(s) >= code) and (s[code] in ['0'..'9']) do begin
      exponent := exponent * 10;
      exponent := exponent + ord(s[code])-ord('0');
      inc(code);
      while (code <= length(s)) and (s[code] = '_') do inc(code);
    end;
  end;
  { Calculate Exponent }
  hd := 1.0;
  for i := 1 to exponent do hd := hd * 10.0;
  if esign > 0 then
    result := result * hd
  else
    result := result / hd;
  { Not all characters are read ? }
  if checkEnd and (length(s) >= code) then
    raise EInvalidValue.create('');
  { evaluate sign }
  result := result * sign;
end;

{@ignore}
{$ifdef Q_on}
{$Q+} // turn it on again!
{$endif}
{@emit
@pop # overflowChecks
}

end.