From: Michael Selig Date: 2009-02-25T07:41:57+09:00 Subject: [ruby-core:22431] Re: [Feature #908] Should be an easy way of reading N characters from am I/O stream 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. Mike.