2 // System.IO.StringReader
4 // Author: Marcin Szczepanski (marcins@zipworld.com.au)
12 public class StringReader : TextReader {
14 private string source;
15 private char[] sourceChars;
18 private int sourceLength;
20 public StringReader( string s ) {
23 sourceLength = s.Length;
24 sourceChars = s.ToCharArray();
27 public override void Close() {
31 protected override void Dispose( bool disposing ) {
35 public override int Peek() {
36 if( nextChar >= sourceLength ) {
39 return (int)source[ nextChar ];
43 public override int Read() {
44 if( nextChar >= sourceLength ) {
47 return (int)source[ nextChar++ ];
52 // The method will read up to count characters from the StringReader
53 // into the buffer character array starting at position index. Returns
54 // the actual number of characters read, or zero if the end of the string
55 // has been reached and no characters are read.
57 public override int Read( char[] buffer, int index, int count ) {
59 if( buffer == null ) {
60 throw new ArgumentNullException();
61 } else if( buffer.Length - index < count ) {
62 throw new ArgumentException();
63 } else if( index < 0 || count < 0 ) {
64 throw new ArgumentOutOfRangeException();
69 if( nextChar + count > sourceLength ) {
70 charsToRead = sourceLength - nextChar;
75 Array.Copy(sourceChars, nextChar, buffer, index, charsToRead );
82 public override string ReadLine() {
83 // Reads until next \r or \n or \r\n, otherwise return null
86 // The Beta 2 SDK help says that the ReadLine method returns
87 // "The next line from the input stream [...] A line is defined as a sequence of
88 // characters followed by a carriage return (\r), a line feed (\n), or a carriage
89 // return immediately followed by a line feed (\r\n). [...]
90 // The returned value is a null reference if the end of the input stream has been reached."
92 // HOWEVER, the MS implementation returns the rest of the string if no \r and/or \n is found
96 int nextCR = source.IndexOf( '\r', nextChar );
97 int nextLF = source.IndexOf( '\n', nextChar );
99 if( nextCR == -1 && nextLF == -1 ) {
103 if( nextChar > sourceLength ) return null;
113 string nextLine = source.Substring( nextChar, readTo - nextChar );
115 if( nextLF == nextCR + 1 ) {
116 nextChar = readTo + 2;
118 nextChar = readTo + 1;
124 public override string ReadToEnd() {
125 string toEnd = source.Substring( nextChar, sourceLength - nextChar );
126 nextChar = sourceLength;