about summary refs log tree commit diff
path: root/IrcTokens/StatefulEncoder.cs
blob: c036400deffe5825368735828e76e3db7ec2e48a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IrcTokens
{
    public class StatefulEncoder
    {
        private Encoding _encoding;

        public Encoding Encoding
        {
            get => _encoding ?? Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback,
                DecoderFallback.ExceptionFallback);
            set
            {
                if (value != null)
                {
                    _encoding = Encoding.GetEncoding(value.CodePage, EncoderFallback.ExceptionFallback,
                        DecoderFallback.ExceptionFallback);
                }
            }
        }

        private Queue<Line> _bufferedLines;

        public byte[] PendingBytes { get; private set; }

        public string Pending()
        {
            try
            {
                return Encoding.GetString(PendingBytes);
            }
            catch (DecoderFallbackException e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public StatefulEncoder()
        {
            Clear();
        }

        public void Clear()
        {
            PendingBytes = Array.Empty<byte>();
            _bufferedLines = new Queue<Line>();
        }

        public void Push(Line line)
        {
            if (line == null)
            {
                throw new ArgumentNullException(nameof(line));
            }

            PendingBytes = PendingBytes.Concat(Encoding.GetBytes($"{line.Format()}\r\n")).ToArray();
            _bufferedLines.Enqueue(line);
        }

        public List<Line> Pop(int byteCount)
        {
            var sent = PendingBytes.Take(byteCount).Count(c => c == '\n');

            PendingBytes = PendingBytes.Skip(byteCount).ToArray();
            _bufferedLines = new Queue<Line>(_bufferedLines.Skip(sent));

            return Enumerable.Range(0, sent)
                .Select(_ => _bufferedLines.Dequeue())
                .ToList();
        }
    }
}