-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathstring.cr
4338 lines (3824 loc) · 115 KB
/
string.cr
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
require "c/stdlib"
require "c/string"
# A `String` represents an immutable sequence of UTF-8 characters.
#
# A `String` is typically created with a string literal, enclosing UTF-8 characters
# in double quotes:
#
# ```
# "hello world"
# ```
#
# A backslash can be used to denote some characters inside the string:
#
# ```
# "\"" # double quote
# "\\" # backslash
# "\e" # escape
# "\f" # form feed
# "\n" # newline
# "\r" # carriage return
# "\t" # tab
# "\v" # vertical tab
# ```
#
# You can use a backslash followed by an *u* and four hexadecimal characters to denote a unicode codepoint written:
#
# ```
# "\u0041" # == "A"
# ```
#
# Or you can use curly braces and specify up to six hexadecimal numbers (0 to 10FFFF):
#
# ```
# "\u{41}" # == "A"
# ```
#
# A string can span multiple lines:
#
# ```
# "hello
# world" # same as "hello\n world"
# ```
#
# Note that in the above example trailing and leading spaces, as well as newlines,
# end up in the resulting string. To avoid this, you can split a string into multiple lines
# by joining multiple literals with a backslash:
#
# ```
# "hello " \
# "world, " \
# "no newlines" # same as "hello world, no newlines"
# ```
#
# Alternatively, a backslash followed by a newline can be inserted inside the string literal:
#
# ```
# "hello \
# world, \
# no newlines" # same as "hello world, no newlines"
# ```
#
# In this case, leading whitespace is not included in the resulting string.
#
# If you need to write a string that has many double quotes, parentheses, or similar
# characters, you can use alternative literals:
#
# ```
# # Supports double quotes and nested parentheses
# %(hello ("world")) # same as "hello (\"world\")"
#
# # Supports double quotes and nested brackets
# %[hello ["world"]] # same as "hello [\"world\"]"
#
# # Supports double quotes and nested curlies
# %{hello {"world"}} # same as "hello {\"world\"}"
#
# # Supports double quotes and nested angles
# %<hello <"world">> # same as "hello <\"world\">"
# ```
#
# To create a `String` with embedded expressions, you can use string interpolation:
#
# ```
# a = 1
# b = 2
# "sum = #{a + b}" # "sum = 3"
# ```
#
# This ends up invoking `Object#to_s(IO)` on each expression enclosed by `#{...}`.
#
# If you need to dynamically build a string, use `String#build` or `IO::Memory`.
#
# ### Non UTF-8 valid strings
#
# String might end up being conformed of bytes which are an invalid
# byte sequence according to UTF-8. This can happen if the string is created
# via one of the constructors that accept bytes, or when getting a string
# from `String.build` or `IO::Memory`. No exception will be raised, but
# invalid byte sequences, when asked as chars, will use the unicode replacement
# char (value 0xFFFD). For example:
#
# ```
# # here 255 is not a valid byte value in the UTF-8 encoding
# string = String.new(Bytes[255, 97])
# string.valid_encoding? # => false
#
# # The first char here is the unicode replacement char
# string.chars # => ['�', 'a']
# ```
#
# One can also create strings with specific byte value in them by
# using octal and hexadecimal escape sequences:
#
# ```
# # Octal escape sequences
# "\101" # # => "A"
# "\12" # # => "\n"
# "\1" # string with one character with code point 1
# "\377" # string with one byte with value 255
#
# # Hexadecimal escape sequences
# "\x41" # # => "A"
# "\xFF" # string with one byte with value 255
# ```
#
# The reason for allowing strings that don't have a valid UTF-8 sequence
# is that the world is full of content that isn't properly encoded,
# and having a program raise an exception or stop because of this
# is not good. It's better if programs are more resilient, but
# show a replacement character when there's an error in incoming data.
class String
# :nodoc:
TYPE_ID = "".crystal_type_id
# :nodoc:
HEADER_SIZE = sizeof({Int32, Int32, Int32})
include Comparable(self)
macro inherited
{{ raise "Cannot inherit from String" }}
end
# Creates a `String` from the given *slice*. `Bytes` will be copied from the slice.
#
# This method is always safe to call, and the resulting string will have
# the contents and size of the slice.
#
# ```
# slice = Slice.new(4) { |i| ('a'.ord + i).to_u8 }
# String.new(slice) # => "abcd"
# ```
def self.new(slice : Bytes)
new(slice.pointer(slice.size), slice.size)
end
# Creates a new `String` from the given *bytes*, which are encoded in the given *encoding*.
#
# The *invalid* argument can be:
# * `nil`: an exception is raised on invalid byte sequences
# * `:skip`: invalid byte sequences are ignored
#
# ```
# slice = Slice.new(2, 0_u8)
# slice[0] = 186_u8
# slice[1] = 195_u8
# String.new(slice, "GB2312") # => "好"
# ```
def self.new(bytes : Bytes, encoding : String, invalid : Symbol? = nil) : String
String.build do |str|
String.encode(bytes, encoding, "UTF-8", str, invalid)
end
end
# Creates a `String` from a pointer. `Bytes` will be copied from the pointer.
#
# This method is **unsafe**: the pointer must point to data that eventually
# contains a zero byte that indicates the ends of the string. Otherwise,
# the result of this method is undefined and might cause a segmentation fault.
#
# This method is typically used in C bindings, where you get a `char*` from a
# library and the library guarantees that this pointer eventually has an
# ending zero byte.
#
# ```
# ptr = Pointer.malloc(5) { |i| i == 4 ? 0_u8 : ('a'.ord + i).to_u8 }
# String.new(ptr) # => "abcd"
# ```
def self.new(chars : UInt8*)
new(chars, LibC.strlen(chars))
end
# Creates a new `String` from a pointer, indicating its bytesize count
# and, optionally, the UTF-8 codepoints count (size). `Bytes` will be
# copied from the pointer.
#
# If the given size is zero, the amount of UTF-8 codepoints will be
# lazily computed when needed.
#
# ```
# ptr = Pointer.malloc(4) { |i| ('a'.ord + i).to_u8 }
# String.new(ptr, 2) # => "ab"
# ```
def self.new(chars : UInt8*, bytesize, size = 0)
# Avoid allocating memory for the empty string
return "" if bytesize == 0
new(bytesize) do |buffer|
buffer.copy_from(chars, bytesize)
{bytesize, size}
end
end
# Creates a new `String` by allocating a buffer (`Pointer(UInt8)`) with the given capacity, then
# yielding that buffer. The block must return a tuple with the bytesize and size
# (UTF-8 codepoints count) of the String. If the returned size is zero, the UTF-8 codepoints
# count will be lazily computed.
#
# The bytesize returned by the block must be less than or equal to the
# capacity given to this String, otherwise `ArgumentError` is raised.
#
# If you need to build a `String` where the maximum capacity is unknown, use `String#build`.
#
# ```
# str = String.new(4) do |buffer|
# buffer[0] = 'a'.ord.to_u8
# buffer[1] = 'b'.ord.to_u8
# {2, 2}
# end
# str # => "ab"
# ```
def self.new(capacity : Int)
check_capacity_in_bounds(capacity)
str = GC.malloc_atomic(capacity.to_u32 + HEADER_SIZE + 1).as(UInt8*)
buffer = str.as(String).to_unsafe
bytesize, size = yield buffer
unless 0 <= bytesize <= capacity
raise ArgumentError.new("Bytesize out of capacity bounds")
end
buffer[bytesize] = 0_u8
# Try to reclaim some memory if capacity is bigger than what was requested
if bytesize < capacity
str = str.realloc(bytesize.to_u32 + HEADER_SIZE + 1)
end
str_header = str.as({Int32, Int32, Int32}*)
str_header.value = {TYPE_ID, bytesize.to_i, size.to_i}
str.as(String)
end
# Builds a `String` by creating a `String::Builder` with the given initial capacity, yielding
# it to the block and finally getting a `String` out of it. The `String::Builder` automatically
# resizes as needed.
#
# ```
# str = String.build do |str|
# str << "hello "
# str << 1
# end
# str # => "hello 1"
# ```
def self.build(capacity = 64) : self
String::Builder.build(capacity) do |builder|
yield builder
end
end
# Returns the number of bytes in this string.
#
# ```
# "hello".bytesize # => 5
# "你好".bytesize # => 6
# ```
def bytesize
@bytesize
end
# Returns the result of interpreting leading characters in this string as an
# integer base *base* (between 2 and 36).
#
# If there is not a valid number at the start of this string,
# or if the resulting integer doesn't fit an `Int32`, an `ArgumentError` is raised.
#
# Options:
# * **whitespace**: if `true`, leading and trailing whitespaces are allowed
# * **underscore**: if `true`, underscores in numbers are allowed
# * **prefix**: if `true`, the prefixes `"0x"`, `"0"` and `"0b"` override the base
# * **strict**: if `true`, extraneous characters past the end of the number are disallowed
#
# ```
# "12345".to_i # => 12345
# "0a".to_i # raises ArgumentError
# "hello".to_i # raises ArgumentError
# "0a".to_i(16) # => 10
# "1100101".to_i(2) # => 101
# "1100101".to_i(8) # => 294977
# "1100101".to_i(10) # => 1100101
# "1100101".to_i(base: 16) # => 17826049
#
# "12_345".to_i # raises ArgumentError
# "12_345".to_i(underscore: true) # => 12345
#
# " 12345 ".to_i # => 12345
# " 12345 ".to_i(whitespace: false) # raises ArgumentError
#
# "0x123abc".to_i # raises ArgumentError
# "0x123abc".to_i(prefix: true) # => 1194684
#
# "99 red balloons".to_i # raises ArgumentError
# "99 red balloons".to_i(strict: false) # => 99
# ```
def to_i(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true)
to_i32(base, whitespace, underscore, prefix, strict)
end
# Same as `#to_i`, but returns `nil` if there is not a valid number at the start
# of this string, or if the resulting integer doesn't fit an `Int32`.
#
# ```
# "12345".to_i? # => 12345
# "99 red balloons".to_i? # => nil
# "0a".to_i?(strict: false) # => 0
# "hello".to_i? # => nil
# ```
def to_i?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true)
to_i32?(base, whitespace, underscore, prefix, strict)
end
# Same as `#to_i`, but returns the block's value if there is not a valid number at the start
# of this string, or if the resulting integer doesn't fit an `Int32`.
#
# ```
# "12345".to_i { 0 } # => 12345
# "hello".to_i { 0 } # => 0
# ```
def to_i(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
to_i32(base, whitespace, underscore, prefix, strict) { yield }
end
# Same as `#to_i` but returns an `Int8`.
def to_i8(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int8
to_i8(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid Int8: #{self}") }
end
# Same as `#to_i` but returns an `Int8` or `nil`.
def to_i8?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int8?
to_i8(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `Int8` or the block's value.
def to_i8(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ i8, 127, 128
end
# Same as `#to_i` but returns an `UInt8`.
def to_u8(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt8
to_u8(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid UInt8: #{self}") }
end
# Same as `#to_i` but returns an `UInt8` or `nil`.
def to_u8?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt8?
to_u8(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `UInt8` or the block's value.
def to_u8(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ u8, 255
end
# Same as `#to_i` but returns an `Int16`.
def to_i16(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int16
to_i16(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid Int16: #{self}") }
end
# Same as `#to_i` but returns an `Int16` or `nil`.
def to_i16?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int16?
to_i16(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `Int16` or the block's value.
def to_i16(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ i16, 32767, 32768
end
# Same as `#to_i` but returns an `UInt16`.
def to_u16(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt16
to_u16(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid UInt16: #{self}") }
end
# Same as `#to_i` but returns an `UInt16` or `nil`.
def to_u16?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt16?
to_u16(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `UInt16` or the block's value.
def to_u16(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ u16, 65535
end
# Same as `#to_i`.
def to_i32(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int32
to_i32(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid Int32: #{self}") }
end
# Same as `#to_i`.
def to_i32?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int32?
to_i32(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i`.
def to_i32(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ i32, 2147483647, 2147483648
end
# Same as `#to_i` but returns an `UInt32`.
def to_u32(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt32
to_u32(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid UInt32: #{self}") }
end
# Same as `#to_i` but returns an `UInt32` or `nil`.
def to_u32?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt32?
to_u32(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `UInt32` or the block's value.
def to_u32(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ u32, 4294967295
end
# Same as `#to_i` but returns an `Int64`.
def to_i64(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int64
to_i64(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid Int64: #{self}") }
end
# Same as `#to_i` but returns an `Int64` or `nil`.
def to_i64?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : Int64?
to_i64(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `Int64` or the block's value.
def to_i64(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ i64, 9223372036854775807, 9223372036854775808
end
# Same as `#to_i` but returns an `UInt64`.
def to_u64(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt64
to_u64(base, whitespace, underscore, prefix, strict) { raise ArgumentError.new("Invalid UInt64: #{self}") }
end
# Same as `#to_i` but returns an `UInt64` or `nil`.
def to_u64?(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true) : UInt64?
to_u64(base, whitespace, underscore, prefix, strict) { nil }
end
# Same as `#to_i` but returns an `UInt64` or the block's value.
def to_u64(base : Int = 10, whitespace = true, underscore = false, prefix = false, strict = true, &block)
gen_to_ u64
end
# :nodoc:
CHAR_TO_DIGIT = begin
table = StaticArray(Int8, 256).new(-1_i8)
10_i8.times do |i|
table.to_unsafe[48 + i] = i
end
26_i8.times do |i|
table.to_unsafe[65 + i] = i + 10
table.to_unsafe[97 + i] = i + 10
end
table
end
# :nodoc:
CHAR_TO_DIGIT62 = begin
table = CHAR_TO_DIGIT.clone
26_i8.times do |i|
table.to_unsafe[65 + i] = i + 36
end
table
end
# :nodoc:
record ToU64Info,
value : UInt64,
negative : Bool,
invalid : Bool
private macro gen_to_(method, max_positive = nil, max_negative = nil)
info = to_u64_info(base, whitespace, underscore, prefix, strict)
return yield if info.invalid
if info.negative
{% if max_negative %}
return yield if info.value > {{max_negative}}
-info.value.to_{{method}}
{% else %}
return yield
{% end %}
else
{% if max_positive %}
return yield if info.value > {{max_positive}}
{% end %}
info.value.to_{{method}}
end
end
private def to_u64_info(base, whitespace, underscore, prefix, strict)
raise ArgumentError.new("Invalid base #{base}") unless 2 <= base <= 36 || base == 62
ptr = to_unsafe
# Skip leading whitespace
if whitespace
while ptr.value.unsafe_chr.ascii_whitespace?
ptr += 1
end
end
negative = false
found_digit = false
mul_overflow = ~0_u64 / base
# Check + and -
case ptr.value.unsafe_chr
when '+'
ptr += 1
when '-'
negative = true
ptr += 1
end
# Check leading zero
if ptr.value.unsafe_chr == '0'
ptr += 1
if prefix
case ptr.value.unsafe_chr
when 'b'
base = 2
ptr += 1
when 'x'
base = 16
ptr += 1
else
base = 8
end
found_digit = false
else
found_digit = true
end
end
value = 0_u64
last_is_underscore = true
invalid = false
digits = (base == 62 ? CHAR_TO_DIGIT62 : CHAR_TO_DIGIT).to_unsafe
while ptr.value != 0
if ptr.value.unsafe_chr == '_' && underscore
break if last_is_underscore
last_is_underscore = true
ptr += 1
next
end
last_is_underscore = false
digit = digits[ptr.value]
if digit == -1 || digit >= base
break
end
if value > mul_overflow
invalid = true
break
end
value *= base
old = value
value += digit
if value < old
invalid = true
break
end
found_digit = true
ptr += 1
end
if found_digit
unless ptr.value == 0
if whitespace
while ptr.value.unsafe_chr.ascii_whitespace?
ptr += 1
end
end
if strict && ptr.value != 0
invalid = true
end
end
else
invalid = true
end
ToU64Info.new value, negative, invalid
end
# Returns the result of interpreting characters in this string as a floating point number (`Float64`).
# This method raises an exception if the string is not a valid float representation.
#
# Options:
# * **whitespace**: if `true`, leading and trailing whitespaces are allowed
# * **strict**: if `true`, extraneous characters past the end of the number are disallowed
#
# ```
# "123.45e1".to_f # => 1234.5
# "45.67 degrees".to_f # raises ArgumentError
# "thx1138".to_f(strict: false) # raises ArgumentError
# " 1.2".to_f(whitespace: false) # raises ArgumentError
# "1.2foo".to_f(strict: false) # => 1.2
# ```
def to_f(whitespace = true, strict = true)
to_f64(whitespace: whitespace, strict: strict)
end
# Returns the result of interpreting characters in this string as a floating point number (`Float64`).
# This method returns `nil` if the string is not a valid float representation.
#
# Options:
# * **whitespace**: if `true`, leading and trailing whitespaces are allowed
# * **strict**: if `true`, extraneous characters past the end of the number are disallowed
#
# ```
# "123.45e1".to_f? # => 1234.5
# "45.67 degrees".to_f? # => nil
# "thx1138".to_f? # => nil
# " 1.2".to_f?(whitespace: false) # => nil
# "1.2foo".to_f?(strict: false) # => 1.2
# ```
def to_f?(whitespace = true, strict = true)
to_f64?(whitespace: whitespace, strict: strict)
end
# Same as `#to_f` but returns a Float32.
def to_f32(whitespace = true, strict = true)
to_f32?(whitespace: whitespace, strict: strict) || raise ArgumentError.new("Invalid Float32: #{self}")
end
# Same as `#to_f?` but returns a Float32.
def to_f32?(whitespace = true, strict = true)
to_f_impl(whitespace: whitespace, strict: strict) do
v = LibC.strtof self, out endptr
{v, endptr}
end
end
# Same as `#to_f`.
def to_f64(whitespace = true, strict = true)
to_f64?(whitespace: whitespace, strict: strict) || raise ArgumentError.new("Invalid Float64: #{self}")
end
# Same as `#to_f?`.
def to_f64?(whitespace = true, strict = true)
to_f_impl(whitespace: whitespace, strict: strict) do
v = LibC.strtod self, out endptr
{v, endptr}
end
end
private def to_f_impl(whitespace = true, strict = true)
return unless whitespace || '0' <= self[0] <= '9' || self[0] == '-' || self[0] == '+'
v, endptr = yield
string_end = to_unsafe + bytesize
# blank string
return if endptr == to_unsafe
if strict
if whitespace
while endptr < string_end && endptr.value.chr.ascii_whitespace?
endptr += 1
end
end
# reached the end of the string
v if endptr == string_end
else
ptr = to_unsafe
if whitespace
while ptr < string_end && ptr.value.chr.ascii_whitespace?
ptr += 1
end
end
# consumed some bytes
v if endptr > ptr
end
end
# Returns the `Char` at the given *index*, or raises `IndexError` if out of bounds.
#
# Negative indices can be used to start counting from the end of the string.
#
# ```
# "hello"[0] # 'h'
# "hello"[1] # 'e'
# "hello"[-1] # 'o'
# "hello"[-2] # 'l'
# "hello"[5] # raises IndexError
# ```
def [](index : Int)
at(index) { raise IndexError.new }
end
# Returns a substring by using a Range's *begin* and *end*
# as character indices. Indices can be negative to start
# counting from the end of the string.
#
# Raises `IndexError` if the range's start is not in range.
#
# ```
# "hello"[0..2] # "hel"
# "hello"[0...2] # "he"
# "hello"[1..-1] # "ello"
# "hello"[1...-1] # "ell"
# ```
def [](range : Range(Int, Int))
self[*Indexable.range_to_index_and_count(range, size)]
end
# Returns a substring starting from the *start* character
# of size *count*.
#
# The *start* argument can be negative to start counting
# from the end of the string.
#
# Raises `IndexError` if *start* isn't in range.
#
# Raises `ArgumentError` if *count* is negative.
def [](start : Int, count : Int)
if ascii_only?
return byte_slice(start, count)
end
start += size if start < 0
start_pos = nil
end_pos = nil
reader = Char::Reader.new(self)
i = 0
reader.each do |char|
if i == start
start_pos = reader.pos
elsif count >= 0 && i == start + count
end_pos = reader.pos
i += 1
break
end
i += 1
end
end_pos ||= reader.pos
if start_pos
raise ArgumentError.new "Negative count" if count < 0
return "" if count == 0
count = end_pos - start_pos
return self if count == bytesize
String.new(count) do |buffer|
buffer.copy_from(to_unsafe + start_pos, count)
{count, 0}
end
elsif start == i
if count >= 0
return ""
else
raise ArgumentError.new "Negative count"
end
else
raise IndexError.new
end
end
def []?(index : Int)
at(index) { nil }
end
def []?(str : String | Char)
includes?(str) ? str : nil
end
def []?(regex : Regex)
self[regex, 0]?
end
def []?(regex : Regex, group)
match = match(regex)
match[group]? if match
end
def [](str : String | Char)
self[str]?.not_nil!
end
def [](regex : Regex)
self[regex]?.not_nil!
end
def [](regex : Regex, group)
self[regex, group]?.not_nil!
end
def at(index : Int)
at(index) { raise IndexError.new }
end
def at(index : Int)
if ascii_only?
byte = byte_at?(index)
if byte
return byte < 0x80 ? byte.unsafe_chr : Char::REPLACEMENT
else
return yield
end
end
index += size if index < 0
byte_index = char_index_to_byte_index(index)
if byte_index && byte_index < @bytesize
reader = Char::Reader.new(self, pos: byte_index)
return reader.current_char
else
yield
end
end
def byte_slice(start : Int, count : Int)
start += bytesize if start < 0
single_byte_optimizable = ascii_only?
if 0 <= start < bytesize
raise ArgumentError.new "Negative count" if count < 0
count = bytesize - start if start + count > bytesize
return "" if count == 0
return self if count == bytesize
String.new(count) do |buffer|
buffer.copy_from(to_unsafe + start, count)
slice_size = single_byte_optimizable ? count : 0
{count, slice_size}
end
elsif start == bytesize
if count >= 0
return ""
else
raise ArgumentError.new "Negative count"
end
else
raise IndexError.new
end
end
def byte_slice(start : Int)
byte_slice start, bytesize - start
end
def codepoint_at(index)
char_at(index).ord
end
def char_at(index)
self[index]
end
def byte_at(index)
byte_at(index) { raise IndexError.new }
end
def byte_at?(index)
byte_at(index) { nil }
end
def byte_at(index)
index += bytesize if index < 0
if 0 <= index < bytesize
to_unsafe[index]
else
yield
end
end
def unsafe_byte_at(index)
to_unsafe[index]
end
# Returns a new `String` with each uppercase letter replaced with its lowercase
# counterpart.
#
# ```
# "hEllO".downcase # => "hello"
# ```
def downcase(options = Unicode::CaseOptions::None)
return self if empty?
if ascii_only? && (options.none? || options.ascii?)
String.new(bytesize) do |buffer|
bytesize.times do |i|
buffer[i] = to_unsafe[i].unsafe_chr.downcase.ord.to_u8
end
{@bytesize, @length}
end
else
String.build(bytesize) do |io|
each_char do |char|
char.downcase(options) do |res|
io << res
end
end
end
end
end
# Returns a new `String` with each lowercase letter replaced with its uppercase
# counterpart.
#
# ```
# "hEllO".upcase # => "HELLO"
# ```
def upcase(options = Unicode::CaseOptions::None)
return self if empty?
if ascii_only? && (options.none? || options.ascii?)
String.new(bytesize) do |buffer|
bytesize.times do |i|
buffer[i] = to_unsafe[i].unsafe_chr.upcase.ord.to_u8
end
{@bytesize, @length}
end
else
String.build(bytesize) do |io|
each_char do |char|
char.upcase(options) do |res|
io << res
end
end
end
end
end
# Returns a new `String` with the first letter converted to uppercase and every
# subsequent letter converted to lowercase.
#
# ```
# "hEllO".capitalize # => "Hello"
# ```
def capitalize(options = Unicode::CaseOptions::None)
return self if empty?
if ascii_only? && (options.none? || options.ascii?)
String.new(bytesize) do |buffer|
bytesize.times do |i|
if i == 0
buffer[i] = to_unsafe[i].unsafe_chr.upcase.ord.to_u8
else
buffer[i] = to_unsafe[i].unsafe_chr.downcase.ord.to_u8
end
end
{@bytesize, @length}
end
else
String.build(bytesize) do |io|
each_char_with_index do |char, i|
if i == 0
char.upcase(options) { |c| io << c }
else
char.downcase(options) { |c| io << c }
end
end
end
end
end
# Returns a new `String` with the last carriage return removed (that is, it
# will remove \n, \r, and \r\n).
#
# ```
# "string\r\n".chomp # => "string"
# "string\n\r".chomp # => "string\n"
# "string\n".chomp # => "string"