-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathutil.jl
1276 lines (1048 loc) · 40.9 KB
/
util.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
"""
Base.Chars = Union{AbstractChar,Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},AbstractSet{<:AbstractChar}}
An alias type for a either single character or a tuple/vector/set of characters, used to describe arguments
of several string-matching functions such as [`startswith`](@ref) and [`strip`](@ref).
!!! compat "Julia 1.11"
Julia versions prior to 1.11 only included `Set`, not `AbstractSet`, in `Base.Chars` types.
"""
const Chars = Union{AbstractChar,Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},AbstractSet{<:AbstractChar}}
# starts with and ends with predicates
"""
startswith(s::AbstractString, prefix::Union{AbstractString,Base.Chars})
Return `true` if `s` starts with `prefix`, which can be a string, a character,
or a tuple/vector/set of characters. If `prefix` is a tuple/vector/set
of characters, test whether the first character of `s` belongs to that set.
See also [`endswith`](@ref), [`contains`](@ref).
# Examples
```jldoctest
julia> startswith("JuliaLang", "Julia")
true
```
"""
function startswith(a::AbstractString, b::AbstractString)
i, j = iterate(a), iterate(b)
while true
j === nothing && return true # ran out of prefix: success!
i === nothing && return false # ran out of source: failure
i[1] == j[1] || return false # mismatch: failure
i, j = iterate(a, i[2]), iterate(b, j[2])
end
end
startswith(str::AbstractString, chars::Chars) = !isempty(str) && first(str)::AbstractChar in chars
"""
endswith(s::AbstractString, suffix::Union{AbstractString,Base.Chars})
Return `true` if `s` ends with `suffix`, which can be a string, a character,
or a tuple/vector/set of characters. If `suffix` is a tuple/vector/set
of characters, test whether the last character of `s` belongs to that set.
See also [`startswith`](@ref), [`contains`](@ref).
# Examples
```jldoctest
julia> endswith("Sunday", "day")
true
```
"""
function endswith(a::AbstractString, b::AbstractString)
a, b = Iterators.Reverse(a), Iterators.Reverse(b)
i, j = iterate(a), iterate(b)
while true
j === nothing && return true # ran out of suffix: success!
i === nothing && return false # ran out of source: failure
i[1] == j[1] || return false # mismatch: failure
i, j = iterate(a, i[2]), iterate(b, j[2])
end
end
endswith(str::AbstractString, chars::Chars) = !isempty(str) && last(str) in chars
function startswith(a::Union{String, SubString{String}},
b::Union{String, SubString{String}})
cub = ncodeunits(b)
if ncodeunits(a) < cub
false
elseif _memcmp(a, b, sizeof(b)) == 0
nextind(a, cub) == cub + 1 # check that end of `b` doesn't match a partial character in `a`
else
false
end
end
"""
startswith(io::IO, prefix::Union{AbstractString,Base.Chars})
Check if an `IO` object starts with a prefix, which can be either a string, a
character, or a tuple/vector/set of characters. See also [`peek`](@ref).
"""
function Base.startswith(io::IO, prefix::Base.Chars)
mark(io)
c = read(io, Char)
reset(io)
return c in prefix
end
function Base.startswith(io::IO, prefix::Union{String,SubString{String}})
mark(io)
s = read(io, ncodeunits(prefix))
reset(io)
return s == codeunits(prefix)
end
Base.startswith(io::IO, prefix::AbstractString) = startswith(io, String(prefix))
function endswith(a::Union{String, SubString{String}},
b::Union{String, SubString{String}})
astart = ncodeunits(a) - ncodeunits(b) + 1
if astart < 1
false
elseif GC.@preserve(a, _memcmp(pointer(a, astart), b, sizeof(b))) == 0
thisind(a, astart) == astart # check that end of `b` doesn't match a partial character in `a`
else
false
end
end
"""
contains(haystack::AbstractString, needle)
Return `true` if `haystack` contains `needle`.
This is the same as `occursin(needle, haystack)`, but is provided for consistency with
`startswith(haystack, needle)` and `endswith(haystack, needle)`.
See also [`occursin`](@ref), [`in`](@ref), [`issubset`](@ref).
# Examples
```jldoctest
julia> contains("JuliaLang is pretty cool!", "Julia")
true
julia> contains("JuliaLang is pretty cool!", 'a')
true
julia> contains("aba", r"a.a")
true
julia> contains("abba", r"a.a")
false
```
!!! compat "Julia 1.5"
The `contains` function requires at least Julia 1.5.
"""
contains(haystack::AbstractString, needle) = occursin(needle, haystack)
"""
endswith(suffix)
Create a function that checks whether its argument ends with `suffix`, i.e.
a function equivalent to `y -> endswith(y, suffix)`.
The returned function is of type `Base.Fix2{typeof(endswith)}`, which can be
used to implement specialized methods.
!!! compat "Julia 1.5"
The single argument `endswith(suffix)` requires at least Julia 1.5.
# Examples
```jldoctest
julia> endswith("Julia")("Ends with Julia")
true
julia> endswith("Julia")("JuliaLang")
false
```
"""
endswith(s) = Base.Fix2(endswith, s)
"""
startswith(prefix)
Create a function that checks whether its argument starts with `prefix`, i.e.
a function equivalent to `y -> startswith(y, prefix)`.
The returned function is of type `Base.Fix2{typeof(startswith)}`, which can be
used to implement specialized methods.
!!! compat "Julia 1.5"
The single argument `startswith(prefix)` requires at least Julia 1.5.
# Examples
```jldoctest
julia> startswith("Julia")("JuliaLang")
true
julia> startswith("Julia")("Ends with Julia")
false
```
"""
startswith(s) = Base.Fix2(startswith, s)
"""
contains(needle)
Create a function that checks whether its argument contains `needle`, i.e.
a function equivalent to `haystack -> contains(haystack, needle)`.
The returned function is of type `Base.Fix2{typeof(contains)}`, which can be
used to implement specialized methods.
"""
contains(needle) = Base.Fix2(contains, needle)
"""
chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)
Remove the first `head` and the last `tail` characters from `s`.
The call `chop(s)` removes the last character from `s`.
If it is requested to remove more characters than `length(s)`
then an empty string is returned.
See also [`chomp`](@ref), [`startswith`](@ref), [`first`](@ref).
# Examples
```jldoctest
julia> a = "March"
"March"
julia> chop(a)
"Marc"
julia> chop(a, head = 1, tail = 2)
"ar"
julia> chop(a, head = 5, tail = 5)
""
```
"""
function chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)
if isempty(s)
return SubString(s)
end
SubString(s, nextind(s, firstindex(s), head), prevind(s, lastindex(s), tail))
end
# TODO: optimization for the default case based on
# chop(s::AbstractString) = SubString(s, firstindex(s), prevind(s, lastindex(s)))
"""
chopprefix(s::AbstractString, prefix::Union{AbstractString,Regex})::SubString
Remove the prefix `prefix` from `s`. If `s` does not start with `prefix`, a string equal to `s` is returned.
See also [`chopsuffix`](@ref).
!!! compat "Julia 1.8"
This function is available as of Julia 1.8.
# Examples
```jldoctest
julia> chopprefix("Hamburger", "Ham")
"burger"
julia> chopprefix("Hamburger", "hotdog")
"Hamburger"
```
"""
function chopprefix(s::AbstractString, prefix::AbstractString)
k = firstindex(s)
i, j = iterate(s), iterate(prefix)
while true
j === nothing && i === nothing && return SubString(s, 1, 0) # s == prefix: empty result
j === nothing && return @inbounds SubString(s, k) # ran out of prefix: success!
i === nothing && return SubString(s) # ran out of source: failure
i[1] == j[1] || return SubString(s) # mismatch: failure
k = i[2]
i, j = iterate(s, k), iterate(prefix, j[2])
end
end
function chopprefix(s::Union{String, SubString{String}},
prefix::Union{String, SubString{String}})
if startswith(s, prefix)
SubString(s, 1 + ncodeunits(prefix))
else
SubString(s)
end
end
"""
chopsuffix(s::AbstractString, suffix::Union{AbstractString,Regex})::SubString
Remove the suffix `suffix` from `s`. If `s` does not end with `suffix`, a string equal to `s` is returned.
See also [`chopprefix`](@ref).
!!! compat "Julia 1.8"
This function is available as of Julia 1.8.
# Examples
```jldoctest
julia> chopsuffix("Hamburger", "er")
"Hamburg"
julia> chopsuffix("Hamburger", "hotdog")
"Hamburger"
```
"""
function chopsuffix(s::AbstractString, suffix::AbstractString)
a, b = Iterators.Reverse(s), Iterators.Reverse(suffix)
k = lastindex(s)
i, j = iterate(a), iterate(b)
while true
j === nothing && i === nothing && return SubString(s, 1, 0) # s == suffix: empty result
j === nothing && return @inbounds SubString(s, firstindex(s), k) # ran out of suffix: success!
i === nothing && return SubString(s) # ran out of source: failure
i[1] == j[1] || return SubString(s) # mismatch: failure
k = i[2]
i, j = iterate(a, k), iterate(b, j[2])
end
end
function chopsuffix(s::Union{String, SubString{String}},
suffix::Union{String, SubString{String}})
if !isempty(suffix) && endswith(s, suffix)
astart = ncodeunits(s) - ncodeunits(suffix) + 1
@inbounds SubString(s, firstindex(s), prevind(s, astart))
else
SubString(s)
end
end
"""
chomp(s::AbstractString)::SubString
Remove a single trailing newline from a string.
See also [`chop`](@ref).
# Examples
```jldoctest
julia> chomp("Hello\\n")
"Hello"
```
"""
function chomp(s::AbstractString)
i = lastindex(s)
(i < 1 || s[i] != '\n') && (return SubString(s, 1, i))
j = prevind(s,i)
(j < 1 || s[j] != '\r') && (return SubString(s, 1, j))
return SubString(s, 1, prevind(s,j))
end
function chomp(s::String)
i = lastindex(s)
if i < 1 || codeunit(s,i) != 0x0a
return @inbounds SubString(s, 1, i)
elseif i < 2 || codeunit(s,i-1) != 0x0d
return @inbounds SubString(s, 1, prevind(s, i))
else
return @inbounds SubString(s, 1, prevind(s, i-1))
end
end
"""
lstrip([pred=isspace,] str::AbstractString)::SubString
lstrip(str::AbstractString, chars)::SubString
Remove leading characters from `str`, either those specified by `chars` or those for
which the function `pred` returns `true`.
The default behaviour is to remove leading whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, or a vector or set of characters.
See also [`strip`](@ref) and [`rstrip`](@ref).
# Examples
```jldoctest
julia> a = lpad("March", 20)
" March"
julia> lstrip(a)
"March"
```
"""
function lstrip(f, s::AbstractString)
e = lastindex(s)
for (i::Int, c::AbstractChar) in pairs(s)
!f(c) && return @inbounds SubString(s, i, e)
end
SubString(s, e+1, e)
end
lstrip(s::AbstractString) = lstrip(isspace, s)
lstrip(s::AbstractString, chars::Chars) = lstrip(in(chars), s)
lstrip(::AbstractString, ::AbstractString) = throw(ArgumentError("Both arguments are strings. The second argument should be a `Char` or collection of `Char`s"))
"""
rstrip([pred=isspace,] str::AbstractString)::SubString
rstrip(str::AbstractString, chars)::SubString
Remove trailing characters from `str`, either those specified by `chars` or those for
which the function `pred` returns `true`.
The default behaviour is to remove trailing whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, or a vector or set of characters.
See also [`strip`](@ref) and [`lstrip`](@ref).
# Examples
```jldoctest
julia> a = rpad("March", 20)
"March "
julia> rstrip(a)
"March"
```
"""
function rstrip(f, s::AbstractString)
for (i, c) in Iterators.reverse(pairs(s))
f(c::AbstractChar) || return @inbounds SubString(s, 1, i::Int)
end
SubString(s, 1, 0)
end
rstrip(s::AbstractString) = rstrip(isspace, s)
rstrip(s::AbstractString, chars::Chars) = rstrip(in(chars), s)
rstrip(::AbstractString, ::AbstractString) = throw(ArgumentError("Both arguments are strings. The second argument should be a `Char` or collection of `Char`s"))
"""
strip([pred=isspace,] str::AbstractString)::SubString
strip(str::AbstractString, chars)::SubString
Remove leading and trailing characters from `str`, either those specified by `chars` or
those for which the function `pred` returns `true`.
The default behaviour is to remove leading and trailing whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, vector or set of characters.
See also [`lstrip`](@ref) and [`rstrip`](@ref).
!!! compat "Julia 1.2"
The method which accepts a predicate function requires Julia 1.2 or later.
# Examples
```jldoctest
julia> strip("{3, 5}\\n", ['{', '}', '\\n'])
"3, 5"
```
"""
strip(s::AbstractString) = lstrip(rstrip(s))
strip(s::AbstractString, chars::Chars) = lstrip(rstrip(s, chars), chars)
strip(::AbstractString, ::AbstractString) = throw(ArgumentError("Both arguments are strings. The second argument should be a `Char` or collection of `Char`s"))
strip(f, s::AbstractString) = lstrip(f, rstrip(f, s))
## string padding functions ##
"""
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ')::String
Stringify `s` and pad the resulting string on the left with `p` to make it `n`
characters (in [`textwidth`](@ref)) long. If `s` is already `n` characters long, an equal
string is returned. Pad with spaces by default.
# Examples
```jldoctest
julia> lpad("March", 10)
" March"
```
!!! compat "Julia 1.7"
In Julia 1.7, this function was changed to use `textwidth` rather than a raw character (codepoint) count.
"""
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') = lpad(string(s)::AbstractString, n, string(p))
function lpad(
s::Union{AbstractChar,AbstractString},
n::Integer,
p::Union{AbstractChar,AbstractString}=' ',
)
stringfn = if _isannotated(s) || _isannotated(p)
annotatedstring else string end
n = Int(n)::Int
m = signed(n) - Int(textwidth(s))::Int
m ≤ 0 && return stringfn(s)
l = Int(textwidth(p))::Int
if l == 0
throw(ArgumentError("$(repr(p)) has zero textwidth" * (ncodeunits(p) != 1 ? "" :
"; maybe you want pad^max(0, npad - ncodeunits(str)) * str to pad by codeunits" *
(s isa AbstractString && codeunit(s) != UInt8 ? "?" : " (bytes)?"))))
end
q, r = divrem(m, l)
r == 0 ? stringfn(p^q, s) : stringfn(p^q, first(p, r), s)
end
"""
rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ')::String
Stringify `s` and pad the resulting string on the right with `p` to make it `n`
characters (in [`textwidth`](@ref)) long. If `s` is already `n` characters long, an equal
string is returned. Pad with spaces by default.
# Examples
```jldoctest
julia> rpad("March", 20)
"March "
```
!!! compat "Julia 1.7"
In Julia 1.7, this function was changed to use `textwidth` rather than a raw character (codepoint) count.
"""
rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') = rpad(string(s)::AbstractString, n, string(p))
function rpad(
s::Union{AbstractChar,AbstractString},
n::Integer,
p::Union{AbstractChar,AbstractString}=' ',
)
stringfn = if _isannotated(s) || _isannotated(p)
annotatedstring else string end
n = Int(n)::Int
m = signed(n) - Int(textwidth(s))::Int
m ≤ 0 && return stringfn(s)
l = Int(textwidth(p))::Int
if l == 0
throw(ArgumentError("$(repr(p)) has zero textwidth" * (ncodeunits(p) != 1 ? "" :
"; maybe you want str * pad^max(0, npad - ncodeunits(str)) to pad by codeunits" *
(s isa AbstractString && codeunit(s) != UInt8 ? "?" : " (bytes)?"))))
end
q, r = divrem(m, l)
r == 0 ? stringfn(s, p^q) : stringfn(s, p^q, first(p, r))
end
"""
rtruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…')
Truncate `str` to at most `maxwidth` columns (as estimated by [`textwidth`](@ref)), replacing the last characters
with `replacement` if necessary. The default replacement string is "…".
# Examples
```jldoctest
julia> s = rtruncate("🍕🍕 I love 🍕", 10)
"🍕🍕 I lo…"
julia> textwidth(s)
10
julia> rtruncate("foo", 3)
"foo"
```
!!! compat "Julia 1.12"
This function was added in Julia 1.12.
See also [`ltruncate`](@ref) and [`ctruncate`](@ref).
"""
function rtruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…')
ret = string_truncate_boundaries(str, Int(maxwidth), replacement, Val(:right))
if isnothing(ret)
return string(str)
else
left, _ = ret::Tuple{Int,Int}
@views return str[begin:left] * replacement
end
end
"""
ltruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…')
Truncate `str` to at most `maxwidth` columns (as estimated by [`textwidth`](@ref)), replacing the first characters
with `replacement` if necessary. The default replacement string is "…".
# Examples
```jldoctest
julia> s = ltruncate("🍕🍕 I love 🍕", 10)
"…I love 🍕"
julia> textwidth(s)
10
julia> ltruncate("foo", 3)
"foo"
```
!!! compat "Julia 1.12"
This function was added in Julia 1.12.
See also [`rtruncate`](@ref) and [`ctruncate`](@ref).
"""
function ltruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…')
ret = string_truncate_boundaries(str, Int(maxwidth), replacement, Val(:left))
if isnothing(ret)
return string(str)
else
_, right = ret::Tuple{Int,Int}
@views return replacement * str[right:end]
end
end
"""
ctruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…'; prefer_left::Bool = true)
Truncate `str` to at most `maxwidth` columns (as estimated by [`textwidth`](@ref)), replacing the middle characters
with `replacement` if necessary. The default replacement string is "…". By default, the truncation
prefers keeping chars on the left, but this can be changed by setting `prefer_left` to `false`.
# Examples
```jldoctest
julia> s = ctruncate("🍕🍕 I love 🍕", 10)
"🍕🍕 …e 🍕"
julia> textwidth(s)
10
julia> ctruncate("foo", 3)
"foo"
```
!!! compat "Julia 1.12"
This function was added in Julia 1.12.
See also [`ltruncate`](@ref) and [`rtruncate`](@ref).
"""
function ctruncate(str::AbstractString, maxwidth::Integer, replacement::Union{AbstractString,AbstractChar} = '…'; prefer_left::Bool = true)
ret = string_truncate_boundaries(str, Int(maxwidth), replacement, Val(:center), prefer_left)
if isnothing(ret)
return string(str)
else
left, right = ret::Tuple{Int,Int}
@views return str[begin:left] * replacement * str[right:end]
end
end
# return whether textwidth(str) <= maxwidth
function check_textwidth(str::AbstractString, maxwidth::Integer)
# check efficiently for early return if str is wider than maxwidth
total_width = 0
for c in str
total_width += textwidth(c)
total_width > maxwidth && return false
end
return true
end
function string_truncate_boundaries(
str::AbstractString,
maxwidth::Integer,
replacement::Union{AbstractString,AbstractChar},
::Val{mode},
prefer_left::Bool = true) where {mode}
maxwidth >= 0 || throw(ArgumentError("maxwidth $maxwidth should be non-negative"))
check_textwidth(str, maxwidth) && return nothing
l0, _ = left, right = firstindex(str), lastindex(str)
width = textwidth(replacement)
# used to balance the truncated width on either side
rm_width_left, rm_width_right, force_other = 0, 0, false
@inbounds while true
if mode === :left || (mode === :center && (!prefer_left || left > l0))
rm_width = textwidth(str[right])
if mode === :left || (rm_width_right <= rm_width_left || force_other)
force_other = false
(width += rm_width) <= maxwidth || break
rm_width_right += rm_width
right = prevind(str, right)
else
force_other = true
end
end
if mode ∈ (:right, :center)
rm_width = textwidth(str[left])
if mode === :left || (rm_width_left <= rm_width_right || force_other)
force_other = false
(width += textwidth(str[left])) <= maxwidth || break
rm_width_left += rm_width
left = nextind(str, left)
else
force_other = true
end
end
end
return prevind(str, left), nextind(str, right)
end
"""
eachsplit(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
eachsplit(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
Split `str` on occurrences of the delimiter(s) `dlm` and return an iterator over the
substrings. `dlm` can be any of the formats allowed by [`findnext`](@ref)'s first argument
(i.e. as a string, regular expression or a function), or as a single character or collection
of characters.
If `dlm` is omitted, it defaults to [`isspace`](@ref).
The optional keyword arguments are:
- `limit`: the maximum size of the result. `limit=0` implies no maximum (default)
- `keepempty`: whether empty fields should be kept in the result. Default is `false` without
a `dlm` argument, `true` with a `dlm` argument.
See also [`split`](@ref).
!!! compat "Julia 1.8"
The `eachsplit` function requires at least Julia 1.8.
# Examples
```jldoctest
julia> a = "Ma.rch"
"Ma.rch"
julia> b = eachsplit(a, ".")
Base.SplitIterator{String, String}("Ma.rch", ".", 0, true)
julia> collect(b)
2-element Vector{SubString{String}}:
"Ma"
"rch"
```
"""
function eachsplit end
# Forcing specialization on `splitter` improves performance (roughly 30% decrease in runtime)
# and prevents a major invalidation risk (1550 MethodInstances)
struct SplitIterator{S<:AbstractString,F}
str::S
splitter::F
limit::Int
keepempty::Bool
end
eltype(::Type{<:SplitIterator{T}}) where T = SubString{T}
eltype(::Type{<:SplitIterator{<:SubString{T}}}) where T = SubString{T}
IteratorSize(::Type{<:SplitIterator}) = SizeUnknown()
# i: the starting index of the substring to be extracted
# k: the starting index of the next substring to be extracted
# n: the number of splits returned so far; always less than iter.limit - 1 (1 for the rest)
function iterate(iter::SplitIterator, (i, k, n)=(firstindex(iter.str), firstindex(iter.str), 0))
i - 1 > ncodeunits(iter.str)::Int && return nothing
r = findnext(iter.splitter, iter.str, k)::Union{Nothing,Int,UnitRange{Int}}
while r !== nothing && n != iter.limit - 1 && first(r) <= ncodeunits(iter.str)
j, k = first(r), nextind(iter.str, last(r))::Int
k_ = k <= j ? nextind(iter.str, j)::Int : k
if i < k
substr = @inbounds SubString(iter.str, i, prevind(iter.str, j)::Int)
(iter.keepempty || i < j) && return (substr, (k, k_, n + 1))
i = k
end
k = k_
r = findnext(iter.splitter, iter.str, k)::Union{Nothing,Int,UnitRange{Int}}
end
iter.keepempty || i <= ncodeunits(iter.str) || return nothing
@inbounds SubString(iter.str, i), (ncodeunits(iter.str) + 2, k, n + 1)
end
# Specialization for partition(s,n) to return a SubString
eltype(::Type{PartitionIterator{T}}) where {T<:AbstractString} = SubString{T}
# SubStrings do not nest
eltype(::Type{PartitionIterator{T}}) where {T<:SubString} = T
function iterate(itr::PartitionIterator{<:AbstractString}, state = firstindex(itr.c))
state > ncodeunits(itr.c) && return nothing
r = min(nextind(itr.c, state, itr.n - 1), lastindex(itr.c))
return SubString(itr.c, state, r), nextind(itr.c, r)
end
eachsplit(str::T, splitter; limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString} =
SplitIterator(str, splitter, limit, keepempty)
eachsplit(str::T, splitter::Union{Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}};
limit::Integer=0, keepempty=true) where {T<:AbstractString} =
eachsplit(str, in(splitter); limit, keepempty)
eachsplit(str::T, splitter::AbstractChar; limit::Integer=0, keepempty=true) where {T<:AbstractString} =
eachsplit(str, isequal(splitter); limit, keepempty)
# a bit oddball, but standard behavior in Perl, Ruby & Python:
eachsplit(str::AbstractString; limit::Integer=0, keepempty=false) =
eachsplit(str, isspace; limit, keepempty)
"""
eachrsplit(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
eachrsplit(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
Return an iterator over `SubString`s of `str`, produced when splitting on
the delimiter(s) `dlm`, and yielded in reverse order (from right to left).
`dlm` can be any of the formats allowed by [`findprev`](@ref)'s first argument
(i.e. a string, a single character or a function), or a collection of characters.
If `dlm` is omitted, it defaults to [`isspace`](@ref), and `keepempty` default to `false`.
The optional keyword arguments are:
- If `limit > 0`, the iterator will split at most `limit - 1` times before returning
the rest of the string unsplit. `limit < 1` implies no cap to splits (default).
- `keepempty`: whether empty fields should be returned when iterating
Default is `false` without a `dlm` argument, `true` with a `dlm` argument.
Note that unlike [`split`](@ref), [`rsplit`](@ref) and [`eachsplit`](@ref), this
function iterates the substrings right to left as they occur in the input.
See also [`eachsplit`](@ref), [`rsplit`](@ref).
!!! compat "Julia 1.11"
This function requires Julia 1.11 or later.
# Examples
```jldoctest
julia> a = "Ma.r.ch";
julia> collect(eachrsplit(a, ".")) == ["ch", "r", "Ma"]
true
julia> collect(eachrsplit(a, "."; limit=2)) == ["ch", "Ma.r"]
true
```
"""
function eachrsplit end
struct RSplitIterator{S <: AbstractString, F}
str::S
splitter::F
limit::Int
keepempty::Bool
end
eltype(::Type{<:RSplitIterator{T}}) where T = SubString{T}
eltype(::Type{<:RSplitIterator{<:SubString{T}}}) where T = SubString{T}
IteratorSize(::Type{<:RSplitIterator}) = SizeUnknown()
eachrsplit(str::T, splitter; limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString} =
RSplitIterator(str, splitter, limit, keepempty)
eachrsplit(str::T, splitter::Union{Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}};
limit::Integer=0, keepempty=true) where {T<:AbstractString} =
eachrsplit(str, in(splitter); limit, keepempty)
eachrsplit(str::T, splitter::AbstractChar; limit::Integer=0, keepempty=true) where {T<:AbstractString} =
eachrsplit(str, isequal(splitter); limit, keepempty)
# a bit oddball, but standard behavior in Perl, Ruby & Python:
eachrsplit(str::AbstractString; limit::Integer=0, keepempty=false) =
eachrsplit(str, isspace; limit, keepempty)
function Base.iterate(it::RSplitIterator, (to, remaining_splits)=(lastindex(it.str), it.limit-1))
to < 0 && return nothing
from = 1
next_to = -1
while !iszero(remaining_splits)
pos = findprev(it.splitter, it.str, to)
# If no matches: It returns the rest of the string, then the iterator stops.
if pos === nothing
from = 1
next_to = -1
break
else
from = nextind(it.str, last(pos))
# pos can be empty if we search for a zero-width delimiter, in which
# case pos is to:to-1.
# In this case, next_to must be to - 1, except if to is 0 or 1, in
# which case, we must stop iteration for some reason.
next_to = (isempty(pos) & (to < 2)) ? -1 : prevind(it.str, first(pos))
# If the element we emit is empty, discard it based on keepempty
if from > to && !(it.keepempty)
to = next_to
continue
end
break
end
end
from > to && !(it.keepempty) && return nothing
return (SubString(it.str, from, to), (next_to, remaining_splits-1))
end
"""
split(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
Split `str` into an array of substrings on occurrences of the delimiter(s) `dlm`. `dlm`
can be any of the formats allowed by [`findnext`](@ref)'s first argument (i.e. as a
string, regular expression or a function), or as a single character or collection of
characters.
If `dlm` is omitted, it defaults to [`isspace`](@ref).
The optional keyword arguments are:
- `limit`: the maximum size of the result. `limit=0` implies no maximum (default)
- `keepempty`: whether empty fields should be kept in the result. Default is `false` without
a `dlm` argument, `true` with a `dlm` argument.
See also [`rsplit`](@ref), [`eachsplit`](@ref).
# Examples
```jldoctest
julia> a = "Ma.rch"
"Ma.rch"
julia> split(a, ".")
2-element Vector{SubString{String}}:
"Ma"
"rch"
```
"""
function split(str::T, splitter;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
collect(eachsplit(str, splitter; limit, keepempty))
end
# a bit oddball, but standard behavior in Perl, Ruby & Python:
split(str::AbstractString;
limit::Integer=0, keepempty::Bool=false) =
split(str, isspace; limit, keepempty)
"""
rsplit(s::AbstractString; limit::Integer=0, keepempty::Bool=false)
rsplit(s::AbstractString, chars; limit::Integer=0, keepempty::Bool=true)
Similar to [`split`](@ref), but starting from the end of the string.
# Examples
```jldoctest
julia> a = "M.a.r.c.h"
"M.a.r.c.h"
julia> rsplit(a, ".")
5-element Vector{SubString{String}}:
"M"
"a"
"r"
"c"
"h"
julia> rsplit(a, "."; limit=1)
1-element Vector{SubString{String}}:
"M.a.r.c.h"
julia> rsplit(a, "."; limit=2)
2-element Vector{SubString{String}}:
"M.a.r.c"
"h"
```
"""
function rsplit(str::T, splitter;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
reverse!(collect(eachrsplit(str, splitter; limit, keepempty)))
end
# a bit oddball, but standard behavior in Perl, Ruby & Python:
rsplit(str::AbstractString;
limit::Integer=0, keepempty::Bool=false) =
rsplit(str, isspace; limit, keepempty)
_replace(io, repl, str, r, pattern) = print(io, repl)
_replace(io, repl::Function, str, r, pattern) =
print(io, repl(SubString(str, first(r), last(r))))
_replace(io, repl::Function, str, r, pattern::Function) =
print(io, repl(str[first(r)]))
_pat_replacer(x) = x
_free_pat_replacer(x) = nothing
_pat_replacer(x::AbstractChar) = isequal(x)
_pat_replacer(x::Union{Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}}) = in(x)
# note: leave str untyped here to make it easier for packages like StringViews to hook in
function _replace_init(str, pat_repl::NTuple{N, Pair}, count::Int) where N
count < 0 && throw(DomainError(count, "`count` must be non-negative."))
e1 = nextind(str, lastindex(str)) # sizeof(str)+1
a = firstindex(str)
patterns = map(p -> _pat_replacer(first(p)), pat_repl)
replaces = map(last, pat_repl)
rs = map(patterns) do p
r = findnext(p, str, a)
if r === nothing || first(r) == 0
return e1+1:0
end
r isa Int && (r = r:r) # findnext / performance fix
return r
end
return e1, patterns, replaces, rs, all(>(e1), map(first, rs))
end
# note: leave str untyped here to make it easier for packages like StringViews to hook in
function _replace_finish(io::IO, str, count::Int,
e1::Int, patterns::Tuple, replaces::Tuple, rs::Tuple)
n = 1
i = a = firstindex(str)
while true
p = argmin(map(first, rs)) # TODO: or argmin(rs), to pick the shortest first match ?
r = rs[p]
j, k = first(r), last(r)
j > e1 && break
if i == a || i <= k
# copy out preserved portion
GC.@preserve str unsafe_write(io, pointer(str, i), UInt(j-i))
# copy out replacement string
_replace(io, replaces[p], str, r, patterns[p])
end
if k < j
i = j
j == e1 && break
k = nextind(str, j)
else
i = k = nextind(str, k)
end
n == count && break
let k = k