Skip to content

Commit 6562623

Browse files
Add note about Char::Reader's value semantics (#14008)
Co-authored-by: Johannes Müller <[email protected]>
1 parent 60c0334 commit 6562623

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/char/reader.cr

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,32 @@ struct Char
77
# Successive calls to `next_char` return the next chars in the string,
88
# advancing `pos`.
99
#
10-
# Note that the null character `'\0'` will be returned in `current_char` when
10+
# NOTE: The null character `'\0'` will be returned in `current_char` when
1111
# the end is reached (as well as when the string is empty). Thus, `has_next?`
1212
# will return `false` only when `pos` is equal to the string's bytesize, in which
1313
# case `current_char` will always be `'\0'`.
14+
#
15+
# NOTE: For performance reasons, `Char::Reader` has value semantics, so care
16+
# must be taken when a reader is declared as a local variable and passed to
17+
# another method:
18+
#
19+
# ```
20+
# def lstrip(reader)
21+
# until reader.current_char.whitespace?
22+
# reader.next_char
23+
# end
24+
# reader
25+
# end
26+
#
27+
# # caller's internal state is untouched
28+
# reader = Char::Reader.new(" abc")
29+
# lstrip(reader)
30+
# reader.current_char # => ' '
31+
#
32+
# # to modify caller's internal state, the method must return a new reader
33+
# reader = lstrip(reader)
34+
# reader.current_char # => 'a'
35+
# ```
1436
struct Reader
1537
include Enumerable(Char)
1638

0 commit comments

Comments
 (0)