view Implab/Formats/Json/JsonStringScanner.cs @ 276:b4e0f81c7425 v3

container configuration docs
author cin
date Sat, 28 Apr 2018 00:11:38 +0300
parents 7c7e9ad6fe4a
children
line wrap: on
line source

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.ArgumentInRange(offset >= 0 && offset < data.Length , nameof(offset));
            Safe.ArgumentInRange(length >= 0 && offset + length <= data.Length, nameof(length));

            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.ArgumentInRange(offset >= 0 && offset < data.Length , nameof(offset));
            Safe.ArgumentInRange(length >= 0 && offset + length <= data.Length, nameof(length));

            return new JsonStringScanner(null, data, offset, offset + length, offset + length);

        }
    }
}