From: Michal Suchanek Date: 2009-02-25T22:53:05+09:00 Subject: [ruby-core:22467] Re: [Feature #908] Should be an easy way of reading N characters from am I/O stream 2009/2/24 Michael Selig : > Hi Michal, > > On Wed, 25 Feb 2009 00:20:52 +1100, Michal Suchanek > wrote: > >>>> BTW the same goes for "reading N bytes up to a character boundary" >>>> unless you are willing to accept that you might read nothing even if >>>> data is available because the character did not fit into N bytes, even >>>> for a large N. >>> >>> The current behaviour of IO#gets "limit" parameter is "read N bytes but >>> round *UP* to the next character boundary". Therefore you may get more >>> bytes >>> returned than requested. As long as "limit" is 1 or more, you should >>> always >>> read something unless the file is at EOF, right? >>> >>> However I still do not understand why reading N characters (instead of >>> the >>> current "limit" implementation) might be described as being "insecure". >>> Can >>> someone please explain it? It is clear that the string returned may be >>> larger than N bytes long, but why is that "insecure"? >>> >> >> The current gets is not any more secure since it rounds up. If you >> found a bug in an encoding that could give you an infinite character >> either version would break. > > Actually rounding *up* to the character boundary *is* more secure. You > pointed it out yourself! If it rounded down, gets could return an empty > string, and code like: > > �� �� �� ��while s = f.gets(1) ..... > > would then go into an infinite loop. > Then either way is insecure because you can get an infinite loop with zero read (unless zero read returned nil or threw an exception) and potentially infinite memory requirement with a broken encoding and rounding up. Thanks Michal