Mercurial > pub > ImplabNet
diff Implab/Formats/JSON/JsonStringScanner.cs @ 228:6fa235c5a760 v2
Rewritten JsonScanner, JsonParser, fixed naming style
author | cin |
---|---|
date | Tue, 12 Sep 2017 01:19:12 +0300 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Implab/Formats/JSON/JsonStringScanner.cs Tue Sep 12 01:19:12 2017 +0300 @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Implab.Formats.Json { + public class JsonStringScanner : JsonScanner { + const int _defaultBuffer = 64; + + readonly string m_data; + int m_offset; + + JsonStringScanner(string data, char[] buffer, int pos, int length, int offset) : base(buffer, pos, length) { + m_data = data; + m_offset = offset; + } + + protected override int Read(char[] buffer, int offset, int size) { + if (m_data == null) + return 0; + if (m_offset >= m_data.Length) + return 0; + + var count = Math.Min(size, m_data.Length - m_offset); + + m_data.CopyTo(m_offset, buffer, offset, count); + m_offset += count; + + return count; + } + + public static JsonStringScanner Create(string data) { + Safe.ArgumentNotNull(data, nameof(data)); + + if (data.Length <= _defaultBuffer) + return new JsonStringScanner(null, data.ToCharArray(), 0, data.Length, data.Length); + + var buffer = new char[_defaultBuffer]; + data.CopyTo(0, buffer, 0, _defaultBuffer); + return new JsonStringScanner(data, buffer, 0, _defaultBuffer, _defaultBuffer); + } + + public static JsonStringScanner Create(string data, int offset, int length) { + Safe.ArgumentNotNull(data, nameof(data)); + Safe.ArgumentGreaterThan(offset, 0, nameof(offset)); + Safe.ArgumentGreaterThan(length, 0, nameof(length)); + + if (offset + length > data.Length) + throw new ArgumentOutOfRangeException("Specified offset and length are out of the string bounds"); + + if (length <= _defaultBuffer) { + var buffer = new char[length]; + data.CopyTo(offset, buffer, 0, length); + + return new JsonStringScanner(null, buffer, 0, length, length); + } else { + var buffer = new char[_defaultBuffer]; + data.CopyTo(offset, buffer, 0, _defaultBuffer); + return new JsonStringScanner(data, buffer, 0, _defaultBuffer, offset + _defaultBuffer); + } + } + + public static JsonStringScanner Create(char[] data, int offset, int length) { + Safe.ArgumentNotNull(data, nameof(data)); + Safe.ArgumentGreaterThan(offset, 0, nameof(offset)); + Safe.ArgumentGreaterThan(length, 0, nameof(length)); + + if (offset + length > data.Length) + throw new ArgumentOutOfRangeException("Specified offset and length are out of the array bounds"); + + return new JsonStringScanner(null, data, offset, offset + length, offset + length); + + } + } +}