All files
[pithos-ms-client] / trunk / Libraries / Json40r2 / Source / Src / Newtonsoft.Json / Utilities / Base64Encoder.cs
1 using System;
2 using System.IO;
3
4 namespace Newtonsoft.Json.Utilities
5 {
6   internal class Base64Encoder
7   {
8     private const int Base64LineSize = 76;
9     private const int LineSizeInBytes = 57;
10
11     private readonly char[] _charsLine = new char[Base64LineSize];
12     private readonly TextWriter _writer;
13
14     private byte[] _leftOverBytes;
15     private int _leftOverBytesCount;
16
17     public Base64Encoder(TextWriter writer)
18     {
19       ValidationUtils.ArgumentNotNull(writer, "writer");
20       _writer = writer;
21     }
22
23     public void Encode(byte[] buffer, int index, int count)
24     {
25       if (buffer == null)
26         throw new ArgumentNullException("buffer");
27
28       if (index < 0)
29         throw new ArgumentOutOfRangeException("index");
30
31       if (count < 0)
32         throw new ArgumentOutOfRangeException("count");
33
34       if (count > (buffer.Length - index))
35         throw new ArgumentOutOfRangeException("count");
36
37       if (_leftOverBytesCount > 0)
38       {
39         int leftOverBytesCount = _leftOverBytesCount;
40         while (leftOverBytesCount < 3 && count > 0)
41         {
42           _leftOverBytes[leftOverBytesCount++] = buffer[index++];
43           count--;
44         }
45         if (count == 0 && leftOverBytesCount < 3)
46         {
47           _leftOverBytesCount = leftOverBytesCount;
48           return;
49         }
50         int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0);
51         WriteChars(_charsLine, 0, num2);
52       }
53       _leftOverBytesCount = count % 3;
54       if (_leftOverBytesCount > 0)
55       {
56         count -= _leftOverBytesCount;
57         if (_leftOverBytes == null)
58         {
59           _leftOverBytes = new byte[3];
60         }
61         for (int i = 0; i < _leftOverBytesCount; i++)
62         {
63           _leftOverBytes[i] = buffer[(index + count) + i];
64         }
65       }
66       int num4 = index + count;
67       int length = LineSizeInBytes;
68       while (index < num4)
69       {
70         if ((index + length) > num4)
71         {
72           length = num4 - index;
73         }
74         int num6 = Convert.ToBase64CharArray(buffer, index, length, _charsLine, 0);
75         WriteChars(_charsLine, 0, num6);
76         index += length;
77       }
78     }
79
80     public void Flush()
81     {
82       if (_leftOverBytesCount > 0)
83       {
84         int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0);
85         WriteChars(_charsLine, 0, count);
86         _leftOverBytesCount = 0;
87       }
88     }
89
90     private void WriteChars(char[] chars, int index, int count)
91     {
92       _writer.Write(chars, index, count);
93     }
94   }
95 }