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.
6 // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
12 using System.Runtime.Serialization;
13 using System.Security.Permissions;
14 using System.Diagnostics.Contracts;
18 [System.Runtime.InteropServices.ComVisible(true)]
19 public class UTF7Encoding : Encoding
21 private const String base64Chars =
22 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23 // 0123456789111111111122222222223333333333444444444455555555556666
24 // 012345678901234567890123456789012345678901234567890123
26 // These are the characters that can be directly encoded in UTF7.
27 private const String directChars =
28 "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
30 // These are the characters that can be optionally directly encoded in UTF7.
31 private const String optionalChars =
32 "!\"#$%&*;<=>@[]^_`{|}";
34 // The set of base 64 characters.
35 private byte[] base64Bytes;
36 // The decoded bits for every base64 values. This array has a size of 128 elements.
37 // The index is the code point value of the base 64 characters. The value is -1 if
38 // the code point is not a valid base 64 character. Otherwise, the value is a value
40 private sbyte[] base64Values;
41 // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7.
42 // This array has a size of 128.
43 private bool[] directEncode;
45 [OptionalField(VersionAdded = 2)]
46 private bool m_allowOptionals;
48 private const int UTF7_CODEPAGE=65000;
56 public UTF7Encoding(bool allowOptionals)
57 : base(UTF7_CODEPAGE) //Set the data item.
59 // Allowing optionals?
60 this.m_allowOptionals = allowOptionals;
66 private void MakeTables()
69 base64Bytes = new byte[64];
70 for (int i = 0; i < 64; i++) base64Bytes[i] = (byte)base64Chars[i];
71 base64Values = new sbyte[128];
72 for (int i = 0; i < 128; i++) base64Values[i] = -1;
73 for (int i = 0; i < 64; i++) base64Values[base64Bytes[i]] = (sbyte)i;
74 directEncode = new bool[128];
75 int count = directChars.Length;
76 for (int i = 0; i < count; i++)
78 directEncode[directChars[i]] = true;
81 if (this.m_allowOptionals)
83 count = optionalChars.Length;
84 for (int i = 0; i < count; i++)
86 directEncode[optionalChars[i]] = true;
91 // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7.
92 internal override void SetDefaultFallbacks()
94 // UTF7 had an odd decoderFallback behavior, and the Encoder fallback
95 // is irrelevent because we encode surrogates individually and never check for unmatched ones
96 // (so nothing can fallback during encoding)
97 this.encoderFallback = new EncoderReplacementFallback(String.Empty);
98 this.decoderFallback = new DecoderUTF7Fallback();
102 #region Serialization
104 private void OnDeserializing(StreamingContext ctx)
106 // make sure the optional fields initialized correctly.
107 base.OnDeserializing();
111 private void OnDeserialized(StreamingContext ctx)
113 base.OnDeserialized();
115 if (m_deserializedFromEverett)
117 // If 1st optional char is encoded we're allowing optionals
118 m_allowOptionals = directEncode[optionalChars[0]];
123 #endregion Serialization
127 [System.Runtime.InteropServices.ComVisible(false)]
128 public override bool Equals(Object value)
130 UTF7Encoding that = value as UTF7Encoding;
133 return (m_allowOptionals == that.m_allowOptionals) &&
134 (EncoderFallback.Equals(that.EncoderFallback)) &&
135 (DecoderFallback.Equals(that.DecoderFallback));
140 // Compared to all the other encodings, variations of UTF7 are unlikely
142 [System.Runtime.InteropServices.ComVisible(false)]
143 public override int GetHashCode()
145 return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
149 // The following methods are copied from EncodingNLS.cs.
150 // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here.
151 // These should be kept in sync for the following classes:
152 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
155 // Returns the number of bytes required to encode a range of characters in
156 // a character array.
158 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
159 // So if you fix this, fix the others. Currently those include:
160 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
161 // parent method is safe
163 [System.Security.SecuritySafeCritical] // auto-generated
164 public override int GetByteCount(char[] chars, int index, int count)
166 return EncodingForwarder.GetByteCount(this, chars, index, count);
169 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
170 // So if you fix this, fix the others. Currently those include:
171 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
172 // parent method is safe
174 [System.Security.SecuritySafeCritical] // auto-generated
175 [System.Runtime.InteropServices.ComVisible(false)]
176 public override int GetByteCount(String s)
178 return EncodingForwarder.GetByteCount(this, s);
181 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
182 // So if you fix this, fix the others. Currently those include:
183 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
185 [System.Security.SecurityCritical] // auto-generated
186 [CLSCompliant(false)]
187 [System.Runtime.InteropServices.ComVisible(false)]
188 public override unsafe int GetByteCount(char* chars, int count)
190 // Validate Parameters
192 throw new ArgumentNullException("chars",
193 Environment.GetResourceString("ArgumentNull_Array"));
196 throw new ArgumentOutOfRangeException("count",
197 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
198 Contract.EndContractBlock();
200 // Call it with empty encoder
201 return GetByteCount(chars, count, null);
204 // Parent method is safe.
205 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
206 // So if you fix this, fix the others. Currently those include:
207 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
209 [System.Security.SecuritySafeCritical] // auto-generated
210 [System.Runtime.InteropServices.ComVisible(false)]
211 public override unsafe int GetBytes(String s, int charIndex, int charCount,
212 byte[] bytes, int byteIndex)
214 if (s == null || bytes == null)
215 throw new ArgumentNullException((s == null ? "s" : "bytes"),
216 Environment.GetResourceString("ArgumentNull_Array"));
218 if (charIndex < 0 || charCount < 0)
219 throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
220 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
222 if (s.Length - charIndex < charCount)
223 throw new ArgumentOutOfRangeException("s",
224 Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
226 if (byteIndex < 0 || byteIndex > bytes.Length)
227 throw new ArgumentOutOfRangeException("byteIndex",
228 Environment.GetResourceString("ArgumentOutOfRange_Index"));
229 Contract.EndContractBlock();
231 int byteCount = bytes.Length - byteIndex;
233 // Fixed doesn't like empty arrays
234 if (bytes.Length == 0)
237 fixed (char* pChars = s)
238 fixed ( byte* pBytes = bytes)
239 return GetBytes(pChars + charIndex, charCount,
240 pBytes + byteIndex, byteCount, null);
243 // Encodes a range of characters in a character array into a range of bytes
244 // in a byte array. An exception occurs if the byte array is not large
245 // enough to hold the complete encoding of the characters. The
246 // GetByteCount method can be used to determine the exact number of
247 // bytes that will be produced for a given range of characters.
248 // Alternatively, the GetMaxByteCount method can be used to
249 // determine the maximum number of bytes that will be produced for a given
250 // number of characters, regardless of the actual character values.
252 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
253 // So if you fix this, fix the others. Currently those include:
254 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
255 // parent method is safe
257 [System.Security.SecuritySafeCritical] // auto-generated
258 public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
259 byte[] bytes, int byteIndex)
261 // Validate parameters
262 if (chars == null || bytes == null)
263 throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
264 Environment.GetResourceString("ArgumentNull_Array"));
266 if (charIndex < 0 || charCount < 0)
267 throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
268 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
270 if (chars.Length - charIndex < charCount)
271 throw new ArgumentOutOfRangeException("chars",
272 Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
274 if (byteIndex < 0 || byteIndex > bytes.Length)
275 throw new ArgumentOutOfRangeException("byteIndex",
276 Environment.GetResourceString("ArgumentOutOfRange_Index"));
277 Contract.EndContractBlock();
279 // If nothing to encode return 0, avoid fixed problem
283 // Just call pointer version
284 int byteCount = bytes.Length - byteIndex;
286 // Fixed doesn't like empty arrays
287 if (bytes.Length == 0)
290 fixed (char* pChars = chars)
291 fixed (byte* pBytes = bytes)
292 // Remember that byteCount is # to decode, not size of array.
293 return GetBytes(pChars + charIndex, charCount,
294 pBytes + byteIndex, byteCount, null);
297 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
298 // So if you fix this, fix the others. Currently those include:
299 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
301 [System.Security.SecurityCritical] // auto-generated
302 [CLSCompliant(false)]
303 [System.Runtime.InteropServices.ComVisible(false)]
304 public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
306 // Validate Parameters
307 if (bytes == null || chars == null)
308 throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
309 Environment.GetResourceString("ArgumentNull_Array"));
311 if (charCount < 0 || byteCount < 0)
312 throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
313 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
314 Contract.EndContractBlock();
316 return GetBytes(chars, charCount, bytes, byteCount, null);
319 // Returns the number of characters produced by decoding a range of bytes
322 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
323 // So if you fix this, fix the others. Currently those include:
324 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
325 // parent method is safe
327 [System.Security.SecuritySafeCritical] // auto-generated
328 public override unsafe int GetCharCount(byte[] bytes, int index, int count)
330 // Validate Parameters
332 throw new ArgumentNullException("bytes",
333 Environment.GetResourceString("ArgumentNull_Array"));
335 if (index < 0 || count < 0)
336 throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
337 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
339 if (bytes.Length - index < count)
340 throw new ArgumentOutOfRangeException("bytes",
341 Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
342 Contract.EndContractBlock();
344 // If no input just return 0, fixed doesn't like 0 length arrays.
348 // Just call pointer version
349 fixed (byte* pBytes = bytes)
350 return GetCharCount(pBytes + index, count, null);
353 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
354 // So if you fix this, fix the others. Currently those include:
355 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
357 [System.Security.SecurityCritical] // auto-generated
358 [CLSCompliant(false)]
359 [System.Runtime.InteropServices.ComVisible(false)]
360 public override unsafe int GetCharCount(byte* bytes, int count)
362 // Validate Parameters
364 throw new ArgumentNullException("bytes",
365 Environment.GetResourceString("ArgumentNull_Array"));
368 throw new ArgumentOutOfRangeException("count",
369 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
370 Contract.EndContractBlock();
372 return GetCharCount(bytes, count, null);
375 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
376 // So if you fix this, fix the others. Currently those include:
377 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
378 // parent method is safe
380 [System.Security.SecuritySafeCritical] // auto-generated
381 public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
382 char[] chars, int charIndex)
384 // Validate Parameters
385 if (bytes == null || chars == null)
386 throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
387 Environment.GetResourceString("ArgumentNull_Array"));
389 if (byteIndex < 0 || byteCount < 0)
390 throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
391 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
393 if ( bytes.Length - byteIndex < byteCount)
394 throw new ArgumentOutOfRangeException("bytes",
395 Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
397 if (charIndex < 0 || charIndex > chars.Length)
398 throw new ArgumentOutOfRangeException("charIndex",
399 Environment.GetResourceString("ArgumentOutOfRange_Index"));
400 Contract.EndContractBlock();
402 // If no input, return 0 & avoid fixed problem
406 // Just call pointer version
407 int charCount = chars.Length - charIndex;
409 // Fixed doesn't like empty arrays
410 if (chars.Length == 0)
413 fixed (byte* pBytes = bytes)
414 fixed (char* pChars = chars)
415 // Remember that charCount is # to decode, not size of array
416 return GetChars(pBytes + byteIndex, byteCount,
417 pChars + charIndex, charCount, null);
420 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
421 // So if you fix this, fix the others. Currently those include:
422 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
424 [System.Security.SecurityCritical] // auto-generated
425 [CLSCompliant(false)]
426 [System.Runtime.InteropServices.ComVisible(false)]
427 public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
429 // Validate Parameters
430 if (bytes == null || chars == null)
431 throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
432 Environment.GetResourceString("ArgumentNull_Array"));
434 if (charCount < 0 || byteCount < 0)
435 throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
436 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
437 Contract.EndContractBlock();
439 return GetChars(bytes, byteCount, chars, charCount, null);
442 // Returns a string containing the decoded representation of a range of
443 // bytes in a byte array.
445 // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
446 // So if you fix this, fix the others. Currently those include:
447 // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
448 // parent method is safe
450 [System.Security.SecuritySafeCritical] // auto-generated
451 [System.Runtime.InteropServices.ComVisible(false)]
452 public override unsafe String GetString(byte[] bytes, int index, int count)
454 // Validate Parameters
456 throw new ArgumentNullException("bytes",
457 Environment.GetResourceString("ArgumentNull_Array"));
459 if (index < 0 || count < 0)
460 throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"),
461 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
463 if (bytes.Length - index < count)
464 throw new ArgumentOutOfRangeException("bytes",
465 Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
466 Contract.EndContractBlock();
468 // Avoid problems with empty input buffer
469 if (count == 0) return String.Empty;
471 fixed (byte* pBytes = bytes)
472 return String.CreateStringFromEncoding(
473 pBytes + index, count, this);
477 // End of standard methods copied from EncodingNLS.cs
480 [System.Security.SecurityCritical] // auto-generated
481 internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
483 Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
484 Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
486 // Just call GetBytes with bytes == null
487 return GetBytes(chars, count, null, 0, baseEncoder);
490 [System.Security.SecurityCritical] // auto-generated
491 internal override unsafe int GetBytes(char* chars, int charCount,
492 byte* bytes, int byteCount, EncoderNLS baseEncoder)
494 Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
495 Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
496 Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
499 UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
501 // Default bits & count
505 // prepare our helpers
506 Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
507 this, encoder, bytes, byteCount, chars, charCount);
512 bitCount = encoder.bitCount;
514 // May have had too many left over
515 while (bitCount >= 6)
518 // If we fail we'll never really have enough room
519 if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F]))
520 ThrowBytesOverflow(encoder, buffer.Count == 0);
524 while (buffer.MoreData)
526 char currentChar = buffer.GetNextChar();
528 if (currentChar < 0x80 && directEncode[currentChar])
534 // Try to add the next byte
535 if (!buffer.AddByte(base64Bytes[bits << 6 - bitCount & 0x3F]))
536 break; // Stop here, didn't throw
541 // Need to get emit '-' and our char, 2 bytes total
542 if (!buffer.AddByte((byte)'-'))
543 break; // Stop here, didn't throw
548 // Need to emit our char
549 if (!buffer.AddByte((byte)currentChar))
550 break; // Stop here, didn't throw
552 else if (bitCount < 0 && currentChar == '+')
554 if (!buffer.AddByte((byte)'+', (byte)'-'))
555 break; // Stop here, didn't throw
561 // Need to emit a + and 12 bits (3 bytes)
562 // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time
563 if (!buffer.AddByte((byte)'+'))
564 break; // Stop here, didn't throw
566 // We're now in bit mode, but haven't stored data yet
571 bits = bits << 16 | currentChar;
574 while (bitCount >= 6)
577 if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F]))
579 bitCount += 6; // We didn't use these bits
580 currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte
581 // --'d it when we ran out of space
582 break; // Stop here, not enough room for bytes
587 break; // Didn't have room to encode enough bits
591 // Now if we have bits left over we have to encode them.
592 // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting
593 if (bitCount >= 0 && (encoder == null || encoder.MustFlush))
595 // Do we have bits we have to stick in?
598 if (buffer.AddByte(base64Bytes[(bits << (6 - bitCount)) & 0x3F]))
600 // Emitted spare bits, 0 bits left
605 // If converting and failed bitCount above, then we'll fail this too
606 if (buffer.AddByte((byte)'-'))
608 // turned off bit mode';
613 // If not successful, convert will maintain state for next time, also
614 // AddByte will have decremented our char count, however we need it to remain the same
615 buffer.GetNextChar();
618 // Do we have an encoder we're allowed to use?
619 // bytes == null if counting, so don't use encoder then
620 if (bytes != null && encoder != null)
622 // We already cleared bits & bitcount for mustflush case
624 encoder.bitCount = bitCount;
625 encoder.m_charsUsed = buffer.CharsUsed;
631 [System.Security.SecurityCritical] // auto-generated
632 internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
634 Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
635 Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
637 // Just call GetChars with null char* to do counting
638 return GetChars(bytes, count, null, 0, baseDecoder);
641 [System.Security.SecurityCritical] // auto-generated
642 internal override unsafe int GetChars(byte* bytes, int byteCount,
643 char* chars, int charCount, DecoderNLS baseDecoder)
645 Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
646 Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
647 Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
649 // Might use a decoder
650 UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
652 // Get our output buffer info.
653 Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
654 this, decoder, chars, charCount, bytes, byteCount);
659 bool firstByte = false;
663 bitCount = decoder.bitCount;
664 firstByte = decoder.firstByte;
666 Contract.Assert(firstByte == false || decoder.bitCount <= 0,
667 "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set");
670 // We may have had bits in the decoder that we couldn't output last time, so do so now
673 // Check our decoder buffer
674 if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF)))
675 ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert
677 // Used this one, clean up extra bits
681 // Loop through the input
682 while (buffer.MoreData)
684 byte currentByte = buffer.GetNextByte();
690 // Modified base 64 encoding.
693 if (currentByte < 0x80 && ((v = base64Values[currentByte]) >=0))
696 bits = (bits << 6) | ((byte)v);
700 c = (bits >> (bitCount - 16)) & 0xFFFF;
703 // If not enough bits just continue
708 // If it wasn't a base 64 byte, everything's going to turn off base 64 mode
711 if (currentByte != '-')
713 // >= 0x80 (because of 1st if statemtn)
714 // We need this check since the base64Values[b] check below need b <= 0x7f.
715 // This is not a valid base 64 byte. Terminate the shifted-sequence and
718 // not in base 64 table
719 // According to the RFC 1642 and the example code of UTF-7
720 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte
722 // Chars won't be updated unless this works, try to fallback
723 if (!buffer.Fallback(currentByte))
724 break; // Stop here, didn't throw
726 // Used that byte, we're done with it
731 // The encoding for '+' is "+-".
733 if (firstByte) c = '+';
734 // We just turn it off if not emitting a +, so we're done.
738 // End of modified base 64 encoding block.
741 else if (currentByte == '+')
744 // Found the start of a modified base 64 encoding block or a plus sign.
753 if (currentByte >= 0x80)
756 if (!buffer.Fallback(currentByte))
757 break; // Stop here, didn't throw
763 // Use the normal character
770 if (!buffer.AddChar((char)c))
772 // No room. If it was a plain char we'll try again later.
773 // Note, we'll consume this byte and stick it in decoder, even if we can't output it
774 if (bitCount >= 0) // Can we rememmber this byte (char)
776 buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed
777 bitCount += 16; // We'll still need that char we have in our bits
779 break; // didn't throw, stop
784 // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder)
785 if (chars != null && decoder != null)
787 // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer)
788 if (decoder.MustFlush)
790 // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them
792 decoder.bitCount = -1;
793 decoder.firstByte = false;
798 decoder.bitCount = bitCount;
799 decoder.firstByte = firstByte;
801 decoder.m_bytesUsed = buffer.BytesUsed;
803 // else ignore any hanging bits.
810 public override System.Text.Decoder GetDecoder()
812 return new UTF7Encoding.Decoder(this);
816 public override System.Text.Encoder GetEncoder()
818 return new UTF7Encoding.Encoder(this);
822 public override int GetMaxByteCount(int charCount)
825 throw new ArgumentOutOfRangeException("charCount",
826 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
827 Contract.EndContractBlock();
829 // Suppose that every char can not be direct-encoded, we know that
830 // a byte can encode 6 bits of the Unicode character. And we will
831 // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark.
832 // Therefore, the max byte should be:
833 // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6);
834 // That is always <= 2 + 3 * charCount;
835 // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char.
836 // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off
837 // encoding if MustFlush is true.
839 // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char.
840 // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3
841 // bytes allows us to turn off and then back on base64 mode if necessary.
843 // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all
844 // code points are encodable int UTF7.
845 long byteCount = (long)charCount * 3 + 2;
847 // check for overflow
848 if (byteCount > 0x7fffffff)
849 throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
851 return (int)byteCount;
855 public override int GetMaxCharCount(int byteCount)
858 throw new ArgumentOutOfRangeException("byteCount",
859 Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
860 Contract.EndContractBlock();
862 // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed
863 // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction.
864 int charCount = byteCount;
865 if (charCount == 0) charCount = 1;
871 // Of all the amazing things... This MUST be Decoder so that our com name
872 // for System.Text.Decoder doesn't change
873 private class Decoder : DecoderNLS, ISerializable
875 /*private*/ internal int bits;
876 /*private*/ internal int bitCount;
877 /*private*/ internal bool firstByte;
879 public Decoder(UTF7Encoding encoding) : base (encoding)
884 // Constructor called by serialization, have to handle deserializing from Everett
885 internal Decoder(SerializationInfo info, StreamingContext context)
888 if (info==null) throw new ArgumentNullException("info");
889 Contract.EndContractBlock();
892 this.bits = (int)info.GetValue("bits", typeof(int));
893 this.bitCount = (int)info.GetValue("bitCount", typeof(int));
894 this.firstByte = (bool)info.GetValue("firstByte", typeof(bool));
895 this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
898 #if FEATURE_SERIALIZATION
899 // ISerializable implementation, get data for this object
900 [System.Security.SecurityCritical] // auto-generated_required
901 void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
904 if (info==null) throw new ArgumentNullException("info");
905 Contract.EndContractBlock();
908 info.AddValue("encoding", this.m_encoding);
909 info.AddValue("bits", this.bits);
910 info.AddValue("bitCount", this.bitCount);
911 info.AddValue("firstByte", this.firstByte);
915 public override void Reset()
919 this.firstByte = false;
920 if (m_fallbackBuffer != null)
921 m_fallbackBuffer.Reset();
924 // Anything left in our encoder?
925 internal override bool HasState
929 // NOTE: This forces the last -, which some encoder might not encode. If we
930 // don't see it we don't think we're done reading.
931 return (this.bitCount != -1);
937 // Of all the amazing things... This MUST be Encoder so that our com name
938 // for System.Text.Encoder doesn't change
939 private class Encoder : EncoderNLS, ISerializable
941 /*private*/ internal int bits;
942 /*private*/ internal int bitCount;
944 public Encoder(UTF7Encoding encoding) : base(encoding)
949 // Constructor called by serialization, have to handle deserializing from Everett
950 internal Encoder(SerializationInfo info, StreamingContext context)
953 if (info==null) throw new ArgumentNullException("info");
954 Contract.EndContractBlock();
957 this.bits = (int)info.GetValue("bits", typeof(int));
958 this.bitCount = (int)info.GetValue("bitCount", typeof(int));
959 this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
962 #if FEATURE_SERIALIZATION
963 // ISerializable implementation, get data for this object
964 [System.Security.SecurityCritical] // auto-generated_required
965 void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
968 if (info==null) throw new ArgumentNullException("info");
969 Contract.EndContractBlock();
972 info.AddValue("encoding", this.m_encoding);
973 info.AddValue("bits", this.bits);
974 info.AddValue("bitCount", this.bitCount);
978 public override void Reset()
982 if (m_fallbackBuffer != null)
983 m_fallbackBuffer.Reset();
986 // Anything left in our encoder?
987 internal override bool HasState
991 return (this.bits != 0 || this.bitCount != -1);
996 // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char
997 // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback.
999 internal sealed class DecoderUTF7Fallback : DecoderFallback
1001 // Construction. Default replacement fallback uses no best fit and ? replacement string
1002 public DecoderUTF7Fallback()
1006 public override DecoderFallbackBuffer CreateFallbackBuffer()
1008 return new DecoderUTF7FallbackBuffer(this);
1011 // Maximum number of characters that this instance of this fallback could return
1012 public override int MaxCharCount
1016 // returns 1 char per bad byte
1021 public override bool Equals(Object value)
1023 DecoderUTF7Fallback that = value as DecoderUTF7Fallback;
1031 public override int GetHashCode()
1037 internal sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer
1039 // Store our default string
1040 char cFallback = (char)0;
1045 public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback)
1050 public override bool Fallback(byte[] bytesUnknown, int index)
1052 // We expect no previous fallback in our buffer
1053 Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
1054 Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
1056 // Go ahead and get our fallback
1057 cFallback = (char)bytesUnknown[0];
1059 // Any of the fallback characters can be handled except for 0
1070 public override char GetNextChar()
1075 // Note: this means that 0 in UTF7 stream will never be emitted.
1079 public override bool MovePrevious()
1086 // return true if we were allowed to do this
1087 return (iCount >= 0 && iCount <= iSize);
1090 // Return # of chars left in this fallback
1091 public override int Remaining
1095 return (iCount > 0) ? iCount : 0;
1100 [System.Security.SecuritySafeCritical] // overrides public transparent member
1101 public override unsafe void Reset()
1107 // This version just counts the fallback and doesn't actually copy anything.
1108 [System.Security.SecurityCritical] // auto-generated
1109 internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
1110 // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
1111 // array, and we might need the index, hence the byte*
1113 // We expect no previous fallback in our buffer
1114 Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
1115 if (bytes.Length != 1)
1117 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
1120 // Can't fallback a byte 0, so return for that case, 1 otherwise.
1121 return bytes[0] == 0 ? 0 : 1;