4 namespace Newtonsoft.Json.Utilities
6 internal class Base64Encoder
8 private const int Base64LineSize = 76;
9 private const int LineSizeInBytes = 57;
11 private readonly char[] _charsLine = new char[Base64LineSize];
12 private readonly TextWriter _writer;
14 private byte[] _leftOverBytes;
15 private int _leftOverBytesCount;
17 public Base64Encoder(TextWriter writer)
19 ValidationUtils.ArgumentNotNull(writer, "writer");
23 public void Encode(byte[] buffer, int index, int count)
26 throw new ArgumentNullException("buffer");
29 throw new ArgumentOutOfRangeException("index");
32 throw new ArgumentOutOfRangeException("count");
34 if (count > (buffer.Length - index))
35 throw new ArgumentOutOfRangeException("count");
37 if (_leftOverBytesCount > 0)
39 int leftOverBytesCount = _leftOverBytesCount;
40 while (leftOverBytesCount < 3 && count > 0)
42 _leftOverBytes[leftOverBytesCount++] = buffer[index++];
45 if (count == 0 && leftOverBytesCount < 3)
47 _leftOverBytesCount = leftOverBytesCount;
50 int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0);
51 WriteChars(_charsLine, 0, num2);
53 _leftOverBytesCount = count % 3;
54 if (_leftOverBytesCount > 0)
56 count -= _leftOverBytesCount;
57 if (_leftOverBytes == null)
59 _leftOverBytes = new byte[3];
61 for (int i = 0; i < _leftOverBytesCount; i++)
63 _leftOverBytes[i] = buffer[(index + count) + i];
66 int num4 = index + count;
67 int length = LineSizeInBytes;
70 if ((index + length) > num4)
72 length = num4 - index;
74 int num6 = Convert.ToBase64CharArray(buffer, index, length, _charsLine, 0);
75 WriteChars(_charsLine, 0, num6);
82 if (_leftOverBytesCount > 0)
84 int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0);
85 WriteChars(_charsLine, 0, count);
86 _leftOverBytesCount = 0;
90 private void WriteChars(char[] chars, int index, int count)
92 _writer.Write(chars, index, count);