Skip to content

Commit 622593e

Browse files
committed
Refactor StringIO#initialize and remove code duplication
1 parent 740eddb commit 622593e

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

lib/truffle/stringio.rb

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,14 @@ def initialize(string = nil, mode = nil, **options)
166166
mode_from_string(string.frozen? ? 'r' : 'r+')
167167
end
168168

169+
if @writable && @__data__.string.frozen?
170+
raise Errno::EACCES, 'Permission denied'
171+
end
172+
173+
if @truncate
174+
@__data__.string.replace(''.force_encoding(@__data__.string.encoding))
175+
end
176+
169177
self
170178
end
171179

@@ -672,43 +680,37 @@ def yaml_initialize(type, val)
672680
end
673681

674682
private def mode_from_string(mode)
675-
@append = truncate = false
683+
@append = @truncate = false
676684

677685
if mode[0] == ?r
678686
@readable = true
679687
@writable = mode[-1] == ?+ ? true : false
680688
end
681689

682690
if mode[0] == ?w
683-
@writable = truncate = true
691+
@writable = @truncate = true
684692
@readable = mode[-1] == ?+ ? true : false
685693
end
686694

687695
if mode[0] == ?a
688696
@append = @writable = true
689697
@readable = mode[-1] == ?+ ? true : false
690698
end
691-
692-
d = @__data__ # no sync, only called from initialize
693-
raise Errno::EACCES, 'Permission denied' if @writable && d.string.frozen?
694-
d.string.replace(''.force_encoding(d.string.encoding)) if truncate
695699
end
696700

697701
private def mode_from_integer(mode)
698-
@readable = @writable = @append = false
699-
d = @__data__ # no sync, only called from initialize
702+
@readable = @writable = @append = @truncate = false
700703

701704
if mode == 0 or mode & IO::RDWR != 0
702705
@readable = true
703706
end
704707

705708
if mode & (IO::WRONLY | IO::RDWR) != 0
706-
raise Errno::EACCES, 'Permission denied' if d.string.frozen?
707709
@writable = true
708710
end
709711

710712
@append = true if (mode & IO::APPEND) != 0
711-
d.string.replace(''.force_encoding(d.string.encoding)) if (mode & IO::TRUNC) != 0
713+
@truncate = true if (mode & IO::TRUNC) != 0
712714
end
713715

714716
private def getline(arg_error, sep, limit, chomp = false)

0 commit comments

Comments
 (0)