forked from exaloop/codon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstr.codon
More file actions
1484 lines (1225 loc) · 42.8 KB
/
str.codon
File metadata and controls
1484 lines (1225 loc) · 42.8 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
# Copyright (C) 2022-2023 Exaloop Inc. <https://exaloop.io>
_MAX: Static[int] = 0x7FFFFFFFFFFFFFFF
@extend
class str:
# Magic methods
def __hash__(self) -> int:
h = 0
p, n = self.ptr, self.len
i = 0
while i < n:
h = 31 * h + int(p[i])
i += 1
return h
def __lt__(self, other: str) -> bool:
return self._cmp(other) < 0
def __le__(self, other: str) -> bool:
return self._cmp(other) <= 0
def __gt__(self, other: str) -> bool:
return self._cmp(other) > 0
def __ge__(self, other: str) -> bool:
return self._cmp(other) >= 0
def __repr__(self) -> str:
v = _strbuf(len(self) + 2)
q, qe = "'", "\\'"
found_single = False
found_double = False
for c in self:
if c == "'":
found_single = True
elif c == '"':
found_double = True
if found_single and not found_double:
q, qe = '"', '\\"'
v.append(q)
for c in self:
d = c
if c == "\n":
d = "\\n"
elif c == "\r":
d = "\\r"
elif c == "\t":
d = "\\t"
elif c == "\\":
d = "\\\\"
elif c == q:
d = qe
else:
b = int(c.ptr[0])
if not (32 <= b <= 126):
h = "0123456789abcdef"
v.append("\\x")
v.append(h[b // 16])
v.append(h[b % 16])
d = ""
if d:
v.append(d)
v.append(q)
return v.__str__()
def __getitem__(self, idx: int) -> str:
if idx < 0:
idx += len(self)
if not (0 <= idx < len(self)):
raise IndexError("string index out of range")
return str(self.ptr + idx, 1)
def __getitem__(self, s: Slice) -> str:
if s.start is None and s.stop is None and s.step is None:
return self.__copy__()
elif s.step is None:
start, stop, step, length = s.adjust_indices(len(self))
return str(self.ptr + start, length)
else:
start, stop, step, length = s.adjust_indices(len(self))
return self._make_from_range(start, stop, step, length)
def _make_from_range(self, start: int, stop: int, step: int, length: int) -> str:
p = Ptr[byte](length)
j = 0
for i in range(start, stop, step):
p[j] = self.ptr[i]
j += 1
return str(p, length)
def __iter__(self) -> Generator[str]:
i = 0
n = len(self)
while i < n:
yield str(self.ptr + i, 1)
i += 1
def __reversed__(self) -> Generator[str]:
i = len(self) - 1
while i >= 0:
yield str(self.ptr + i, 1)
i -= 1
def __mul__(self, x: int) -> str:
total = x * self.len
p = Ptr[byte](total)
n = 0
for _ in range(x):
str.memcpy(p + n, self.ptr, self.len)
n += self.len
return str(p, total)
def _cmp(self, other: str) -> int:
n = min(self.len, other.len)
i = 0
while i < n:
c1 = self.ptr[i]
c2 = other.ptr[i]
if c1 != c2:
return int(c1) - int(c2)
i += 1
return self.len - other.len
import algorithms.strings as algorithms
@extend
class str:
def __contains__(self, pattern: str) -> bool:
return self.find(pattern) >= 0
# Helper methods
def _isdigit(a: byte) -> bool:
return _C.isdigit(i32(int(a))) != i32(0)
def _isspace(a: byte) -> bool:
return _C.isspace(i32(int(a))) != i32(0)
def _isupper(a: byte) -> bool:
return _C.isupper(i32(int(a))) != i32(0)
def _islower(a: byte) -> bool:
return _C.islower(i32(int(a))) != i32(0)
def _isalpha(a: byte) -> bool:
return _C.isalpha(i32(int(a))) != i32(0)
def _isalnum(a: byte) -> bool:
return _C.isalnum(i32(int(a))) != i32(0)
def _toupper(a: byte) -> byte:
return byte(int(_C.toupper(i32(int(a)))))
def _tolower(a: byte) -> byte:
return byte(int(_C.tolower(i32(int(a)))))
def _slice(self, i: int, j: int) -> str:
return str(self.ptr + i, j - i)
def _at(self, i: int) -> str:
return str(self.ptr + i, 1)
def join(self, l: Generator[str]) -> str:
buf = _strbuf()
if len(self) == 0:
for a in l:
buf.append(a)
else:
first = True
for a in l:
if first:
first = False
else:
buf.append(self)
buf.append(a)
return buf.__str__()
def join(self, l: List[str]) -> str:
if len(l) == 0:
return ""
if len(l) == 1:
return l[0]
if len(self) == 0:
return str.cat(l)
# compute length
n = 0
i = 0
while i < len(l):
n += len(l[i])
if i < len(l) - 1:
n += len(self)
i += 1
# copy to new buffer
p = Ptr[byte](n)
r = 0
i = 0
while i < len(l):
str.memcpy(p + r, l[i].ptr, len(l[i]))
r += len(l[i])
if i < len(l) - 1:
str.memcpy(p + r, self.ptr, len(self))
r += len(self)
i += 1
return str(p, n)
def isdigit(self) -> bool:
"""
str.isdigit() -> bool
Return True if all characters in str are digits
and there is at least one character in str, False otherwise.
"""
if len(self) == 0:
return False
for i in range(len(self)):
if not str._isdigit(self.ptr[i]):
return False
return True
def islower(self) -> bool:
"""
str.islower() -> bool
Return True if all cased characters in str are lowercase and there is
at least one cased character in str, False otherwise.
"""
cased = False
# For empty strings
if len(self) == 0:
return False
# For single character strings
if len(self) == 1:
return str._islower(self.ptr[0])
for i in range(len(self)):
if str._isupper(self.ptr[i]):
return False
elif not cased and str._islower(self.ptr[i]):
cased = True
return cased
def isupper(self) -> bool:
"""
str.isupper() -> bool
Return True if all cased characters in str are uppercase and there is
at least one cased character in str, False otherwise.
"""
cased = False
# For empty strings
if len(self) == 0:
return False
# For single character strings
if len(self) == 1:
return str._isupper(self.ptr[0])
for i in range(len(self)):
if str._islower(self.ptr[i]):
return False
elif not cased and str._isupper(self.ptr[i]):
cased = True
return cased
def isalnum(self) -> bool:
"""
str.isalnum() -> bool
Return True if all characters in str are alphanumeric
and there is at least one character in str, False otherwise.
"""
if len(self) == 0:
return False
for i in range(len(self)):
if not str._isalnum(self.ptr[i]):
return False
return True
def isalpha(self) -> bool:
"""
str.isalpha() -> bool
Return True if all characters in str are alphabetic
and there is at least one character in str, False otherwise.
"""
if len(self) == 0:
return False
for i in range(len(self)):
if not str._isalpha(self.ptr[i]):
return False
return True
def isspace(self) -> bool:
"""
str.isspace() -> bool
Return True if all characters in str are whitespace
and there is at least one character in str, False otherwise.
"""
if len(self) == 0:
return False
for i in range(len(self)):
if not str._isspace(self.ptr[i]):
return False
return True
def istitle(self) -> bool:
"""
str.istitle() -> bool
Return True if str is a titlecased string and there is at least one
character in str, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
# For empty strings
if len(self) == 0:
return False
# For single character strings
if len(self) == 1:
return str._isupper(self.ptr[0])
cased = False
prev_is_cased = False
for i in range(len(self)):
if str._isupper(self.ptr[i]):
if prev_is_cased:
return False
prev_is_cased = True
cased = True
elif str._islower(self.ptr[i]):
if not prev_is_cased:
return False
prev_is_cased = True
cased = True
else:
prev_is_cased = False
return cased
def capitalize(self) -> str:
"""
str.capitalize() -> copy of str
Return a copy of str with only its first character capitalized (ASCII)
and the rest lower-cased.
"""
n = len(self)
if n > 0:
p = Ptr[byte](n)
p[0] = str._toupper(self.ptr[0])
for i in range(1, n):
p[i] = str._tolower(self.ptr[i])
return str(p, n)
return ""
def isdecimal(self) -> bool:
"""
str.isdecimal() -> bool
Return True if str is a decimal string, False otherwise.
str is a decimal string if all characters in str are decimal and
there is at least one character in str.
"""
if len(self) == 0:
return False
for i in range(len(self)):
# test ascii values 48-57 == 0-9
if not (48 <= int(self.ptr[i]) <= 57):
return False
return True
def lower(self) -> str:
"""
str.lower() -> copy of str
Return a copy of str with all ASCII characters converted to lowercase.
"""
# Empty string
n = len(self)
if n == 0:
return ""
p = Ptr[byte](n)
for i in range(n):
p[i] = str._tolower(self.ptr[i])
return str(p, n)
def upper(self) -> str:
"""
str.upper() -> copy of str
Return a copy of str with all ASCII characters converted to uppercase.
"""
# Empty string
n = len(self)
if n == 0:
return ""
p = Ptr[byte](n)
for i in range(n):
p[i] = str._toupper(self.ptr[i])
return str(p, n)
def isascii(self) -> bool:
"""
str.isascii() -> bool
Return True if str is empty or all characters in str are ASCII,
False otherwise.
"""
for i in range(len(self)):
if int(self.ptr[i]) >= 128:
return False
return True
def casefold(self) -> str:
"""
str.casefold() -> copy of str
Return a version of the string suitable for caseless comparisons.
Unlike Python, casefold() deals with just ASCII characters.
"""
return self.lower()
def swapcase(self) -> str:
"""
str.swapcase() -> copy of str
Return a copy of str with uppercase ASCII characters converted
to lowercase ASCII and vice versa.
"""
# Empty string
n = len(self)
if n == 0:
return ""
p = Ptr[byte](n)
for i in range(n):
if str._islower(self.ptr[i]):
p[i] = str._toupper(self.ptr[i])
elif str._isupper(self.ptr[i]):
p[i] = str._tolower(self.ptr[i])
else:
p[i] = self.ptr[i]
return str(p, n)
def title(self) -> str:
"""
str.title() -> copy of str
Return a titlecased version of str, i.e. ASCII words start with uppercase
characters, all remaining cased characters have lowercase.
"""
prev_is_cased = False
n = len(self)
if n == 0:
return ""
p = Ptr[byte](n)
for i in range(n):
if str._islower(self.ptr[i]):
# lowercase to uppercase
if not prev_is_cased:
p[i] = str._toupper(self.ptr[i])
else:
p[i] = self.ptr[i]
prev_is_cased = True
elif str._isupper(self.ptr[i]):
# uppercase to lowercase
if prev_is_cased:
p[i] = str._tolower(self.ptr[i])
else:
p[i] = self.ptr[i]
prev_is_cased = True
else:
p[i] = self.ptr[i]
prev_is_cased = False
return str(p, n)
def isnumeric(self) -> bool:
"""
str.isdecimal() -> bool
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric
and there is at least one character in the string.
Unlike Python, isnumeric() deals with just ASCII characters.
"""
return self.isdecimal()
def _build(*args):
total = 0
for t in args:
if isinstance(t, str):
total += len(t)
else:
total += len(t[0]) * t[1]
p = Ptr[byte](total)
i = 0
for t in args:
if isinstance(t, str):
str.memcpy(p + i, t.ptr, t.len)
i += t.len
else:
s, n = t
for _ in range(n):
str.memcpy(p + i, s.ptr, s.len)
i += s.len
return str(p, total)
def ljust(self, width: int, fillchar: str = " ") -> str:
"""
ljust(width[, fillchar]) -> string
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
"""
if len(fillchar) != 1:
raise ValueError("The fill character must be exactly one character long")
if width <= len(self):
return self
return str._build(self, (fillchar, width - len(self)))
def rjust(self, width: int, fillchar: str = " ") -> str:
"""
rjust(width[, fillchar]) -> string
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
"""
if len(fillchar) != 1:
raise ValueError("The fill character must be exactly one character long")
if width <= len(self):
return self
return str._build((fillchar, width - len(self)), self)
def center(self, width: int, fillchar: str = " ") -> str:
"""
str.center(width[, fillchar]) -> string
Return str centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
if len(fillchar) != 1:
raise ValueError("The fill character must be exactly one character long")
if width <= len(self):
return self
pad = width - len(self)
left_pad = pad // 2
right_pad = width - len(self) - left_pad
return str._build((fillchar, left_pad), self, (fillchar, right_pad))
def zfill(self, width: int) -> str:
"""
str.zfill(width) -> string
Pad a numeric string str with zeros on the left, to fill a field
of the specified width. The string str is never truncated.
"""
if len(self) >= width:
return self
plus = byte(43) # +
minus = byte(45) # -
zero = byte(48) # 0
zf = self.rjust(width, '0')
fill = width - len(self)
p = zf.ptr
if p[fill] == plus or p[fill] == minus:
p[0] = p[fill]
p[fill] = zero
return zf
def count(self, sub: str, start: int = 0, end: Optional[int] = None) -> int:
"""
str.count(sub[, start[, end]]) -> int
Return the number of occurrences of subsection sub in
bytes str[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
end: int = end if end is not None else len(self)
start, end = self._correct_indices(start, end)
if end - start < len(sub):
return 0
return algorithms.count(self._slice(start, end), sub)
def find(self, sub: str, start: int = 0, end: Optional[int] = None) -> int:
"""
str.find(sub [,start [,end]]) -> int
Return the lowest index in str where substring sub is found,
such that sub is contained within str[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
end: int = end if end is not None else len(self)
start, end = self._correct_indices(start, end)
if end - start < len(sub):
return -1
pos = algorithms.find(self._slice(start, end), sub)
return pos if pos < 0 else pos + start
def rfind(self, sub: str, start: int = 0, end: Optional[int] = None) -> int:
"""
str.rfind(sub [,start [,end]]) -> int
Return the highest index in str where substring sub is found,
such that sub is contained within str[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
end: int = end if end is not None else len(self)
start, end = self._correct_indices(start, end)
if end - start < len(sub):
return -1
pos = algorithms.rfind(self._slice(start, end), sub)
return pos if pos < 0 else pos + start
def isidentifier(self) -> bool:
"""
str.isidentifier() -> bool
Return True if the string is a valid identifier, False otherwise.
Unlike Python, isidentifier() deals with just ASCII characters.
"""
# empty string
if len(self) == 0:
return False
# is not a letter or _
first = self._at(0)
if not first.isalpha():
if first != "_":
return False
if first.isalpha() or first == "_":
for i in range(1, len(self)):
ith = self._at(i)
if not ith.isalpha():
if not ith.isdecimal():
if ith != "_":
return False
return True
def isprintable(self) -> bool:
"""
str.isprintable() -> bool
Return True if the string is printable or empty, False otherwise.
Unlike Python, isprintable() deals with just ASCII characters.
"""
for i in range(len(self)):
if not (31 < int(self.ptr[i]) < 128):
return False
return True
def _has_char(self, chars: str) -> bool:
s = self._at(0)
if chars:
for c in chars:
if s == c:
return True
return False
else:
return s.isspace()
def lstrip(self, chars: str = "") -> str:
"""
str.lstrip([chars]) -> string
Return a copy of the string str with leading whitespace removed.
If chars is given, remove characters in chars instead.
Unlike Python, lstrip() deals with just ASCII characters.
"""
i = 0
while i < len(self) and self._at(i)._has_char(chars):
i += 1
return self._slice(i, len(self))
def rstrip(self, chars: str = "") -> str:
"""
str.rstrip([chars]) -> string
Return a copy of the string str with trailing whitespace removed.
If chars is given, remove characters in chars instead.
Unlike Python, rstrip() deals with just ASCII characters.
"""
i = len(self) - 1
while i >= 0 and self._at(i)._has_char(chars):
i -= 1
return self._slice(0, i + 1)
def strip(self, chars: str = "") -> str:
"""
str.strip([chars]) -> string
Return a copy of the string str with leading and trailing
whitespace removed.
If chars is given, remove characters in chars instead.
Unlike Python, strip() deals with just ASCII characters.
"""
return self.lstrip(chars).rstrip(chars)
def partition(self, sep: str) -> Tuple[str, str, str]:
"""
Search for the separator sep in str, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return str and two empty strings.
"""
if not sep:
raise ValueError("empty separator")
pos = algorithms.find(self, sep)
if pos < 0:
return self, "", ""
return self._slice(0, pos), sep, self._slice(pos + len(sep), len(self))
def rpartition(self, sep: str) -> Tuple[str, str, str]: # XXX
"""
Search for the separator sep in str, starting at the end of str, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and str.
"""
if not sep:
raise ValueError("empty separator")
pos = algorithms.rfind(self, sep)
if pos < 0:
return "", "", self
return self._slice(0, pos), sep, self._slice(pos + len(sep), len(self))
def split(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]:
"""
str.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string str, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any
whitespace string is a separator and empty strings are removed
from the result.
"""
if sep is None:
return self._split_whitespace(
maxsplit if maxsplit >= 0 else _MAX
)
sep: str = sep
if len(sep) == 0:
raise ValueError("empty separator")
# special case for length-1 pattern
if len(sep) == 1:
return self._split_char(sep.ptr[0], maxsplit if maxsplit >= 0 else _MAX)
MAX_PREALLOC = 12
maxsplit = maxsplit if maxsplit >= 0 else _MAX
prealloc_size = MAX_PREALLOC if maxsplit >= MAX_PREALLOC else maxsplit + 1
v = List[str](capacity=prealloc_size)
i = 0
j = 0
n = len(self)
while maxsplit > 0:
maxsplit -= 1
pos = algorithms.find(self._slice(i, n), sep)
if pos < 0:
break
j = i + pos
v.append(self._slice(i, j))
i = j + len(sep)
v.append(self._slice(i, n))
return v
def rsplit(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]:
"""
str.rsplit([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string str, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified, any whitespace string
is a separator.
"""
if sep is None:
return self._rsplit_whitespace(
maxsplit if maxsplit >= 0 else _MAX
)
sep: str = sep
if len(sep) == 0:
raise ValueError("empty separator")
# special case for length-1 pattern
if len(sep) == 1:
return self._rsplit_char(sep.ptr[0], maxsplit if maxsplit >= 0 else _MAX)
MAX_PREALLOC = 12
maxsplit = maxsplit if maxsplit >= 0 else _MAX
prealloc_size = MAX_PREALLOC if maxsplit >= MAX_PREALLOC else maxsplit + 1
v = List[str](capacity=prealloc_size)
i = 0
j = len(self)
n = j
while maxsplit > 0:
maxsplit -= 1
pos = algorithms.rfind(self._slice(0, j), sep)
if pos < 0:
break
v.append(self._slice(pos + len(sep), j))
j = pos
v.append(self._slice(0, j))
v.reverse()
return v
def splitlines(self, keepends: bool = False) -> List[str]:
"""
str.splitlines([keepends]) -> list of strings
Return a list of the lines in str, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
v = []
i = 0
j = 0
n = len(self)
break_r = byte(13) # \r
break_n = byte(10) # \n
while i < n:
while i < n and not (self.ptr[i] == break_r or self.ptr[i] == break_n):
i += 1
eol = i
if i < n:
if self.ptr[i] == break_r and i + 1 < n and self.ptr[i + 1] == break_n:
i += 2
else:
i += 1
if keepends:
eol = i
if j == 0 and eol == n:
v.append(self)
break
v.append(self._slice(j, eol))
j = i
return v
def startswith(
self, prefix: str, start: int = 0, end: Optional[int] = None
) -> bool:
"""
str.startswith(prefix[, start[, end]]) -> bool
Return True if str starts with the specified prefix, False otherwise.
With optional start, test str beginning at that position.
With optional end, stop comparing str at that position.
"""
end: int = end if end is not None else len(self)
if end < 0:
end += len(self)
elif start < 0:
start += len(self)
# length prefix is longer than range of string being compared to
if start + len(prefix) > len(self):
return False
# length of prefix is longer than range of string[start:end]
if end - start < len(prefix):
return False
# prefix is an empty string
if not prefix:
return True
return prefix == self._slice(start, start + len(prefix))
def endswith(self, suffix: str, start: int = 0, end: Optional[int] = None) -> bool:
"""
str.endswith(prefix[, start[, end]]) -> bool
Return True if str ends with the specified suffix, False otherwise.
With optional start, test str beginning at that position.
With optional end, stop comparing str at that position.
"""
end: int = end if end is not None else len(self)
if end < 0:
end += len(self)
elif start < 0:
start += len(self)
if end > len(self):
end = len(self)
# length prefix is longer than range of string being compared to
if end - start < len(suffix) or start > len(self):
return False
if end - len(suffix) > start:
start = end - len(suffix)
# length of prefix is longer than range of string[start:end]
if end - start < len(suffix):
return False
# prefix is an empty string
if not suffix:
return True
return suffix == self._slice(start, start + len(suffix))
def index(self, sub: str, start: int = 0, end: Optional[int] = None) -> int:
"""
str.index(sub [,start [,end]]) -> int
Like str.find() but raise ValueError when the substring is not found.
"""
i = self.find(sub, start, end)
if i == -1:
raise ValueError("substring not found")
else:
return i
def rindex(self, sub: str, start: int = 0, end: Optional[int] = None) -> int:
"""
str.index(sub [,start [,end]]) -> int
Like str.find() but raise ValueError when the substring is not found.
"""
i = self.rfind(sub, start, end)
if i == -1:
raise ValueError("substring not found")
else:
return i
def replace(self, old: str, new: str, maxcount: int = -1) -> str:
"""
str.replace(old, new[, count]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxcount is
given, only the first maxcount occurrences are replaced.
"""
return self._replace(old, new, maxcount)
def expandtabs(self, tabsize: int = 8) -> str:
"""
str.expandtabs([tabsize]) -> string
Return a copy of str where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
i = 0
j = 0
p = self.ptr
e = p + len(self)
break_r = byte(13) # \r
break_n = byte(10) # \n
tab = byte(9) # \t
space = byte(32) # ' '
def overflow():
raise OverflowError("result too long")