5 // Atsushi Enomoto <atsushi@ximian.com>
6 // Pablo Ruiz García <pruiz@netway.org>
8 // Copyright (C) 2005 Novell, Inc. http://www.novell.com
9 // Copyright (C) 2011 Pablo Ruiz García
12 using System.Runtime.InteropServices;
19 public abstract class MonoSafeEncoding : Encoding
21 readonly int win_code_page;
23 public MonoSafeEncoding (int codePage)
28 public MonoSafeEncoding(int codePage, int windowsCodePage)
31 win_code_page = windowsCodePage;
34 public override int WindowsCodePage {
35 get { return win_code_page != 0 ? win_code_page : base.WindowsCodePage; }
39 /// GetBytes method used internally by state-full encoders/encodings.
41 /// <param name="chars">The chars.</param>
42 /// <param name="charIndex">Index of the char.</param>
43 /// <param name="charCount">The char count.</param>
44 /// <param name="bytes">The bytes.</param>
45 /// <param name="byteIndex">Index of the byte.</param>
46 /// <param name="flush">if set to <c>true</c> [flush].</param>
47 /// <param name="encoding">The encoding class to use (or null if state-less).</param>
48 /// <returns></returns>
50 /// Only state-full encoders need to implement this method (ie. ISO-2022-JP)
52 protected virtual int GetBytesInternal(char[] chars, int charIndex, int charCount,
53 byte[] bytes, int byteIndex, bool flush, object state)
55 throw new NotImplementedException("Statefull encoding is not implemented (yet?) by this encoding class.");
58 public void HandleFallback(ref EncoderFallbackBuffer buffer,
59 char[] chars, ref int charIndex, ref int charCount,
60 byte[] bytes, ref int byteIndex, ref int byteCount, object state)
63 buffer = EncoderFallback.CreateFallbackBuffer();
65 if (charCount > 1 && (Char.IsSurrogate(chars[charIndex]) && Char.IsSurrogate(chars[charIndex + 1])))
67 buffer.Fallback (chars[charIndex], chars[charIndex + 1], charIndex);
72 buffer.Fallback (chars[charIndex], charIndex);
74 char[] tmp = new char[buffer.Remaining];
76 while (buffer.Remaining > 0)
77 tmp[idx++] = buffer.GetNextChar();
79 var len = state == null ?
80 GetBytes(tmp, 0, tmp.Length, bytes, byteIndex)
81 : GetBytesInternal(tmp, 0, tmp.Length, bytes, byteIndex, true, state);
88 public abstract class MonoSafeEncoder : Encoder
90 MonoSafeEncoding encoding;
92 public MonoSafeEncoder (MonoSafeEncoding encoding)
94 this.encoding = encoding;
97 public void HandleFallback(
98 char[] chars, ref int charIndex, ref int charCount,
99 byte[] bytes, ref int byteIndex, ref int byteCount, object state)
101 EncoderFallbackBuffer buffer = FallbackBuffer;
102 encoding.HandleFallback(ref buffer, chars, ref charIndex, ref charCount,
103 bytes, ref byteIndex, ref byteCount, state);