View difference between Paste ID: GpNy0Yr1 and bcVkq3ee
SHOW: | | - or go back to the newest paste.
1
using System;
2
using System.IO;
3
using System.Collections;
4
using Microsoft.SPOT;
5
6
namespace Netduino_ReadFile
7
{
8
	// Only works with ASCII streams
9
	public class FastLineReader
10
	{
11
		protected Stream mInputStream;
12
		protected byte[] mFileBuffer;
13
		protected int mFileBufferPos;
14
		protected int mFileBufferLen;
15
		protected int mBufferSize;
16
17
		public bool EndOfStream { get; protected set; }
18
19-
		public FastLineReader(Stream s, int bufferSize = 512)
19+
		/// <summary>
20
		/// 
21
		/// </summary>
22
		/// <param name="s"></param>
23
		/// <param name="bufferSize">this should be your expected max line length. it is ok if too small</param>
24
		public FastLineReader(Stream s, int bufferSize = 256)
25
		{
26
			mInputStream = s;
27
			mBufferSize = bufferSize;
28
			mFileBuffer = new byte[bufferSize];
29
			mFileBufferPos = 0;
30
			mFileBufferLen = 0;
31
			EndOfStream = false;
32
		}
33
34
		public String ReadLine()
35
		{
36
			var lineBuffer = new char[mBufferSize];
37
			int lineBufferPos = 0;
38
39
			bool foundLF = false;
40
			while(!foundLF)
41
			{
42
				if (mFileBufferPos >= mFileBufferLen)
43
				{
44
					mFileBufferPos = 0;
45
					mFileBufferLen = mInputStream.Read(mFileBuffer, mFileBufferPos, mFileBuffer.Length);
46
					if (mFileBufferLen == 0)
47
					{
48-
				if (lineBufferPos >= lineBuffer.Length - 1)
48+
49
						break; // empty file or we're finished
50-
					var tempBuffer = new char[lineBuffer.Length + mFileBufferLen];
50+
51
				}
52
53
				int lfLocation = mFileBufferLen - 1;
54
				for (int x = mFileBufferPos; x < mFileBufferLen; ++x)
55
				{
56
					if (mFileBuffer[x] == '\n')
57
					{
58
						lfLocation = x;
59
						foundLF = true;
60
						break;
61
					}
62
				}
63
				var dataSize = (lfLocation + 1 - mFileBufferPos); // lfLocation is 0 based, need to increment by 1 for size
64
65
				if ((lineBufferPos + dataSize) > lineBuffer.Length)
66
				{
67
					var tempBuffer = new char[lineBufferPos + dataSize];
68
					Array.Copy(lineBuffer, tempBuffer, lineBuffer.Length);
69
					lineBuffer = tempBuffer;
70
				}
71
72
				for (int x = mFileBufferPos; x <= lfLocation; ++x)
73
				{
74
					lineBuffer[lineBufferPos++] = (char)mFileBuffer[x];
75
				}
76
				mFileBufferPos = lfLocation + 1; 
77
			}
78
79
			return new String(lineBuffer, 0, lineBufferPos);
80
		}
81
	}
82
}