forked from nim-lang/nimony
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunicode.nim
More file actions
1569 lines (1401 loc) · 51.3 KB
/
unicode.nim
File metadata and controls
1569 lines (1401 loc) · 51.3 KB
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
import syncio, assertions, strutils
#
#
# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module provides support to handle the Unicode UTF-8 encoding.
##
## There are no specialized ``insert``, ``delete``, ``add`` and ``contains``
## procedures for ``seq[Rune]`` in this module because the generic variants
## of these procedures in the system module already work with it.
##
## The current version is compatible with Unicode v12.0.0.
##
## **See also:**
## * `strutils module <strutils.html>`_
## * `unidecode module <unidecode.html>`_
## * `encodings module <encodings.html>`_
#----------------------------------------------------
when not defined(cpu32):
template chr(x: int32): char =
## TODO: fixes type inference
chr(int(x))
# func `<=%`(x, y: int): bool {.inline.} =
# ## Treats `x` and `y` as unsigned and compares them.
# ## Returns true if `unsigned(x) <= unsigned(y)`.
# cast[uint](x) <= cast[uint](y)
func `<=%`(x, y: int8): bool {.inline.} = cast[uint8](x) <= cast[uint8](y)
func `<=%`(x, y: int16): bool {.inline.} = cast[uint16](x) <= cast[uint16](y)
func `<=%`(x, y: int32): bool {.inline.} = cast[uint32](x) <= cast[uint32](y)
func `<=%`(x, y: int64): bool {.inline.} = cast[uint64](x) <= cast[uint64](y)
# func `<%`(x, y: int): bool {.inline.} =
# ## Treats `x` and `y` as unsigned and compares them.
# ## Returns true if `unsigned(x) < unsigned(y)`.
# cast[uint](x) < cast[uint](y)
func `<%`(x, y: int8): bool {.inline.} = cast[uint8](x) < cast[uint8](y)
func `<%`(x, y: int16): bool {.inline.} = cast[uint16](x) < cast[uint16](y)
func `<%`(x, y: int32): bool {.inline.} = cast[uint32](x) < cast[uint32](y)
func `<%`(x, y: int64): bool {.inline.} = cast[uint64](x) < cast[uint64](y)
func add(x: var string, y: openArray[char]) =
## Concatenates `x` and `y` in place. `y` must not overlap with `x` to
## allow future `memcpy` optimizations.
# Use `{.noalias.}` ?
let n = x.len
x.setLen n + y.len
# pending #19727
# setLen unnecessarily zeros memory
var i = 0
while i < y.len:
x[n + i] = y[i]
i.inc
#----------------------------------------------------
template toOa(s: string): openArray[char] = s.toOpenArray(0, s.high)
func substr(s: openArray[char], first, last: int): string =
# Copied substr from system
let first = max(first, 0)
let L = max(min(last, high(s)) - first + 1, 0)
result = newString(L)
for i in 0 .. L-1:
result[i] = s[i+first]
func substr(s: openArray[char]): string =
result = substr(s, 0, high(s))
type
RuneImpl = int32 # underlying type of Rune
Rune* = distinct RuneImpl ## \
## Type that can hold a single Unicode code point.
##
## A Rune may be composed with other Runes to a character on the screen.
## `RuneImpl` is the underlying type used to store Runes, currently `int32`.
template ones(n: untyped): untyped = ((1 shl n)-1)
func runeLen*(s: openArray[char]): int =
## Returns the number of runes of the string ``s``.
runnableExamples:
let a = "añyóng"
assert a.runeLen == 6
## note: a.len == 8
result = 0
var i = 0
while i < len(s):
if uint(s[i]) <= 127: inc(i)
elif uint(s[i]) shr 5 == 0b110: inc(i, 2)
elif uint(s[i]) shr 4 == 0b1110: inc(i, 3)
elif uint(s[i]) shr 3 == 0b11110: inc(i, 4)
elif uint(s[i]) shr 2 == 0b111110: inc(i, 5)
elif uint(s[i]) shr 1 == 0b1111110: inc(i, 6)
else: inc i
inc(result)
func runeLenAt*(s: openArray[char], i: Natural): int =
## Returns the number of bytes the rune starting at ``s[i]`` takes.
##
## See also:
## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
runnableExamples:
let a = "añyóng"
assert a.runeLenAt(0) == 1
assert a.runeLenAt(1) == 2
if uint(s[i]) <= 127: result = 1
elif uint(s[i]) shr 5 == 0b110: result = 2
elif uint(s[i]) shr 4 == 0b1110: result = 3
elif uint(s[i]) shr 3 == 0b11110: result = 4
elif uint(s[i]) shr 2 == 0b111110: result = 5
elif uint(s[i]) shr 1 == 0b1111110: result = 6
else: result = 1
const replRune = Rune(0xFFFD)
template fastRuneAt*(s: openArray[char], i: int, result: untyped, doInc = true): untyped =
## Returns the rune ``s[i]`` in ``result``.
##
## If ``doInc == true`` (default), ``i`` is incremented by the number
## of bytes that have been processed.
# bind ones
if uint(s[i]) <= 127:
result = Rune(uint(s[i]))
when doInc: inc(i)
elif uint(s[i]) shr 5 == 0b110:
# assert(uint(s[i+1]) shr 6 == 0b10)
if i <= s.len - 2:
result = Rune((uint(s[i]) and uint(ones(5))) shl 6 or
(uint(s[i+1]) and uint(ones(6))))
when doInc: inc(i, 2)
else:
result = replRune
when doInc: inc(i)
elif uint(s[i]) shr 4 == 0b1110:
# assert(uint(s[i+1]) shr 6 == 0b10)
# assert(uint(s[i+2]) shr 6 == 0b10)
if i <= s.len - 3:
result = Rune((uint(s[i]) and uint(ones(4))) shl 12 or
(uint(s[i+1]) and uint(ones(6))) shl 6 or
(uint(s[i+2]) and uint(ones(6))))
when doInc: inc(i, 3)
else:
result = replRune
when doInc: inc(i)
elif uint(s[i]) shr 3 == 0b11110:
# assert(uint(s[i+1]) shr 6 == 0b10)
# assert(uint(s[i+2]) shr 6 == 0b10)
# assert(uint(s[i+3]) shr 6 == 0b10)
if i <= s.len - 4:
result = Rune((uint(s[i]) and uint(ones(3))) shl 18 or
(uint(s[i+1]) and uint(ones(6))) shl 12 or
(uint(s[i+2]) and uint(ones(6))) shl 6 or
(uint(s[i+3]) and uint(ones(6))))
when doInc: inc(i, 4)
else:
result = replRune
when doInc: inc(i)
elif uint(s[i]) shr 2 == 0b111110:
# assert(uint(s[i+1]) shr 6 == 0b10)
# assert(uint(s[i+2]) shr 6 == 0b10)
# assert(uint(s[i+3]) shr 6 == 0b10)
# assert(uint(s[i+4]) shr 6 == 0b10)
if i <= s.len - 5:
result = Rune((uint(s[i]) and uint(ones(2))) shl 24 or
(uint(s[i+1]) and uint(ones(6))) shl 18 or
(uint(s[i+2]) and uint(ones(6))) shl 12 or
(uint(s[i+3]) and uint(ones(6))) shl 6 or
(uint(s[i+4]) and uint(ones(6))))
when doInc: inc(i, 5)
else:
result = replRune
when doInc: inc(i)
elif uint(s[i]) shr 1 == 0b1111110:
# assert(uint(s[i+1]) shr 6 == 0b10)
# assert(uint(s[i+2]) shr 6 == 0b10)
# assert(uint(s[i+3]) shr 6 == 0b10)
# assert(uint(s[i+4]) shr 6 == 0b10)
# assert(uint(s[i+5]) shr 6 == 0b10)
if i <= s.len - 6:
result = Rune((uint(s[i]) and uint(ones(1))) shl 30 or
(uint(s[i+1]) and uint(ones(6))) shl 24 or
(uint(s[i+2]) and uint(ones(6))) shl 18 or
(uint(s[i+3]) and uint(ones(6))) shl 12 or
(uint(s[i+4]) and uint(ones(6))) shl 6 or
(uint(s[i+5]) and uint(ones(6))))
when doInc: inc(i, 6)
else:
result = replRune
when doInc: inc(i)
else:
result = Rune(uint(s[i]))
when doInc: inc(i)
func runeAt*(s: openArray[char], i: Natural): Rune =
## Returns the rune in ``s`` at **byte index** ``i``.
##
## See also:
## * `runeAtPos func <#runeAtPos,string,int>`_
## * `runeStrAtPos func <#runeStrAtPos,string,Natural>`_
## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
runnableExamples:
let a = "añyóng"
assert a.runeAt(1) == "ñ".runeAt(0)
assert a.runeAt(2) == "ñ".runeAt(1)
assert a.runeAt(3) == "y".runeAt(0)
fastRuneAt(s, i, result, false)
func validateUtf8*(s: openArray[char]): int =
## Returns the position of the invalid byte in ``s`` if the string ``s`` does
## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
##
## See also:
## * `toUTF8 func <#toUTF8,Rune>`_
## * `$ func <#$,Rune>`_ alias for `toUTF8`
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
var i = 0
let L = s.len
while i < L:
if uint(s[i]) <= 127:
inc(i)
elif uint(s[i]) shr 5 == 0b110:
if uint(s[i]) < 0xc2: return i # Catch overlong ascii representations.
if i+1 < L and uint(s[i+1]) shr 6 == 0b10: inc(i, 2)
else: return i
elif uint(s[i]) shr 4 == 0b1110:
if i+2 < L and uint(s[i+1]) shr 6 == 0b10 and uint(s[i+2]) shr 6 == 0b10:
inc i, 3
else: return i
elif uint(s[i]) shr 3 == 0b11110:
if i+3 < L and uint(s[i+1]) shr 6 == 0b10 and
uint(s[i+2]) shr 6 == 0b10 and
uint(s[i+3]) shr 6 == 0b10:
inc i, 4
else: return i
else:
return i
return -1
template fastToUTF8Copy*(c: Rune, s: var string, pos: int, doInc = true): untyped {.untyped.} =
## Copies UTF-8 representation of ``c`` into the preallocated string ``s``
## starting at position ``pos``.
##
## If ``doInc == true`` (default), ``pos`` is incremented
## by the number of bytes that have been processed.
##
## To be the most efficient, make sure ``s`` is preallocated
## with an additional amount equal to the byte length of ``c``.
##
## See also:
## * `validateUtf8 func <#validateUtf8,string>`_
## * `toUTF8 func <#toUTF8,Rune>`_
## * `$ func <#$,Rune>`_ alias for `toUTF8`
var i = RuneImpl(c)
if i <=% 127:
s.setLen(pos+1)
s[pos+0] = chr(i)
when doInc: inc(pos)
elif i <=% 0x07FF:
s.setLen(pos+2)
s[pos+0] = chr((i shr 6) or 0b110_00000)
s[pos+1] = chr((i and ones(6)) or 0b10_0000_00)
when doInc: inc(pos, 2)
elif i <=% 0xFFFF:
s.setLen(pos+3)
s[pos+0] = chr(i shr 12 or 0b1110_0000)
s[pos+1] = chr(i shr 6 and ones(6) or 0b10_0000_00)
s[pos+2] = chr(i and ones(6) or 0b10_0000_00)
when doInc: inc(pos, 3)
elif i <=% 0x001FFFFF:
s.setLen(pos+4)
s[pos+0] = chr(i shr 18 or 0b1111_0000)
s[pos+1] = chr(i shr 12 and ones(6) or 0b10_0000_00)
s[pos+2] = chr(i shr 6 and ones(6) or 0b10_0000_00)
s[pos+3] = chr(i and ones(6) or 0b10_0000_00)
when doInc: inc(pos, 4)
elif i <=% 0x03FFFFFF:
s.setLen(pos+5)
s[pos+0] = chr(i shr 24 or 0b111110_00)
s[pos+1] = chr(i shr 18 and ones(6) or 0b10_0000_00)
s[pos+2] = chr(i shr 12 and ones(6) or 0b10_0000_00)
s[pos+3] = chr(i shr 6 and ones(6) or 0b10_0000_00)
s[pos+4] = chr(i and ones(6) or 0b10_0000_00)
when doInc: inc(pos, 5)
elif i <=% 0x7FFFFFFF:
s.setLen(pos+6)
s[pos+0] = chr(i shr 30 or 0b1111110_0)
s[pos+1] = chr(i shr 24 and ones(6) or 0b10_0000_00)
s[pos+2] = chr(i shr 18 and ones(6) or 0b10_0000_00)
s[pos+3] = chr(i shr 12 and ones(6) or 0b10_0000_00)
s[pos+4] = chr(i shr 6 and ones(6) or 0b10_0000_00)
s[pos+5] = chr(i and ones(6) or 0b10_0000_00)
when doInc: inc(pos, 6)
else:
discard # error, exception?
func toUTF8*(c: Rune): string =
## Converts a rune into its UTF-8 representation.
##
## See also:
## * `validateUtf8 func <#validateUtf8,string>`_
## * `$ func <#$,Rune>`_ alias for `toUTF8`
## * `utf8 iterator <#utf8.i,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
runnableExamples:
let a = "añyóng"
assert a.runeAt(1).toUTF8 == "ñ"
result = ""
fastToUTF8Copy(c, result, 0, false)
func add*(s: var string; c: Rune) =
## Adds a rune ``c`` to a string ``s``.
runnableExamples:
var s = "abc"
let c = "ä".runeAt(0)
s.add(c)
assert s == "abcä"
let pos = s.len
fastToUTF8Copy(c, s, pos, false)
func `$`*(rune: Rune): string =
## An alias for `toUTF8 <#toUTF8,Rune>`_.
##
## See also:
## * `validateUtf8 func <#validateUtf8,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
rune.toUTF8
func `$`*(runes: seq[Rune]): string =
## Converts a sequence of Runes to a string.
##
## See also:
## * `toRunes <#toRunes,string>`_ for a reverse operation
runnableExamples:
let
someString = "öÑ"
someRunes = toRunes(someString)
assert $someRunes == someString
result = ""
for rune in runes:
result.add rune
func runeOffset*(s: openArray[char], pos: Natural, start: Natural = 0): int =
## Returns the byte position of rune
## at position ``pos`` in ``s`` with an optional start byte position.
## Returns the special value -1 if it runs out of the string.
##
## **Beware:** This can lead to unoptimized code and slow execution!
## Most problems can be solved more efficiently by using an iterator
## or conversion to a seq of Rune.
##
## See also:
## * `runeReverseOffset func <#runeReverseOffset,string,Positive>`_
runnableExamples:
let a = "añyóng"
assert a.runeOffset(1) == 1
assert a.runeOffset(3) == 4
assert a.runeOffset(4) == 6
var
i = 0
o = start
while i < pos:
o = o + runeLenAt(s, o)
if o >= s.len:
return -1
inc i
return o
func runeReverseOffset*(s: openArray[char], rev: Positive): (int, int) =
## Returns a tuple with the byte offset of the
## rune at position ``rev`` in ``s``, counting
## from the end (starting with 1) and the total
## number of runes in the string.
##
## Returns a negative value for offset if there are too few runes in
## the string to satisfy the request.
##
## **Beware:** This can lead to unoptimized code and slow execution!
## Most problems can be solved more efficiently by using an iterator
## or conversion to a seq of Rune.
##
## See also:
## * `runeOffset func <#runeOffset,string,Natural,Natural>`_
var
a = rev.int
o = 0
x = 0
let times = 2*rev.int-s.runeLen # transformed from rev.int - a < s.runeLen - rev.int
while o < s.len:
let r = runeLenAt(s, o)
o = o + r
if a > times:
x = x + r
dec a
result = if a > 0: (-a, rev.int-a) else: (x, -a+rev.int)
func runeAtPos*(s: openArray[char], pos: int): Rune =
## Returns the rune at position ``pos``.
##
## **Beware:** This can lead to unoptimized code and slow execution!
## Most problems can be solved more efficiently by using an iterator
## or conversion to a seq of Rune.
##
## See also:
## * `runeAt func <#runeAt,string,Natural>`_
## * `runeStrAtPos func <#runeStrAtPos,string,Natural>`_
## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
fastRuneAt(s, runeOffset(s, pos), result, false)
func runeStrAtPos*(s: openArray[char], pos: Natural): string =
## Returns the rune at position ``pos`` as UTF8 String.
##
## **Beware:** This can lead to unoptimized code and slow execution!
## Most problems can be solved more efficiently by using an iterator
## or conversion to a seq of Rune.
##
## See also:
## * `runeAt func <#runeAt,string,Natural>`_
## * `runeAtPos func <#runeAtPos,string,int>`_
## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
let o = runeOffset(s, pos)
substr(s.toOpenArray(o, (o+runeLenAt(s, o)-1)))
func runeSubStr*(s: openArray[char], pos: int, len: int = int.high): string =
## Returns the UTF-8 substring starting at code point ``pos``
## with ``len`` code points.
##
## If ``pos`` or ``len`` is negative they count from
## the end of the string. If ``len`` is not given it means the longest
## possible string.
runnableExamples:
let s = "Hänsel ««: 10,00€"
assert(runeSubStr(s, 0, 2) == "Hä")
assert(runeSubStr(s, 10, 1) == ":")
assert(runeSubStr(s, -6) == "10,00€")
assert(runeSubStr(s, 10) == ": 10,00€")
assert(runeSubStr(s, 12, 5) == "10,00")
assert(runeSubStr(s, -6, 3) == "10,")
if pos < 0:
let (o, rl) = runeReverseOffset(s, -pos)
if len >= rl:
result = s.substr(o, s.high)
elif len < 0:
let e = rl + len
if e < 0:
result = ""
else:
result = s.substr(o, runeOffset(s, e-(rl+pos), o)-1)
else:
result = s.substr(o, runeOffset(s, len, o)-1)
else:
let o = runeOffset(s, pos)
if o < 0:
result = ""
elif len == int.high:
result = s.substr(o, s.len-1)
elif len < 0:
let (e, rl) = runeReverseOffset(s, -len)
discard rl
if e <= 0:
result = ""
else:
result = s.substr(o, e-1)
else:
var e = runeOffset(s, len, o)
if e < 0:
e = s.len
result = s.substr(o, e-1)
func `<=%`*(a, b: Rune): bool =
## Checks if code point of `a` is smaller or equal to code point of `b`.
runnableExamples:
let
a = "ú".runeAt(0)
b = "ü".runeAt(0)
assert a <=% b
return int(a) <=% int(b)
func `<%`*(a, b: Rune): bool =
## Checks if code point of `a` is smaller than code point of `b`.
runnableExamples:
let
a = "ú".runeAt(0)
b = "ü".runeAt(0)
assert a <% b
return int(a) <% int(b)
func `==`*(a, b: Rune): bool =
## Checks if two runes are equal.
return int(a) == int(b)
include "includes/unicode_ranges"
func binarySearch(c: RuneImpl, tab: openArray[int32], len, stride: int): int =
var n = len
var t = 0
while n > 1:
var m = n div 2
var p = t + m*stride
if c >= tab[p]:
t = p
n = n-m
else:
n = m
if n != 0 and c >= tab[t]:
return t
return -1
func toLower*(c: Rune): Rune =
## Converts ``c`` into lower case. This works for any rune.
##
## If possible, prefer ``toLower`` over ``toUpper``.
##
## See also:
## * `toUpper func <#toUpper,Rune>`_
## * `toTitle func <#toTitle,Rune>`_
## * `isLower func <#isLower,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return Rune(c + toLowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return Rune(c + toLowerSinglets[p+1] - 500)
return Rune(c)
func toUpper*(c: Rune): Rune =
## Converts ``c`` into upper case. This works for any rune.
##
## If possible, prefer ``toLower`` over ``toUpper``.
##
## See also:
## * `toLower func <#toLower,Rune>`_
## * `toTitle func <#toTitle,Rune>`_
## * `isUpper func <#isUpper,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return Rune(c + toUpperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return Rune(c + toUpperSinglets[p+1] - 500)
return Rune(c)
func toTitle*(c: Rune): Rune =
## Converts ``c`` to title case.
##
## See also:
## * `toLower func <#toLower,Rune>`_
## * `toUpper func <#toUpper,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2)
if p >= 0 and c == toTitleSinglets[p]:
return Rune(c + toTitleSinglets[p+1] - 500)
return Rune(c)
func isLower*(c: Rune): bool =
## Returns true if ``c`` is a lower case rune.
##
## If possible, prefer ``isLower`` over ``isUpper``.
##
## See also:
## * `toLower func <#toLower,Rune>`_
## * `isUpper func <#isUpper,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
var c = RuneImpl(c)
# Note: toUpperRanges is correct here!
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return true
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return true
else:
return false
func isUpper*(c: Rune): bool =
## Returns true if ``c`` is a upper case rune.
##
## If possible, prefer ``isLower`` over ``isUpper``.
##
## See also:
## * `toUpper func <#toUpper,Rune>`_
## * `isLower func <#isLower,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
## * `isAlpha func <#isAlpha,Rune>`_
## * `isWhiteSpace func <#isWhiteSpace,Rune>`_
var c = RuneImpl(c)
# Note: toLowerRanges is correct here!
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return true
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return true
else:
return false
func isAlpha*(c: Rune): bool =
## Returns true if ``c`` is an *alpha* rune (i.e., a letter).
##
## See also:
## * `isLower func <#isLower,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
## * `isAlpha func <#isAlpha,Rune>`_
## * `isWhiteSpace func <#isWhiteSpace,Rune>`_
## * `isCombining func <#isCombining,Rune>`_
if isUpper(c) or isLower(c):
return true
var c = RuneImpl(c)
var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2)
if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]:
return true
p = binarySearch(c, alphaSinglets, len(alphaSinglets), 1)
if p >= 0 and c == alphaSinglets[p]:
return true
else:
return false
func isTitle*(c: Rune): bool =
## Returns true if ``c`` is a Unicode titlecase code point.
##
## See also:
## * `toTitle func <#toTitle,Rune>`_
## * `isLower func <#isLower,Rune>`_
## * `isUpper func <#isUpper,Rune>`_
## * `isAlpha func <#isAlpha,Rune>`_
## * `isWhiteSpace func <#isWhiteSpace,Rune>`_
return isUpper(c) and isLower(c)
func isWhiteSpace*(c: Rune): bool =
## Returns true if ``c`` is a Unicode whitespace code point.
##
## See also:
## * `isLower func <#isLower,Rune>`_
## * `isUpper func <#isUpper,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
## * `isAlpha func <#isAlpha,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2)
if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]:
return true
else:
return false
func isCombining*(c: Rune): bool =
## Returns true if ``c`` is a Unicode combining code unit.
##
## See also:
## * `isLower func <#isLower,Rune>`_
## * `isUpper func <#isUpper,Rune>`_
## * `isTitle func <#isTitle,Rune>`_
## * `isAlpha func <#isAlpha,Rune>`_
var c = RuneImpl(c)
# Optimized to return false immediately for ASCII
return c >= 0x0300 and (c <= 0x036f or
(c >= 0x1ab0 and c <= 0x1aff) or
(c >= 0x1dc0 and c <= 0x1dff) or
(c >= 0x20d0 and c <= 0x20ff) or
(c >= 0xfe20 and c <= 0xfe2f))
func runeCheck(s: openArray[char], runeProc: proc (c: Rune): bool {.noSideEffect, nimcall.}): bool =
## Common code for isAlpha and isSpace.
result = if len(s) == 0: false else: true
var
i = 0
rune: Rune
while i < len(s) and result:
fastRuneAt(s, i, rune, doInc = true)
result = runeProc(rune) and result
func isAlphaImpl(c: Rune): bool =
# TODO: fixes templates # bug #1305
result = isAlpha(c)
func isAlpha*(s: openArray[char]): bool {.noSideEffect.} =
## Returns true if ``s`` contains all alphabetic runes.
runnableExamples:
let a = "añyóng"
assert a.isAlpha
runeCheck(s, isAlphaImpl)
func isSpace*(s: openArray[char]): bool {.noSideEffect.} =
## Returns true if ``s`` contains all whitespace runes.
runnableExamples:
let a = "\t\l \v\r\f"
assert a.isSpace
runeCheck(s, isWhiteSpace)
func convertRune(s: openArray[char], runeProc: proc (c: Rune): Rune {.noSideEffect, nimcall.}): string =
## Convert runes in ``s`` using ``runeProc`` as the converter.
result = newString(len(s))
var
i = 0
resultIndex = 0
rune: Rune
while i < len(s):
fastRuneAt(s, i, rune, doInc = true)
rune = runeProc(rune)
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
func toUpperImpl(c: Rune): Rune =
result = toUpper(c)
func toUpper*(s: openArray[char]): string {.noSideEffect.} =
## Converts ``s`` into upper-case runes.
runnableExamples:
assert toUpper("abγ") == "ABΓ"
convertRune(s, toUpperImpl)
func toLowerImpl(c: Rune): Rune =
result = toLower(c)
func toLower*(s: openArray[char]): string {.noSideEffect.} =
## Converts ``s`` into lower-case runes.
runnableExamples:
assert toLower("ABΓ") == "abγ"
convertRune(s, toLowerImpl)
func swapCase*(s: openArray[char]): string {.noSideEffect.} =
## Swaps the case of runes in ``s``.
##
## Returns a new string such that the cases of all runes
## are swapped if possible.
runnableExamples:
assert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
var
i = 0
resultIndex = 0
rune: Rune
result = newString(len(s))
while i < len(s):
fastRuneAt(s, i, rune)
if rune.isUpper():
rune = rune.toLower()
elif rune.isLower():
rune = rune.toUpper()
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
func capitalize*(s: openArray[char]): string {.noSideEffect.} =
## Converts the first character of ``s`` into an upper-case rune.
runnableExamples:
assert capitalize("βeta") == "Βeta"
if len(s) == 0:
return ""
var
rune: Rune
i = 0
fastRuneAt(s, i, rune, doInc = true)
result = $toUpper(rune) & substr(s.toOpenArray(i, s.high))
# when not defined(nimHasEffectsOf):
# {.pragma: effectsOf.}
func translate*(s: openArray[char], replacements: proc(key: string): string {.noSideEffect.}): string = #{.
#rtl, extern: "nuc$1", effectsOf: replacements.} =
## Translates words in a string using the ``replacements`` func to substitute
## words inside ``s`` with their replacements.
##
## ``replacements`` is any func that takes a word and returns
## a new word to fill it's place.
runnableExamples:
func wordToNumber(s: string): string =
case s
of "one": "1"
of "two": "2"
else: s
let a = "one two three four"
assert a.translate(wordToNumber) == "1 2 three four"
# Allocate memory for the new string based on the old one.
# If the new string length is less than the old, no allocations
# will be needed. If the new string length is greater than the
# old, then maybe only one allocation is needed
result = newStringOfCap(s.len)
var
index = 0
lastIndex = 0
wordStart = 0
inWord = false
rune: Rune
while index < len(s):
lastIndex = index
fastRuneAt(s, index, rune)
let whiteSpace = rune.isWhiteSpace()
if whiteSpace and inWord:
# If we've reached the end of a word
let word = substr(s.toOpenArray(wordStart, lastIndex - 1))
result.add(replacements(word))
result.add($rune)
inWord = false
elif not whiteSpace and not inWord:
# If we've hit a non space character and
# are not currently in a word, track
# the starting index of the word
inWord = true
wordStart = lastIndex
elif whiteSpace:
result.add($rune)
if wordStart < len(s) and inWord:
# Get the trailing word at the end
let word = substr(s.toOpenArray(wordStart, s.high))
result.add(replacements(word))
func title*(s: openArray[char]): string {.noSideEffect.} =
## Converts ``s`` to a unicode title.
##
## Returns a new string such that the first character
## in each word inside ``s`` is capitalized.
runnableExamples:
assert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
var
i = 0
resultIndex = 0
rune: Rune
result = newString(len(s))
var firstRune = true
while i < len(s):
fastRuneAt(s, i, rune)
if not rune.isWhiteSpace() and firstRune:
rune = rune.toUpper()
firstRune = false
elif rune.isWhiteSpace():
firstRune = true
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
iterator runes*(s: openArray[char]): Rune =
## Iterates over any rune of the string ``s`` returning runes.
var
i = 0
result: Rune
while i < len(s):
fastRuneAt(s, i, result, true)
yield result
iterator utf8*(s: openArray[char]): string =
## Iterates over any rune of the string ``s`` returning utf8 values.
##
## See also:
## * `validateUtf8 func <#validateUtf8,string>`_
## * `toUTF8 func <#toUTF8,Rune>`_
## * `$ func <#$,Rune>`_ alias for `toUTF8`
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
var o = 0
while o < s.len:
let n = runeLenAt(s, o)
yield substr(s.toOpenArray(o, (o+n-1)))
o = o + n
func toRunes*(s: openArray[char]): seq[Rune] =
## Obtains a sequence containing the Runes in ``s``.
##
## See also:
## * `$ func <#$,Rune>`_ for a reverse operation
runnableExamples:
let a = toRunes("aáä")
assert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)]
result = newSeq[Rune](0)
for r in s.runes:
result.add(r)
func cmpRunesIgnoreCase*(a, b: openArray[char]): int =
## Compares two UTF-8 strings and ignores the case. Returns:
##
## | `0` if a == b
## | `< 0` if a < b
## | `> 0` if a > b
var i = 0
var j = 0
var ar, br: Rune
while i < a.len and j < b.len:
# slow path:
fastRuneAt(a, i, ar)
fastRuneAt(b, j, br)
when (defined(cpu16) or defined(cpu8)):
const lo = low(int).int32
const hi = high(int).int32
result = clamp(RuneImpl(toLower(ar)) - RuneImpl(toLower(br)), lo, hi).int
else:
result = RuneImpl(toLower(ar)) - RuneImpl(toLower(br))
if result != 0: return result
result = a.len - b.len
func reversed*(s: openArray[char]): string =
## Returns the reverse of ``s``, interpreting it as runes.
##
## Unicode combining characters are correctly interpreted as well.
runnableExamples:
assert reversed("Reverse this!") == "!siht esreveR"
assert reversed("先秦兩漢") == "漢兩秦先"
assert reversed("as⃝df̅") == "f̅ds⃝a"
assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
var
i = 0
lastI = 0
newPos = len(s) - 1
blockPos = 0
r: Rune
template reverseUntil(pos: int) =
var j = pos - 1
while j > blockPos:
result[newPos] = s[j]
dec j
dec newPos
blockPos = pos - 1
result = newString(len(s))
while i < len(s):
lastI = i
fastRuneAt(s, i, r, true)
if not isCombining(r):
reverseUntil(lastI)
reverseUntil(len(s))
func graphemeLen*(s: openArray[char]; i: Natural): Natural =
## The number of bytes belonging to byte index ``s[i]``,
## including following combining code units.
runnableExamples:
let a = "añyóng"
assert a.graphemeLen(1) == 2 ## ñ
assert a.graphemeLen(2) == 1
assert a.graphemeLen(4) == 2 ## ó
result = 0
var j = i.int
var r, r2: Rune
if j < s.len:
fastRuneAt(s, j, r, true)
result = j-i
while j < s.len:
fastRuneAt(s, j, r2, true)
if not isCombining(r2): break
result = j-i
func lastRune*(s: openArray[char]; last: int): (Rune, int) =
## Length of the last rune in ``s[0..last]``. Returns the rune and its length
## in bytes.
if s[last] <= chr(127):
result = (Rune(s[last]), 1)
else:
var L = 0
while last-L >= 0 and uint(s[last-L]) shr 6 == 0b10: inc(L)
var r: Rune
fastRuneAt(s, last-L, r, false)
result = (r, L+1)
func size*(r: Rune): int {.noSideEffect.} =
## Returns the number of bytes the rune ``r`` takes.
runnableExamples:
let a = toRunes "aá"
assert size(a[0]) == 1
assert size(a[1]) == 2
let v = r.uint32
if v <= 0x007F'u32: result = 1
elif v <= 0x07FF'u32: result = 2
elif v <= 0xFFFF'u32: result = 3
elif v <= 0x1FFFFF'u32: result = 4
elif v <= 0x3FFFFFF'u32: result = 5
elif v <= 0x7FFFFFFF'u32: result = 6
else: result = 1
# --------- Private templates for different split separators -----------
func stringHasSep(s: openArray[char], index: int, seps: openArray[Rune]): bool =
var rune: Rune
fastRuneAt(s, index, rune, false)