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)
34 base.Dispose (disposing);
37 public override int Peek() {
38 if( nextChar >= sourceLength ) {
41 return (int)source[ nextChar ];
45 public override int Read() {
46 if( nextChar >= sourceLength ) {
49 return (int)source[ nextChar++ ];
54 // The method will read up to count characters from the StringReader
55 // into the buffer character array starting at position index. Returns
56 // the actual number of characters read, or zero if the end of the string
57 // has been reached and no characters are read.
59 public override int Read( char[] buffer, int index, int count ) {
61 if( buffer == null ) {
62 throw new ArgumentNullException();
63 } else if( buffer.Length - index < count ) {
64 throw new ArgumentException();
65 } else if( index < 0 || count < 0 ) {
66 throw new ArgumentOutOfRangeException();
71 if( nextChar + count > sourceLength ) {
72 charsToRead = sourceLength - nextChar;
77 Array.Copy(sourceChars, nextChar, buffer, index, charsToRead );
84 public override string ReadLine() {
85 // Reads until next \r or \n or \r\n, otherwise return null
88 // The Beta 2 SDK help says that the ReadLine method returns
89 // "The next line from the input stream [...] A line is defined as a sequence of
90 // characters followed by a carriage return (\r), a line feed (\n), or a carriage
91 // return immediately followed by a line feed (\r\n). [...]
92 // The returned value is a null reference if the end of the input stream has been reached."
94 // HOWEVER, the MS implementation returns the rest of the string if no \r and/or \n is found
97 if (nextChar >= source.Length)
100 int nextCR = source.IndexOf( '\r', nextChar );
101 int nextLF = source.IndexOf( '\n', nextChar );
103 if( nextCR == -1 && nextLF == -1 ) {
115 string nextLine = source.Substring( nextChar, readTo - nextChar );
117 if( nextLF == nextCR + 1 ) {
118 nextChar = readTo + 2;
120 nextChar = readTo + 1;
126 public override string ReadToEnd() {
127 string toEnd = source.Substring( nextChar, sourceLength - nextChar );
128 nextChar = sourceLength;