Encoding code clean up (#12864)
[platform/upstream/coreclr.git] / src / mscorlib / shared / System / Text / Encoder.cs
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 using System.Text;
6 using System;
7 using System.Diagnostics;
8 using System.Diagnostics.Contracts;
9
10 namespace System.Text
11 {
12     // An Encoder is used to encode a sequence of blocks of characters into
13     // a sequence of blocks of bytes. Following instantiation of an encoder,
14     // sequential blocks of characters are converted into blocks of bytes through
15     // calls to the GetBytes method. The encoder maintains state between the
16     // conversions, allowing it to correctly encode character sequences that span
17     // adjacent blocks.
18     //
19     // Instances of specific implementations of the Encoder abstract base
20     // class are typically obtained through calls to the GetEncoder method
21     // of Encoding objects.
22     //
23     public abstract class Encoder
24     {
25         internal EncoderFallback _fallback = null;
26
27         internal EncoderFallbackBuffer _fallbackBuffer = null;
28
29         protected Encoder()
30         {
31             // We don't call default reset because default reset probably isn't good if we aren't initialized.
32         }
33
34         public EncoderFallback Fallback
35         {
36             get
37             {
38                 return _fallback;
39             }
40
41             set
42             {
43                 if (value == null)
44                     throw new ArgumentNullException(nameof(value));
45                 Contract.EndContractBlock();
46
47                 // Can't change fallback if buffer is wrong
48                 if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
49                     throw new ArgumentException(
50                       SR.Argument_FallbackBufferNotEmpty, nameof(value));
51
52                 _fallback = value;
53                 _fallbackBuffer = null;
54             }
55         }
56
57         // Note: we don't test for threading here because async access to Encoders and Decoders
58         // doesn't work anyway.
59         public EncoderFallbackBuffer FallbackBuffer
60         {
61             get
62             {
63                 if (_fallbackBuffer == null)
64                 {
65                     if (_fallback != null)
66                         _fallbackBuffer = _fallback.CreateFallbackBuffer();
67                     else
68                         _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
69                 }
70
71                 return _fallbackBuffer;
72             }
73         }
74
75         internal bool InternalHasFallbackBuffer
76         {
77             get
78             {
79                 return _fallbackBuffer != null;
80             }
81         }
82
83         // Reset the Encoder
84         //
85         // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder.  This
86         // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
87         //
88         // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
89         //
90         // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
91         // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
92         public virtual void Reset()
93         {
94             char[] charTemp = { };
95             byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
96             GetBytes(charTemp, 0, 0, byteTemp, 0, true);
97             if (_fallbackBuffer != null)
98                 _fallbackBuffer.Reset();
99         }
100
101         // Returns the number of bytes the next call to GetBytes will
102         // produce if presented with the given range of characters and the given
103         // value of the flush parameter. The returned value takes into
104         // account the state in which the encoder was left following the last call
105         // to GetBytes. The state of the encoder is not affected by a call
106         // to this method.
107         //
108         public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
109
110         // We expect this to be the workhorse for NLS encodings
111         // unfortunately for existing overrides, it has to call the [] version,
112         // which is really slow, so avoid this method if you might be calling external encodings.
113         [CLSCompliant(false)]
114         public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
115         {
116             // Validate input parameters
117             if (chars == null)
118                 throw new ArgumentNullException(nameof(chars),
119                       SR.ArgumentNull_Array);
120
121             if (count < 0)
122                 throw new ArgumentOutOfRangeException(nameof(count),
123                       SR.ArgumentOutOfRange_NeedNonNegNum);
124             Contract.EndContractBlock();
125
126             char[] arrChar = new char[count];
127             int index;
128
129             for (index = 0; index < count; index++)
130                 arrChar[index] = chars[index];
131
132             return GetByteCount(arrChar, 0, count, flush);
133         }
134
135         // Encodes a range of characters in a character array into a range of bytes
136         // in a byte array. The method encodes charCount characters from
137         // chars starting at index charIndex, storing the resulting
138         // bytes in bytes starting at index byteIndex. The encoding
139         // takes into account the state in which the encoder was left following the
140         // last call to this method. The flush parameter indicates whether
141         // the encoder should flush any shift-states and partial characters at the
142         // end of the conversion. To ensure correct termination of a sequence of
143         // blocks of encoded bytes, the last call to GetBytes should specify
144         // a value of true for the flush parameter.
145         //
146         // An exception occurs if the byte array is not large enough to hold the
147         // complete encoding of the characters. The GetByteCount method can
148         // be used to determine the exact number of bytes that will be produced for
149         // a given range of characters. Alternatively, the GetMaxByteCount
150         // method of the Encoding that produced this encoder can be used to
151         // determine the maximum number of bytes that will be produced for a given
152         // number of characters, regardless of the actual character values.
153         //
154         public abstract int GetBytes(char[] chars, int charIndex, int charCount,
155                                         byte[] bytes, int byteIndex, bool flush);
156
157         // We expect this to be the workhorse for NLS Encodings, but for existing
158         // ones we need a working (if slow) default implementation)
159         //
160         // WARNING WARNING WARNING
161         //
162         // WARNING: If this breaks it could be a security threat.  Obviously we
163         // call this internally, so you need to make sure that your pointers, counts
164         // and indexes are correct when you call this method.
165         //
166         // In addition, we have internal code, which will be marked as "safe" calling
167         // this code.  However this code is dependent upon the implementation of an
168         // external GetBytes() method, which could be overridden by a third party and
169         // the results of which cannot be guaranteed.  We use that result to copy
170         // the byte[] to our byte* output buffer.  If the result count was wrong, we
171         // could easily overflow our output buffer.  Therefore we do an extra test
172         // when we copy the buffer so that we don't overflow byteCount either.
173         [CLSCompliant(false)]
174         public virtual unsafe int GetBytes(char* chars, int charCount,
175                                               byte* bytes, int byteCount, bool flush)
176         {
177             // Validate input parameters
178             if (bytes == null || chars == null)
179                 throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
180                     SR.ArgumentNull_Array);
181
182             if (charCount < 0 || byteCount < 0)
183                 throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
184                     SR.ArgumentOutOfRange_NeedNonNegNum);
185             Contract.EndContractBlock();
186
187             // Get the char array to convert
188             char[] arrChar = new char[charCount];
189
190             int index;
191             for (index = 0; index < charCount; index++)
192                 arrChar[index] = chars[index];
193
194             // Get the byte array to fill
195             byte[] arrByte = new byte[byteCount];
196
197             // Do the work
198             int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
199
200             Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
201
202             // Copy the byte array
203             // WARNING: We MUST make sure that we don't copy too many bytes.  We can't
204             // rely on result because it could be a 3rd party implementation.  We need
205             // to make sure we never copy more than byteCount bytes no matter the value
206             // of result
207             if (result < byteCount)
208                 byteCount = result;
209
210             // Don't copy too many bytes!
211             for (index = 0; index < byteCount; index++)
212                 bytes[index] = arrByte[index];
213
214             return byteCount;
215         }
216
217         // This method is used to avoid running out of output buffer space.
218         // It will encode until it runs out of chars, and then it will return
219         // true if it the entire input was converted.  In either case it
220         // will also return the number of converted chars and output bytes used.
221         // It will only throw a buffer overflow exception if the entire lenght of bytes[] is
222         // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
223         // We're done processing this buffer only if completed returns true.
224         //
225         // Might consider checking Max...Count to avoid the extra counting step.
226         //
227         // Note that if all of the input chars are not consumed, then we'll do a /2, which means
228         // that its likely that we didn't consume as many chars as we could have.  For some
229         // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
230         public virtual void Convert(char[] chars, int charIndex, int charCount,
231                                       byte[] bytes, int byteIndex, int byteCount, bool flush,
232                                       out int charsUsed, out int bytesUsed, out bool completed)
233         {
234             // Validate parameters
235             if (chars == null || bytes == null)
236                 throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
237                       SR.ArgumentNull_Array);
238
239             if (charIndex < 0 || charCount < 0)
240                 throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
241                       SR.ArgumentOutOfRange_NeedNonNegNum);
242
243             if (byteIndex < 0 || byteCount < 0)
244                 throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
245                       SR.ArgumentOutOfRange_NeedNonNegNum);
246
247             if (chars.Length - charIndex < charCount)
248                 throw new ArgumentOutOfRangeException(nameof(chars),
249                       SR.ArgumentOutOfRange_IndexCountBuffer);
250
251             if (bytes.Length - byteIndex < byteCount)
252                 throw new ArgumentOutOfRangeException(nameof(bytes),
253                       SR.ArgumentOutOfRange_IndexCountBuffer);
254             Contract.EndContractBlock();
255
256             charsUsed = charCount;
257
258             // Its easy to do if it won't overrun our buffer.
259             // Note: We don't want to call unsafe version because that might be an untrusted version
260             // which could be really unsafe and we don't want to mix it up.
261             while (charsUsed > 0)
262             {
263                 if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
264                 {
265                     bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
266                     completed = (charsUsed == charCount &&
267                         (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
268                     return;
269                 }
270
271                 // Try again with 1/2 the count, won't flush then 'cause won't read it all
272                 flush = false;
273                 charsUsed /= 2;
274             }
275
276             // Oops, we didn't have anything, we'll have to throw an overflow
277             throw new ArgumentException(SR.Argument_ConversionOverflow);
278         }
279
280         // Same thing, but using pointers
281         //
282         // Might consider checking Max...Count to avoid the extra counting step.
283         //
284         // Note that if all of the input chars are not consumed, then we'll do a /2, which means
285         // that its likely that we didn't consume as many chars as we could have.  For some
286         // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
287         [CLSCompliant(false)]
288         public virtual unsafe void Convert(char* chars, int charCount,
289                                              byte* bytes, int byteCount, bool flush,
290                                              out int charsUsed, out int bytesUsed, out bool completed)
291         {
292             // Validate input parameters
293             if (bytes == null || chars == null)
294                 throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
295                     SR.ArgumentNull_Array);
296             if (charCount < 0 || byteCount < 0)
297                 throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
298                     SR.ArgumentOutOfRange_NeedNonNegNum);
299             Contract.EndContractBlock();
300
301             // Get ready to do it
302             charsUsed = charCount;
303
304             // Its easy to do if it won't overrun our buffer.
305             while (charsUsed > 0)
306             {
307                 if (GetByteCount(chars, charsUsed, flush) <= byteCount)
308                 {
309                     bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
310                     completed = (charsUsed == charCount &&
311                         (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
312                     return;
313                 }
314
315                 // Try again with 1/2 the count, won't flush then 'cause won't read it all
316                 flush = false;
317                 charsUsed /= 2;
318             }
319
320             // Oops, we didn't have anything, we'll have to throw an overflow
321             throw new ArgumentException(SR.Argument_ConversionOverflow);
322         }
323     }
324 }
325