Skip to content

Commit 5c05dab

Browse files
authored
Simplify String#byte_slice(Int) and String#byte_slice?(Int) (#16235)
Removes duplicate bounds checking, it's already done in `Indexable.normalize_start_and_count`
1 parent f9f6d0e commit 5c05dab

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

src/string.cr

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,9 +1173,8 @@ class String
11731173
# ```
11741174
# "hello".byte_slice(0, 2) # => "he"
11751175
# "hello".byte_slice(0, 100) # => "hello"
1176-
# "hello".byte_slice(-2, 3) # => "he"
1177-
# "hello".byte_slice(-2, 5) # => "he"
1178-
# "hello".byte_slice(-2, 5) # => "he"
1176+
# "hello".byte_slice(-2, 3) # => "lo"
1177+
# "hello".byte_slice(-2, 5) # => "lo"
11791178
# "¥hello".byte_slice(0, 2) # => "¥"
11801179
# "¥hello".byte_slice(2, 2) # => "he"
11811180
# "¥hello".byte_slice(0, 1) # => "\xC2" (invalid UTF-8 character)
@@ -1277,9 +1276,7 @@ class String
12771276
# "hello".byte_slice(-6) # raises IndexError
12781277
# ```
12791278
def byte_slice(start : Int) : String
1280-
count = bytesize - start
1281-
raise IndexError.new if start > 0 && count < 0
1282-
byte_slice start, count
1279+
byte_slice start, bytesize
12831280
end
12841281

12851282
# Returns a substring starting from the *start* byte.
@@ -1304,9 +1301,7 @@ class String
13041301
# "hello".byte_slice?(-6) # => nil
13051302
# ```
13061303
def byte_slice?(start : Int) : String?
1307-
count = bytesize - start
1308-
return nil if start > 0 && count < 0
1309-
byte_slice? start, count
1304+
byte_slice? start, bytesize
13101305
end
13111306

13121307
# Returns the codepoint of the character at the given *index*.

0 commit comments

Comments
 (0)