UTF8Encoding.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /*
  2. * UTF8Encoding.cs - Implementation of the "System.Text.UTF8Encoding" class.
  3. *
  4. * Copyright (c) 2001, 2002 Southern Storm Software, Pty Ltd
  5. * Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining
  8. * a copy of this software and associated documentation files (the "Software"),
  9. * to deal in the Software without restriction, including without limitation
  10. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. * and/or sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included
  15. * in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  21. * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  22. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. * OTHER DEALINGS IN THE SOFTWARE.
  24. */
  25. namespace System.Text
  26. {
  27. using System;
  28. using System.Runtime.InteropServices;
  29. [Serializable]
  30. [MonoLimitation ("Serialization format not compatible with .NET")]
  31. [MonoLimitation ("EncoderFallback is not handled")]
  32. [ComVisible (true)]
  33. public class UTF8Encoding : Encoding
  34. {
  35. // Magic number used by Windows for UTF-8.
  36. internal const int UTF8_CODE_PAGE = 65001;
  37. // Internal state.
  38. private bool emitIdentifier;
  39. // Constructors.
  40. public UTF8Encoding () : this (false, false) {}
  41. public UTF8Encoding (bool encoderShouldEmitUTF8Identifier)
  42. : this (encoderShouldEmitUTF8Identifier, false) {}
  43. public UTF8Encoding (bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes)
  44. : base (UTF8_CODE_PAGE)
  45. {
  46. emitIdentifier = encoderShouldEmitUTF8Identifier;
  47. if (throwOnInvalidBytes)
  48. SetFallbackInternal (null, DecoderFallback.ExceptionFallback);
  49. else
  50. SetFallbackInternal (null, DecoderFallback.StandardSafeFallback);
  51. web_name = body_name = header_name = "utf-8";
  52. encoding_name = "Unicode (UTF-8)";
  53. is_browser_save = true;
  54. is_browser_display = true;
  55. is_mail_news_display = true;
  56. is_mail_news_save = true;
  57. windows_code_page = UnicodeEncoding.UNICODE_CODE_PAGE;
  58. }
  59. #region GetByteCount()
  60. // Internal version of "GetByteCount" which can handle a rolling
  61. // state between multiple calls to this method.
  62. private static int InternalGetByteCount (char[] chars, int index, int count, ref char leftOver, bool flush)
  63. {
  64. // Validate the parameters.
  65. if (chars == null) {
  66. throw new ArgumentNullException ("chars");
  67. }
  68. if (index < 0 || index > chars.Length) {
  69. throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array"));
  70. }
  71. if (count < 0 || count > (chars.Length - index)) {
  72. throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array"));
  73. }
  74. if (index == chars.Length) {
  75. if (flush && leftOver != '\0') {
  76. // Flush the left-over surrogate pair start.
  77. leftOver = '\0';
  78. return 3;
  79. }
  80. return 0;
  81. }
  82. unsafe {
  83. fixed (char* cptr = chars) {
  84. return InternalGetByteCount (cptr + index, count, ref leftOver, flush);
  85. }
  86. }
  87. }
  88. private unsafe static int InternalGetByteCount (char* chars, int count, ref char leftOver, bool flush)
  89. {
  90. int length = 0;
  91. char* end = chars + count;
  92. while (chars < end) {
  93. if (leftOver == 0) {
  94. for (; chars < end; chars++) {
  95. if (*chars < '\x80') {
  96. ++length;
  97. } else if (*chars < '\x800') {
  98. length += 2;
  99. } else if (*chars < '\uD800' || *chars > '\uDFFF') {
  100. length += 3;
  101. } else if (*chars <= '\uDBFF') {
  102. // This is a surrogate start char, exit the inner loop only
  103. // if we don't find the complete surrogate pair.
  104. if (chars + 1 < end && chars [1] >= '\uDC00' && chars [1] <= '\uDFFF') {
  105. length += 4;
  106. chars++;
  107. continue;
  108. }
  109. leftOver = *chars;
  110. chars++;
  111. break;
  112. } else {
  113. // We have a surrogate tail without
  114. // leading surrogate. In NET_2_0 it
  115. // uses fallback. In NET_1_1 we output
  116. // wrong surrogate.
  117. length += 3;
  118. leftOver = '\0';
  119. }
  120. }
  121. } else {
  122. if (*chars >= '\uDC00' && *chars <= '\uDFFF') {
  123. // We have a correct surrogate pair.
  124. length += 4;
  125. chars++;
  126. } else {
  127. // We have a surrogate start followed by a
  128. // regular character. Technically, this is
  129. // invalid, but we have to do something.
  130. // We write out the surrogate start and then
  131. // re-visit the current character again.
  132. length += 3;
  133. }
  134. leftOver = '\0';
  135. }
  136. }
  137. if (flush) {
  138. // Flush the left-over surrogate pair start.
  139. if (leftOver != '\0') {
  140. length += 3;
  141. leftOver = '\0';
  142. }
  143. }
  144. return length;
  145. }
  146. // Get the number of bytes needed to encode a character buffer.
  147. public override int GetByteCount (char[] chars, int index, int count)
  148. {
  149. char dummy = '\0';
  150. return InternalGetByteCount (chars, index, count, ref dummy, true);
  151. }
  152. [CLSCompliant (false)]
  153. [ComVisible (false)]
  154. public unsafe override int GetByteCount (char* chars, int count)
  155. {
  156. if (chars == null)
  157. throw new ArgumentNullException ("chars");
  158. if (count == 0)
  159. return 0;
  160. char dummy = '\0';
  161. return InternalGetByteCount (chars, count, ref dummy, true);
  162. }
  163. #endregion
  164. #region GetBytes()
  165. // Internal version of "GetBytes" which can handle a rolling
  166. // state between multiple calls to this method.
  167. private static int InternalGetBytes (char[] chars, int charIndex,
  168. int charCount, byte[] bytes,
  169. int byteIndex, ref char leftOver,
  170. bool flush)
  171. {
  172. // Validate the parameters.
  173. if (chars == null) {
  174. throw new ArgumentNullException ("chars");
  175. }
  176. if (bytes == null) {
  177. throw new ArgumentNullException ("bytes");
  178. }
  179. if (charIndex < 0 || charIndex > chars.Length) {
  180. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array"));
  181. }
  182. if (charCount < 0 || charCount > (chars.Length - charIndex)) {
  183. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_Array"));
  184. }
  185. if (byteIndex < 0 || byteIndex > bytes.Length) {
  186. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  187. }
  188. if (charIndex == chars.Length) {
  189. if (flush && leftOver != '\0') {
  190. // FIXME: use EncoderFallback.
  191. //
  192. // By default it is empty, so I do nothing for now.
  193. leftOver = '\0';
  194. }
  195. return 0;
  196. }
  197. unsafe {
  198. fixed (char* cptr = chars) {
  199. if (bytes.Length == byteIndex)
  200. return InternalGetBytes (
  201. cptr + charIndex, charCount,
  202. null, 0, ref leftOver, flush);
  203. fixed (byte *bptr = bytes) {
  204. return InternalGetBytes (
  205. cptr + charIndex, charCount,
  206. bptr + byteIndex, bytes.Length - byteIndex,
  207. ref leftOver, flush);
  208. }
  209. }
  210. }
  211. }
  212. private unsafe static int InternalGetBytes (char* chars, int count, byte* bytes, int bcount, ref char leftOver, bool flush)
  213. {
  214. char* end = chars + count;
  215. byte* end_bytes = bytes + bcount;
  216. while (chars < end) {
  217. if (leftOver == 0) {
  218. for (; chars < end; chars++) {
  219. int ch = *chars;
  220. if (ch < '\x80') {
  221. if (bytes >= end_bytes)
  222. goto fail_no_space;
  223. *bytes++ = (byte)ch;
  224. } else if (ch < '\x800') {
  225. if (bytes + 1 >= end_bytes)
  226. goto fail_no_space;
  227. bytes [0] = (byte) (0xC0 | (ch >> 6));
  228. bytes [1] = (byte) (0x80 | (ch & 0x3F));
  229. bytes += 2;
  230. } else if (ch < '\uD800' || ch > '\uDFFF') {
  231. if (bytes + 2 >= end_bytes)
  232. goto fail_no_space;
  233. bytes [0] = (byte) (0xE0 | (ch >> 12));
  234. bytes [1] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  235. bytes [2] = (byte) (0x80 | (ch & 0x3F));
  236. bytes += 3;
  237. } else if (ch <= '\uDBFF') {
  238. // This is a surrogate char, exit the inner loop.
  239. leftOver = *chars;
  240. chars++;
  241. break;
  242. } else {
  243. // We have a surrogate tail without
  244. // leading surrogate. In NET_2_0 it
  245. // uses fallback. In NET_1_1 we output
  246. // wrong surrogate.
  247. if (bytes + 2 >= end_bytes)
  248. goto fail_no_space;
  249. bytes [0] = (byte) (0xE0 | (ch >> 12));
  250. bytes [1] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  251. bytes [2] = (byte) (0x80 | (ch & 0x3F));
  252. bytes += 3;
  253. leftOver = '\0';
  254. }
  255. }
  256. } else {
  257. if (*chars >= '\uDC00' && *chars <= '\uDFFF') {
  258. // We have a correct surrogate pair.
  259. int ch = 0x10000 + (int) *chars - 0xDC00 + (((int) leftOver - 0xD800) << 10);
  260. if (bytes + 3 >= end_bytes)
  261. goto fail_no_space;
  262. bytes [0] = (byte) (0xF0 | (ch >> 18));
  263. bytes [1] = (byte) (0x80 | ((ch >> 12) & 0x3F));
  264. bytes [2] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  265. bytes [3] = (byte) (0x80 | (ch & 0x3F));
  266. bytes += 4;
  267. chars++;
  268. } else {
  269. // We have a surrogate start followed by a
  270. // regular character. Technically, this is
  271. // invalid, but we have to do something.
  272. // We write out the surrogate start and then
  273. // re-visit the current character again.
  274. int ch = leftOver;
  275. if (bytes + 2 >= end_bytes)
  276. goto fail_no_space;
  277. bytes [0] = (byte) (0xE0 | (ch >> 12));
  278. bytes [1] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  279. bytes [2] = (byte) (0x80 | (ch & 0x3F));
  280. bytes += 3;
  281. }
  282. leftOver = '\0';
  283. }
  284. }
  285. if (flush) {
  286. // Flush the left-over surrogate pair start.
  287. if (leftOver != '\0') {
  288. int ch = leftOver;
  289. if (bytes + 2 < end_bytes) {
  290. bytes [0] = (byte) (0xE0 | (ch >> 12));
  291. bytes [1] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  292. bytes [2] = (byte) (0x80 | (ch & 0x3F));
  293. bytes += 3;
  294. } else {
  295. goto fail_no_space;
  296. }
  297. leftOver = '\0';
  298. }
  299. }
  300. return (int)(bytes - (end_bytes - bcount));
  301. fail_no_space:
  302. throw new ArgumentException ("Insufficient Space", "bytes");
  303. }
  304. // Get the bytes that result from encoding a character buffer.
  305. public override int GetBytes (char[] chars, int charIndex, int charCount,
  306. byte[] bytes, int byteIndex)
  307. {
  308. char leftOver = '\0';
  309. return InternalGetBytes (chars, charIndex, charCount, bytes, byteIndex, ref leftOver, true);
  310. }
  311. // Convenience wrappers for "GetBytes".
  312. public override int GetBytes (String s, int charIndex, int charCount,
  313. byte[] bytes, int byteIndex)
  314. {
  315. // Validate the parameters.
  316. if (s == null) {
  317. throw new ArgumentNullException ("s");
  318. }
  319. if (bytes == null) {
  320. throw new ArgumentNullException ("bytes");
  321. }
  322. if (charIndex < 0 || charIndex > s.Length) {
  323. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_StringIndex"));
  324. }
  325. if (charCount < 0 || charCount > (s.Length - charIndex)) {
  326. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_StringRange"));
  327. }
  328. if (byteIndex < 0 || byteIndex > bytes.Length) {
  329. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  330. }
  331. if (charIndex == s.Length)
  332. return 0;
  333. unsafe {
  334. fixed (char* cptr = s) {
  335. char dummy = '\0';
  336. if (bytes.Length == byteIndex)
  337. return InternalGetBytes (
  338. cptr + charIndex, charCount,
  339. null, 0, ref dummy, true);
  340. fixed (byte *bptr = bytes) {
  341. return InternalGetBytes (
  342. cptr + charIndex, charCount,
  343. bptr + byteIndex, bytes.Length - byteIndex,
  344. ref dummy, true);
  345. }
  346. }
  347. }
  348. }
  349. [CLSCompliant (false)]
  350. [ComVisible (false)]
  351. public unsafe override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount)
  352. {
  353. if (chars == null)
  354. throw new ArgumentNullException ("chars");
  355. if (charCount < 0)
  356. throw new IndexOutOfRangeException ("charCount");
  357. if (bytes == null)
  358. throw new ArgumentNullException ("bytes");
  359. if (byteCount < 0)
  360. throw new IndexOutOfRangeException ("charCount");
  361. if (charCount == 0)
  362. return 0;
  363. char dummy = '\0';
  364. if (byteCount == 0)
  365. return InternalGetBytes (chars, charCount, null, 0, ref dummy, true);
  366. else
  367. return InternalGetBytes (chars, charCount, bytes, byteCount, ref dummy, true);
  368. }
  369. #endregion
  370. // Internal version of "GetCharCount" which can handle a rolling
  371. // state between multiple calls to this method.
  372. private unsafe static int InternalGetCharCount (
  373. byte[] bytes, int index, int count, uint leftOverBits,
  374. uint leftOverCount, object provider,
  375. ref DecoderFallbackBuffer fallbackBuffer, ref byte [] bufferArg, bool flush)
  376. {
  377. // Validate the parameters.
  378. if (bytes == null) {
  379. throw new ArgumentNullException ("bytes");
  380. }
  381. if (index < 0 || index > bytes.Length) {
  382. throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array"));
  383. }
  384. if (count < 0 || count > (bytes.Length - index)) {
  385. throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array"));
  386. }
  387. if (count == 0)
  388. return 0;
  389. fixed (byte *bptr = bytes)
  390. return InternalGetCharCount (bptr + index, count,
  391. leftOverBits, leftOverCount, provider, ref fallbackBuffer, ref bufferArg, flush);
  392. }
  393. private unsafe static int InternalGetCharCount (
  394. byte* bytes, int count, uint leftOverBits,
  395. uint leftOverCount, object provider,
  396. ref DecoderFallbackBuffer fallbackBuffer, ref byte [] bufferArg, bool flush)
  397. {
  398. int index = 0;
  399. int length = 0;
  400. if (leftOverCount == 0) {
  401. int end = index + count;
  402. for (; index < end; index++, count--) {
  403. if (bytes [index] < 0x80)
  404. length++;
  405. else
  406. break;
  407. }
  408. }
  409. // Determine the number of characters that we have.
  410. uint ch;
  411. uint leftBits = leftOverBits;
  412. uint leftSoFar = (leftOverCount & (uint)0x0F);
  413. uint leftSize = ((leftOverCount >> 4) & (uint)0x0F);
  414. while (count > 0) {
  415. ch = (uint)(bytes[index++]);
  416. --count;
  417. if (leftSize == 0) {
  418. // Process a UTF-8 start character.
  419. if (ch < (uint)0x0080) {
  420. // Single-byte UTF-8 character.
  421. ++length;
  422. } else if ((ch & (uint)0xE0) == (uint)0xC0) {
  423. // Double-byte UTF-8 character.
  424. leftBits = (ch & (uint)0x1F);
  425. leftSoFar = 1;
  426. leftSize = 2;
  427. } else if ((ch & (uint)0xF0) == (uint)0xE0) {
  428. // Three-byte UTF-8 character.
  429. leftBits = (ch & (uint)0x0F);
  430. leftSoFar = 1;
  431. leftSize = 3;
  432. } else if ((ch & (uint)0xF8) == (uint)0xF0) {
  433. // Four-byte UTF-8 character.
  434. leftBits = (ch & (uint)0x07);
  435. leftSoFar = 1;
  436. leftSize = 4;
  437. } else if ((ch & (uint)0xFC) == (uint)0xF8) {
  438. // Five-byte UTF-8 character.
  439. leftBits = (ch & (uint)0x03);
  440. leftSoFar = 1;
  441. leftSize = 5;
  442. } else if ((ch & (uint)0xFE) == (uint)0xFC) {
  443. // Six-byte UTF-8 character.
  444. leftBits = (ch & (uint)0x03);
  445. leftSoFar = 1;
  446. leftSize = 6;
  447. } else {
  448. // Invalid UTF-8 start character.
  449. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - 1, 1);
  450. }
  451. } else {
  452. // Process an extra byte in a multi-byte sequence.
  453. if ((ch & (uint)0xC0) == (uint)0x80) {
  454. leftBits = ((leftBits << 6) | (ch & (uint)0x3F));
  455. if (++leftSoFar >= leftSize) {
  456. // We have a complete character now.
  457. if (leftBits < (uint)0x10000) {
  458. // is it an overlong ?
  459. bool overlong = false;
  460. switch (leftSize) {
  461. case 2:
  462. overlong = (leftBits <= 0x7F);
  463. break;
  464. case 3:
  465. overlong = (leftBits <= 0x07FF);
  466. break;
  467. case 4:
  468. overlong = (leftBits <= 0xFFFF);
  469. break;
  470. case 5:
  471. overlong = (leftBits <= 0x1FFFFF);
  472. break;
  473. case 6:
  474. overlong = (leftBits <= 0x03FFFFFF);
  475. break;
  476. }
  477. if (overlong) {
  478. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - leftSoFar, leftSoFar);
  479. }
  480. else if ((leftBits & 0xF800) == 0xD800) {
  481. // UTF-8 doesn't use surrogate characters
  482. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - leftSoFar, leftSoFar);
  483. }
  484. else
  485. ++length;
  486. } else if (leftBits < (uint)0x110000) {
  487. length += 2;
  488. } else {
  489. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - leftSoFar, leftSoFar);
  490. }
  491. leftSize = 0;
  492. }
  493. } else {
  494. // Invalid UTF-8 sequence: clear and restart.
  495. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - leftSoFar, leftSoFar);
  496. leftSize = 0;
  497. --index;
  498. ++count;
  499. }
  500. }
  501. }
  502. if (flush && leftSize != 0) {
  503. // We had left-over bytes that didn't make up
  504. // a complete UTF-8 character sequence.
  505. length += Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, index - leftSoFar, leftSoFar);
  506. }
  507. // Return the final length to the caller.
  508. return length;
  509. }
  510. // for GetCharCount()
  511. static unsafe int Fallback (object provider, ref DecoderFallbackBuffer buffer, ref byte [] bufferArg, byte* bytes, long index, uint size)
  512. {
  513. if (buffer == null) {
  514. DecoderFallback fb = provider as DecoderFallback;
  515. if (fb != null)
  516. buffer = fb.CreateFallbackBuffer ();
  517. else
  518. buffer = ((Decoder) provider).FallbackBuffer;
  519. }
  520. if (bufferArg == null)
  521. bufferArg = new byte [1];
  522. int ret = 0;
  523. for (int i = 0; i < size; i++) {
  524. bufferArg [0] = bytes [(int) index + i];
  525. buffer.Fallback (bufferArg, 0);
  526. ret += buffer.Remaining;
  527. buffer.Reset ();
  528. }
  529. return ret;
  530. }
  531. // for GetChars()
  532. static unsafe void Fallback (object provider, ref DecoderFallbackBuffer buffer, ref byte [] bufferArg, byte* bytes, long byteIndex, uint size,
  533. char* chars, ref int charIndex)
  534. {
  535. if (buffer == null) {
  536. DecoderFallback fb = provider as DecoderFallback;
  537. if (fb != null)
  538. buffer = fb.CreateFallbackBuffer ();
  539. else
  540. buffer = ((Decoder) provider).FallbackBuffer;
  541. }
  542. if (bufferArg == null)
  543. bufferArg = new byte [1];
  544. for (int i = 0; i < size; i++) {
  545. bufferArg [0] = bytes [byteIndex + i];
  546. buffer.Fallback (bufferArg, 0);
  547. while (buffer.Remaining > 0)
  548. chars [charIndex++] = buffer.GetNextChar ();
  549. buffer.Reset ();
  550. }
  551. }
  552. // Get the number of characters needed to decode a byte buffer.
  553. public override int GetCharCount (byte[] bytes, int index, int count)
  554. {
  555. DecoderFallbackBuffer buf = null;
  556. byte [] bufferArg = null;
  557. return InternalGetCharCount (bytes, index, count, 0, 0, DecoderFallback, ref buf, ref bufferArg, true);
  558. }
  559. [CLSCompliant (false)]
  560. [ComVisible (false)]
  561. public unsafe override int GetCharCount (byte* bytes, int count)
  562. {
  563. DecoderFallbackBuffer buf = null;
  564. byte [] bufferArg = null;
  565. return InternalGetCharCount (bytes, count, 0, 0, DecoderFallback, ref buf, ref bufferArg, true);
  566. }
  567. // Get the characters that result from decoding a byte buffer.
  568. private unsafe static int InternalGetChars (
  569. byte[] bytes, int byteIndex, int byteCount, char[] chars,
  570. int charIndex, ref uint leftOverBits, ref uint leftOverCount,
  571. object provider,
  572. ref DecoderFallbackBuffer fallbackBuffer, ref byte [] bufferArg, bool flush)
  573. {
  574. // Validate the parameters.
  575. if (bytes == null) {
  576. throw new ArgumentNullException ("bytes");
  577. }
  578. if (chars == null) {
  579. throw new ArgumentNullException ("chars");
  580. }
  581. if (byteIndex < 0 || byteIndex > bytes.Length) {
  582. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  583. }
  584. if (byteCount < 0 || byteCount > (bytes.Length - byteIndex)) {
  585. throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_Array"));
  586. }
  587. if (charIndex < 0 || charIndex > chars.Length) {
  588. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array"));
  589. }
  590. if (charIndex == chars.Length)
  591. return 0;
  592. fixed (char* cptr = chars) {
  593. if (byteCount == 0 || byteIndex == bytes.Length)
  594. return InternalGetChars (null, 0, cptr + charIndex, chars.Length - charIndex, ref leftOverBits, ref leftOverCount, provider, ref fallbackBuffer, ref bufferArg, flush);
  595. // otherwise...
  596. fixed (byte* bptr = bytes)
  597. return InternalGetChars (bptr + byteIndex, byteCount, cptr + charIndex, chars.Length - charIndex, ref leftOverBits, ref leftOverCount, provider, ref fallbackBuffer, ref bufferArg, flush);
  598. }
  599. }
  600. private unsafe static int InternalGetChars (
  601. byte* bytes, int byteCount, char* chars, int charCount,
  602. ref uint leftOverBits, ref uint leftOverCount,
  603. object provider,
  604. ref DecoderFallbackBuffer fallbackBuffer, ref byte [] bufferArg, bool flush)
  605. {
  606. int charIndex = 0, byteIndex = 0;
  607. int length = charCount;
  608. int posn = charIndex;
  609. if (leftOverCount == 0) {
  610. int end = byteIndex + byteCount;
  611. for (; byteIndex < end; posn++, byteIndex++, byteCount--) {
  612. if (bytes [byteIndex] < 0x80)
  613. chars [posn] = (char) bytes [byteIndex];
  614. else
  615. break;
  616. }
  617. }
  618. // Convert the bytes into the output buffer.
  619. uint ch;
  620. uint leftBits = leftOverBits;
  621. uint leftSoFar = (leftOverCount & (uint)0x0F);
  622. uint leftSize = ((leftOverCount >> 4) & (uint)0x0F);
  623. int byteEnd = byteIndex + byteCount;
  624. for(; byteIndex < byteEnd; byteIndex++) {
  625. // Fetch the next character from the byte buffer.
  626. ch = (uint)(bytes[byteIndex]);
  627. if (leftSize == 0) {
  628. // Process a UTF-8 start character.
  629. if (ch < (uint)0x0080) {
  630. // Single-byte UTF-8 character.
  631. if (posn >= length) {
  632. throw new ArgumentException (_("Arg_InsufficientSpace"), "chars");
  633. }
  634. chars[posn++] = (char)ch;
  635. } else if ((ch & (uint)0xE0) == (uint)0xC0) {
  636. // Double-byte UTF-8 character.
  637. leftBits = (ch & (uint)0x1F);
  638. leftSoFar = 1;
  639. leftSize = 2;
  640. } else if ((ch & (uint)0xF0) == (uint)0xE0) {
  641. // Three-byte UTF-8 character.
  642. leftBits = (ch & (uint)0x0F);
  643. leftSoFar = 1;
  644. leftSize = 3;
  645. } else if ((ch & (uint)0xF8) == (uint)0xF0) {
  646. // Four-byte UTF-8 character.
  647. leftBits = (ch & (uint)0x07);
  648. leftSoFar = 1;
  649. leftSize = 4;
  650. } else if ((ch & (uint)0xFC) == (uint)0xF8) {
  651. // Five-byte UTF-8 character.
  652. leftBits = (ch & (uint)0x03);
  653. leftSoFar = 1;
  654. leftSize = 5;
  655. } else if ((ch & (uint)0xFE) == (uint)0xFC) {
  656. // Six-byte UTF-8 character.
  657. leftBits = (ch & (uint)0x03);
  658. leftSoFar = 1;
  659. leftSize = 6;
  660. } else {
  661. // Invalid UTF-8 start character.
  662. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex, 1, chars, ref posn);
  663. }
  664. } else {
  665. // Process an extra byte in a multi-byte sequence.
  666. if ((ch & (uint)0xC0) == (uint)0x80) {
  667. leftBits = ((leftBits << 6) | (ch & (uint)0x3F));
  668. if (++leftSoFar >= leftSize) {
  669. // We have a complete character now.
  670. if (leftBits < (uint)0x10000) {
  671. // is it an overlong ?
  672. bool overlong = false;
  673. switch (leftSize) {
  674. case 2:
  675. overlong = (leftBits <= 0x7F);
  676. break;
  677. case 3:
  678. overlong = (leftBits <= 0x07FF);
  679. break;
  680. case 4:
  681. overlong = (leftBits <= 0xFFFF);
  682. break;
  683. case 5:
  684. overlong = (leftBits <= 0x1FFFFF);
  685. break;
  686. case 6:
  687. overlong = (leftBits <= 0x03FFFFFF);
  688. break;
  689. }
  690. if (overlong) {
  691. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex - leftSoFar, leftSoFar, chars, ref posn);
  692. }
  693. else if ((leftBits & 0xF800) == 0xD800) {
  694. // UTF-8 doesn't use surrogate characters
  695. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex - leftSoFar, leftSoFar, chars, ref posn);
  696. }
  697. else {
  698. if (posn >= length) {
  699. throw new ArgumentException
  700. (_("Arg_InsufficientSpace"), "chars");
  701. }
  702. chars[posn++] = (char)leftBits;
  703. }
  704. } else if (leftBits < (uint)0x110000) {
  705. if ((posn + 2) > length) {
  706. throw new ArgumentException
  707. (_("Arg_InsufficientSpace"), "chars");
  708. }
  709. leftBits -= (uint)0x10000;
  710. chars[posn++] = (char)((leftBits >> 10) +
  711. (uint)0xD800);
  712. chars[posn++] =
  713. (char)((leftBits & (uint)0x3FF) + (uint)0xDC00);
  714. } else {
  715. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex - leftSoFar, leftSoFar, chars, ref posn);
  716. }
  717. leftSize = 0;
  718. }
  719. } else {
  720. // Invalid UTF-8 sequence: clear and restart.
  721. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex - leftSoFar, leftSoFar, chars, ref posn);
  722. leftSize = 0;
  723. --byteIndex;
  724. }
  725. }
  726. }
  727. if (flush && leftSize != 0) {
  728. // We had left-over bytes that didn't make up
  729. // a complete UTF-8 character sequence.
  730. Fallback (provider, ref fallbackBuffer, ref bufferArg, bytes, byteIndex - leftSoFar, leftSoFar, chars, ref posn);
  731. }
  732. leftOverBits = leftBits;
  733. leftOverCount = (leftSoFar | (leftSize << 4));
  734. // Return the final length to the caller.
  735. return posn - charIndex;
  736. }
  737. // Get the characters that result from decoding a byte buffer.
  738. public override int GetChars (byte[] bytes, int byteIndex, int byteCount,
  739. char[] chars, int charIndex)
  740. {
  741. uint leftOverBits = 0;
  742. uint leftOverCount = 0;
  743. DecoderFallbackBuffer buf = null;
  744. byte [] bufferArg = null;
  745. return InternalGetChars (bytes, byteIndex, byteCount, chars,
  746. charIndex, ref leftOverBits, ref leftOverCount, DecoderFallback, ref buf, ref bufferArg, true);
  747. }
  748. [CLSCompliant (false)]
  749. [ComVisible (false)]
  750. public unsafe override int GetChars (byte* bytes, int byteCount, char* chars, int charCount)
  751. {
  752. DecoderFallbackBuffer buf = null;
  753. byte [] bufferArg = null;
  754. uint leftOverBits = 0;
  755. uint leftOverCount = 0;
  756. return InternalGetChars (bytes, byteCount, chars,
  757. charCount, ref leftOverBits, ref leftOverCount, DecoderFallback, ref buf, ref bufferArg, true);
  758. }
  759. // Get the maximum number of bytes needed to encode a
  760. // specified number of characters.
  761. public override int GetMaxByteCount (int charCount)
  762. {
  763. if (charCount < 0) {
  764. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_NonNegative"));
  765. }
  766. return charCount * 4;
  767. }
  768. // Get the maximum number of characters needed to decode a
  769. // specified number of bytes.
  770. public override int GetMaxCharCount (int byteCount)
  771. {
  772. if (byteCount < 0) {
  773. throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_NonNegative"));
  774. }
  775. return byteCount;
  776. }
  777. // Get a UTF8-specific decoder that is attached to this instance.
  778. public override Decoder GetDecoder ()
  779. {
  780. return new UTF8Decoder (DecoderFallback);
  781. }
  782. // Get a UTF8-specific encoder that is attached to this instance.
  783. public override Encoder GetEncoder ()
  784. {
  785. return new UTF8Encoder (emitIdentifier);
  786. }
  787. // Get the UTF8 preamble.
  788. public override byte[] GetPreamble ()
  789. {
  790. if (emitIdentifier)
  791. return new byte [] { 0xEF, 0xBB, 0xBF };
  792. return new byte [0];
  793. }
  794. // Determine if this object is equal to another.
  795. public override bool Equals (Object value)
  796. {
  797. UTF8Encoding enc = (value as UTF8Encoding);
  798. if (enc != null) {
  799. return (codePage == enc.codePage &&
  800. emitIdentifier == enc.emitIdentifier &&
  801. DecoderFallback.Equals (enc.DecoderFallback) &&
  802. EncoderFallback.Equals (enc.EncoderFallback));
  803. } else {
  804. return false;
  805. }
  806. }
  807. // Get the hash code for this object.
  808. public override int GetHashCode ()
  809. {
  810. return base.GetHashCode ();
  811. }
  812. public override int GetByteCount (string chars)
  813. {
  814. // hmm, does this override make any sense?
  815. return base.GetByteCount (chars);
  816. }
  817. [ComVisible (false)]
  818. public override string GetString (byte [] bytes, int index, int count)
  819. {
  820. // hmm, does this override make any sense?
  821. return base.GetString (bytes, index, count);
  822. }
  823. // UTF-8 decoder implementation.
  824. [Serializable]
  825. private class UTF8Decoder : Decoder
  826. {
  827. private uint leftOverBits;
  828. private uint leftOverCount;
  829. // Constructor.
  830. public UTF8Decoder (DecoderFallback fallback)
  831. {
  832. Fallback = fallback;
  833. leftOverBits = 0;
  834. leftOverCount = 0;
  835. }
  836. // Override inherited methods.
  837. public override int GetCharCount (byte[] bytes, int index, int count)
  838. {
  839. DecoderFallbackBuffer buf = null;
  840. byte [] bufferArg = null;
  841. return InternalGetCharCount (bytes, index, count,
  842. leftOverBits, leftOverCount, this, ref buf, ref bufferArg, false);
  843. }
  844. public override int GetChars (byte[] bytes, int byteIndex,
  845. int byteCount, char[] chars, int charIndex)
  846. {
  847. DecoderFallbackBuffer buf = null;
  848. byte [] bufferArg = null;
  849. return InternalGetChars (bytes, byteIndex, byteCount,
  850. chars, charIndex, ref leftOverBits, ref leftOverCount, this, ref buf, ref bufferArg, false);
  851. }
  852. } // class UTF8Decoder
  853. // UTF-8 encoder implementation.
  854. [Serializable]
  855. private class UTF8Encoder : Encoder
  856. {
  857. // private bool emitIdentifier;
  858. private char leftOverForCount;
  859. private char leftOverForConv;
  860. // Constructor.
  861. public UTF8Encoder (bool emitIdentifier)
  862. {
  863. // this.emitIdentifier = emitIdentifier;
  864. leftOverForCount = '\0';
  865. leftOverForConv = '\0';
  866. }
  867. // Override inherited methods.
  868. public override int GetByteCount (char[] chars, int index,
  869. int count, bool flush)
  870. {
  871. return InternalGetByteCount (chars, index, count, ref leftOverForCount, flush);
  872. }
  873. public override int GetBytes (char[] chars, int charIndex,
  874. int charCount, byte[] bytes, int byteIndex, bool flush)
  875. {
  876. int result;
  877. result = InternalGetBytes (chars, charIndex, charCount, bytes, byteIndex, ref leftOverForConv, flush);
  878. // emitIdentifier = false;
  879. return result;
  880. }
  881. public unsafe override int GetByteCount (char* chars, int count, bool flush)
  882. {
  883. return InternalGetByteCount (chars, count, ref leftOverForCount, flush);
  884. }
  885. public unsafe override int GetBytes (char* chars, int charCount,
  886. byte* bytes, int byteCount, bool flush)
  887. {
  888. int result;
  889. result = InternalGetBytes (chars, charCount, bytes, byteCount, ref leftOverForConv, flush);
  890. // emitIdentifier = false;
  891. return result;
  892. }
  893. } // class UTF8Encoder
  894. }; // class UTF8Encoding
  895. }; // namespace System.Text