This repository has been archived by the owner on Jan 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
string.rb
763 lines (617 loc) · 16.3 KB
/
string.rb
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
# frozen_string_literal: true
class Encoding
class CompatibilityError < StandardError; end
def initialize(name)
@name = name
end
ASCII_8BIT = new('ASCII-8BIT')
BINARY = ASCII_8BIT
US_ASCII = new('US-ASCII')
ASCII = US_ASCII
EUC_JP = new('EUC-JP')
ISO_8859_1 = new('ISO-8859-1')
Shift_JIS = new('Shift_JIS')
SHIFT_JIS = Shift_JIS
UTF_8 = new('UTF-8')
def self.default_external
UTF_8
end
def self.default_external=(_enc)
UTF_8
end
def self.default_internal
UTF_8
end
def self.default_internal=(_enc)
UTF_8
end
def self.find(string)
new(string)
end
attr_reader :name
def ascii_compatible?
true
end
def dummy?
true
end
def inspect
"#<#{self.class}:#{@name}>"
end
def names
[name]
end
def replicate(name)
new(name)
end
def to_s
name
end
end
class String
def self.try_convert(obj = nil)
raise ArgumentError if obj.nil?
return obj if obj.is_a?(String)
str = obj.to_str
return nil if str.nil?
raise TypeError unless str.is_a?(String)
str
rescue NoMethodError
nil
end
def +@
return dup if frozen?
self
end
def -@
return self if frozen?
dup.freeze
end
def <<(obj)
raise TypeError if obj.nil?
obj = obj.chr if obj.is_a?(Integer)
self[0..-1] = "#{self}#{obj}"
self
end
alias concat <<
def =~(other)
return other.match(self)&.begin(0) if other.is_a?(Regexp)
raise TypeError, "type mismatch: #{other.class} given" if other.is_a?(String)
return other =~ self if other.respond_to?(:=~)
nil
end
alias __old_element_reference []
def [](*args)
raise ArgumentError, 'wrong number of arguments (given 0, expected 1..2)' if args.empty? || args.length > 2
element =
if (regexp = args[0]).is_a?(Regexp)
capture = args.fetch(1, 0)
capture =
begin
capture.to_int
rescue NoMethodError
capture
end
regexp.match(self)&.[](capture)
elsif args.length == 1
index, = *args
index =
begin
index.to_int
rescue NoMethodError
index
end
__old_element_reference(index)
else
index, length = *args
index =
begin
index.to_int
rescue NoMethodError
index
end
length =
begin
length.to_int
rescue NoMethodError
length
end
__old_element_reference(index, length)
end
return nil if element.nil?
if self.class == String
element
else
self.class.new(element)
end
end
alias slice []
alias __old_element_assignment []=
def []=(*args)
return __old_element_assignment(*args) unless args[0].is_a?(Regexp) # rubocop:disable Lint/ReturnInVoidContext
*args, replace = *args
regexp = args[0]
capture = args.fetch(1, 0)
match = regexp.match(self)
return if match.nil?
self[match.begin(capture)...match.end(capture)] = replace
end
def ascii_only?
bytes.length == length
end
def b
# mruby has no Encoding, so there is no difference between an ASCII_8BIT
# String and a UTF-8 String.
dup
end
def byteslice(*args)
if args[0].is_a?(Integer)
position, len = *args
len = 1 if len.nil?
position = length + position if position.negative?
slice = bytes[position...position + len]
slice.pack('c*')
elsif args.length == 1 && args[0].is_a?(Range)
range, = *args
position = range.begin
len = range.size
slice = bytes[position...position + len]
slice.pack('c*')
else
raise ArgumentError
end
end
def casecmp(str)
return nil unless String.try_convert(str)
downcase <=> str.downcase
end
def casecmp?(str)
casecmp(str)&.zero? == true
end
def center(width, padstr = ' ')
return self if length >= width
left_pad = (width - length) / 2
left_pad = (padstr * left_pad)[0...left_pad]
right_pad = (width - length) / 2 + (width - length) % 2
right_pad = (padstr * right_pad)[0...right_pad]
"#{left_pad}#{self}#{right_pad}"
end
def chars
if block_given?
split('').each do |char|
yield char
end
self
else
split('')
end
end
def chr
dup[0]
end
def clear
self[0..-1] = ''
end
def codepoints
each_codepoint.to_a
end
def count
raise NotImplementedError
end
def crypt(_salt)
raise NotImplementedError
end
def delete(*args)
args.inject(self) { |string, pattern| string.tr(pattern, '') }
end
def delete!(*args)
replaced = delete(*args)
self[0..-1] = replaced unless self == replaced
end
def delete_prefix(prefix)
self[0...prefix.length] = '' if start_with?(prefix)
self
end
def delete_prefix!(prefix)
replaced = delete_prefix(prefix)
self[0..-1] = replaced unless self == replaced
end
def delete_suffix(suffix)
self[-suffix.length..-1] = '' if end_with?(suffix)
self
end
def delete_suffix!(prefix)
replaced = delete_suffix(prefix)
self[0..-1] = replaced unless self == replaced
end
def dump
raise NotImplementedError
end
def each_codepoint
return to_enum(:each_codepoint) unless block_given?
split('').each do |c|
yield c.ord
end
end
def each_grapheme_cluster
raise NotImplementedError
end
def each_line(separator = $/, getline_args = nil) # rubocop:disable Style/SpecialGlobalVars
return to_enum(:each_line, separator, getline_args) unless block_given?
if separator.nil?
yield self
return self
end
raise TypeError if separator.is_a?(Symbol)
raise TypeError if (separator = String.try_convert(separator)).nil?
paragraph_mode = false
if separator.empty?
paragraph_mode = true
separator = "\n\n"
end
start = 0
string = dup
self_len = length
sep_len = separator.length
should_yield_subclass_instances = self.class != String
while (pointer = string.index(separator, start))
pointer += sep_len
pointer += 1 while paragraph_mode && string[pointer] == "\n"
if should_yield_subclass_instances
yield self.class.new(string[start, pointer - start])
else
yield string[start, pointer - start]
end
start = pointer
end
return self if start == self_len
if should_yield_subclass_instances
yield self.class.new(string[start, self_len - start])
else
yield string[start, self_len - start]
end
self
end
def encode(*_args)
# mruby does not support encoding, all Strings are UTF-8. This method is a
# NOOP and is here for compatibility.
dup
end
def encode!(*_args)
# mruby does not support encoding, all Strings are UTF-8. This method is a
# NOOP and is here for compatibility.
self
end
def encoding
# mruby does not support encoding, all Strings are UTF-8. This method is a
# stub and is here for compatibility.
Encoding::UTF_8
end
def end_with?(*suffixes)
suffixes.each do |suffix|
return true if self[-suffix.length..-1] == suffix
end
false
end
def force_encoding(*_args)
# mruby does not support encoding, all Strings are UTF-8. This method is a
# NOOP and is here for compatibility.
self
end
def getbyte(index)
bytes[index]
end
def grapheme_clusters
each_grapheme_cluster.to_a
end
# TODO: Support backrefs
#
# "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>"
# "hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}"
def gsub(pattern, replacement = nil)
return to_enum(:gsub, pattern) if replacement.nil? && !block_given?
replace =
if replacement.nil?
->(old) { (yield old).to_s }
elsif replacement.is_a?(Hash)
->(old) { replacement[old].to_s }
else
->(_old) { replacement.to_s }
end
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
match = pattern.match(self)
return dup if match.nil?
buf = ''
remainder = dup
until match.nil? || remainder.empty?
buf << remainder[0..match.begin(0) - 1] if match.begin(0).positive?
buf << replace.call(match[0])
remainder = remainder[match.end(0)..-1]
remainder = remainder[1..-1] if match.begin(0) == match.end(0)
match = pattern.match(remainder)
end
buf << remainder
end
def gsub!(pattern, replacement = nil, &blk)
replaced = gsub(pattern, replacement, &blk)
self[0..-1] = replaced unless self == replaced
self
end
def hex
raise NotImplementedError
end
def insert(index, other_str)
return self << other_str if index == -1
index += 1 if index.negative?
self[index, 0] = other_str
self
end
def lines(*args)
each_line(*args).to_a
end
def ljust(integer, padstr = ' ')
raise ArgumentError, 'zero width padding' if padstr == ''
return self if integer <= length
pad_repetitions = (integer / padstr.length).ceil
padding = (padstr * pad_repetitions)[0...(integer - length)]
"#{self}#{padding}"
end
def lstrip
strip_pointer = 0
string_end = length - 1
strip_pointer += 1 while strip_pointer <= string_end && " \f\n\r\t\v".include?(self[strip_pointer])
return '' if string_end.zero?
dup[strip_pointer..string_end]
end
def lstrip!
replaced = lstrip
self[0..-1] = replaced unless self == replaced
end
def match(pattern, pos = 0)
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
pattern.match(self[pos..-1])
end
def match?(pattern, pos = 0)
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
# TODO: Don't set $~ and other Regexp globals
pattern.match?(self[pos..-1])
end
def next
raise NotImplementedError
end
alias succ next
def next!
raise NotImplementedError
end
alias succ! next!
def oct
raise NotImplementedError
end
def partition(pattern)
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
match = pattern.match(self)
[match.pre_match, match[0], match.post_match]
end
def prepend(*args)
insert(0, args.join(''))
end
def rjust(integer, padstr = ' ')
raise ArgumentError, 'zero width padding' if padstr == ''
return self if integer <= length
pad_repetitions = (integer / padstr.length).ceil
padding = (padstr * pad_repetitions)[0...(integer - length)]
"#{padding}#{self}"
end
def rpartition(pattern)
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
_ = pattern
raise NotImplementedError
end
def rstrip
strip_pointer = length - 1
string_start = 0
strip_pointer -= 1 while strip_pointer >= string_start && " \f\n\r\t\v".include?(self[strip_pointer])
return '' if strip_pointer.zero?
dup[string_start..strip_pointer]
end
def rstrip!
replaced = rstrip
self[0..-1] = replaced unless self == replaced
end
def scrub
# TODO: This is a stub. Implement scrub correctly.
self
end
def scrub!
# TODO: This is a stub. Implement scrub! correctly.
self
end
def setbyte(index, integer)
slice = bytes
slice[index] = integer
self[0..-1] = slice.pack('c*')
end
def split(pattern, limit = nil)
parts = []
return parts if self == ''
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
if pattern.source == ''
length.times do |i|
yield self[i].dup if block_given?
parts << self[i].dup
end
return parts
end
remainder = dup
match = pattern.match(remainder)
if limit&.positive?
until match.nil? || remainder.nil? || parts.length >= limit - 1
parts << remainder[0...match.begin(0)]
remainder = remainder[match.end(0)..-1]
remainder = remainder[1..-1] if match.begin(0) == match.end(0)
match = nil
match = pattern.match(remainder) unless remainder.nil?
end
parts << remainder unless remainder.nil?
else
until match.nil? || remainder.nil?
parts << remainder[0...match.begin(0)]
remainder = remainder[match.end(0)..-1]
remainder = remainder[1..-1] if match.begin(0) == match.end(0)
match = nil
match = pattern.match(remainder) unless remainder.nil?
end
parts << remainder unless remainder.nil?
if limit&.negative? && -limit > parts.length
(-limit - parts.length).times do
parts << ''
end
end
end
parts.each { |part| yield part } if block_given?
parts
end
def squeeze(*_args)
raise NotImplementedError
end
def start_with?(*prefixes)
prefixes.each do |prefix|
return true if self[0...prefix.length] == prefix
end
false
end
def strip
result = lstrip
result = self if result.nil?
result.rstrip
end
def strip!
replaced = strip
self[0..-1] = replaced unless self == replaced
end
def sub(pattern, replacement = nil)
return to_enum(:sub, pattern) if replacement.nil? && !block_given?
replace =
if replacement.nil?
->(old) { (yield old).to_s }
elsif replacement.is_a?(Hash)
->(old) { replacement[old].to_s }
else
->(_old) { replacement.to_s }
end
pattern = Regexp.compile(Regexp.escape(pattern)) if pattern.is_a?(String)
match = pattern.match(self)
return dup if match.nil?
buf = ''
remainder = dup
buf << remainder[0..match.begin(0) - 1] if match.begin(0).positive?
buf << replace.call(match[0])
remainder = remainder[match.end(0)..-1]
remainder = remainder[1..-1] if match.begin(0) == match.end(0)
buf << remainder
buf
end
def sub!(pattern, replacement = nil, &blk)
replaced = sub(pattern, replacement, &blk)
self[0..-1] = replaced unless self == replaced
end
def sum
raise NotImplementedError
end
def swapcase(*_args)
raise NotImplementedError
end
def swapcase!(*_args)
raise NotImplementedError
end
def to_c
raise NotImplementedError
end
def to_r
raise NotImplementedError
end
def to_str
dup
end
def tr(from_str, to_str)
# TODO: Support character ranges c1-c2
# TODO: Support backslash escapes
to_str = to_str.rjust(from_str.length, to_str[-1]) if to_str.length.positive?
gsub(Regexp.compile("[#{from_str}]")) do |char|
to_str[from_str.index(char)] || ''
end
end
def tr!(from_str, to_str)
raise 'frozen string' if frozen?
replaced = tr(from_str, to_str)
self[0..-1] = replaced unless self == replaced
end
def tr_s(_from_str, _to_str)
# TODO: Support character ranges c1-c2
# TODO: Support backslash escapes
raise NotImplementedError
end
def tr_s!(_from_str, _to_str)
raise 'frozen string' if frozen?
# TODO: Support character ranges c1-c2
# TODO: Support backslash escapes
raise NotImplementedError
end
def undump
raise NotImplementedError
end
def unicode_normalize(_form = :nfc)
raise NotImplementedError
end
def unicode_normalize!(_form = :nfc)
raise NotImplementedError
end
def unicode_normalized?(_form = :nfc)
raise NotImplementedError
end
def upto(max, exclusive = false, &block)
return to_enum(:upto, max, exclusive) unless block
raise TypeError, "no implicit conversion of #{max.class} into String" unless max.is_a?(String)
len = length
maxlen = max.length
# single character
if len == 1 && maxlen == 1
c = ord
e = max.ord
while c <= e
break if exclusive && c == e
yield c.chr
c += 1
end
return self
end
# both edges are all digits
bi = to_i(10)
ei = max.to_i(10)
if (bi.positive? || bi == '0' * len) && (ei.positive? || ei == '0' * maxlen)
while bi <= ei
break if exclusive && bi == ei
s = bi.to_s
s = s.rjust(len, '0') if s.length < len
yield s
bi += 1
end
return self
end
bs = self
loop do
n = (bs <=> max)
break if n.positive?
break if exclusive && n.zero?
yield bs
break if n.zero?
bs = bs.succ
end
self
end
def valid_encoding?
# mruby does not support encoding, all Strings are UTF-8. This method is a
# NOOP and is here for compatibility.
true
end
end