about summary refs log tree commit diff
path: root/IrcTokens/StatefulEncoder.cs
blob: 57f1b9619d0c5d906db80f8c2534538638a3c16e (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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IrcTokens
{
    public class StatefulEncoder
    {
        private List<Line> _bufferedLines;
        private Encoding _encoding;

        public StatefulEncoder()
        {
            Clear();
        }

        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);
            }
        }

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

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

        public void Clear()
        {
            PendingBytes   = Array.Empty<byte>();
            _bufferedLines = new List<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.Add(line);
        }

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

            PendingBytes   = PendingBytes.Skip(byteCount).ToArray();
            
            var sentLines = _bufferedLines.Take(sent).ToList();
            _bufferedLines = _bufferedLines.Skip(sent).ToList();

            return sentLines;
        }
    }
}