UTF8Encoding.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. [Serializable]
  29. [MonoTODO ("Fix serialization compatibility with MS.NET")]
  30. #if NET_2_0
  31. [MonoTODO ("EncoderFallback is not handled")]
  32. #endif
  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. #if !NET_2_0
  40. private bool throwOnInvalid;
  41. #endif
  42. // Constructors.
  43. public UTF8Encoding () : this (false, false) {}
  44. public UTF8Encoding (bool encoderShouldEmitUTF8Identifier)
  45. : this (encoderShouldEmitUTF8Identifier, false) {}
  46. public UTF8Encoding (bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes)
  47. : base (UTF8_CODE_PAGE)
  48. {
  49. emitIdentifier = encoderShouldEmitUTF8Identifier;
  50. #if NET_2_0
  51. if (throwOnInvalidBytes)
  52. SetFallbackInternal (null, new DecoderExceptionFallback ());
  53. else
  54. SetFallbackInternal (null, new DecoderReplacementFallback (String.Empty));
  55. #else
  56. throwOnInvalid = throwOnInvalidBytes;
  57. #endif
  58. web_name = body_name = header_name = "utf-8";
  59. encoding_name = "Unicode (UTF-8)";
  60. is_browser_save = true;
  61. is_browser_display = true;
  62. is_mail_news_display = true;
  63. windows_code_page = UnicodeEncoding.UNICODE_CODE_PAGE;
  64. }
  65. #region GetByteCount()
  66. // Internal version of "GetByteCount" which can handle a rolling
  67. // state between multiple calls to this method.
  68. private static int InternalGetByteCount (char[] chars, int index, int count, ref char leftOver, bool flush)
  69. {
  70. // Validate the parameters.
  71. if (chars == null) {
  72. throw new ArgumentNullException ("chars");
  73. }
  74. if (index < 0 || index > chars.Length) {
  75. throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array"));
  76. }
  77. if (count < 0 || count > (chars.Length - index)) {
  78. throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array"));
  79. }
  80. if (index == chars.Length) {
  81. if (flush && leftOver != '\0') {
  82. // Flush the left-over surrogate pair start.
  83. leftOver = '\0';
  84. return 3;
  85. }
  86. return 0;
  87. }
  88. unsafe {
  89. fixed (char* cptr = chars) {
  90. return InternalGetByteCount (cptr + index, count, ref leftOver, flush);
  91. }
  92. }
  93. }
  94. private unsafe static int InternalGetByteCount (char* chars, int count, ref char leftOver, bool flush)
  95. {
  96. int index = 0;
  97. // Determine the lengths of all characters.
  98. char ch;
  99. int length = 0;
  100. char pair = leftOver;
  101. while (count > 0) {
  102. ch = chars[index];
  103. if (pair == 0) {
  104. if (ch < '\u0080') {
  105. // fast path optimization
  106. int end = index + count;
  107. for (; index < end; index++, count--) {
  108. if (chars [index] < '\x80')
  109. ++length;
  110. else
  111. break;
  112. }
  113. continue;
  114. //length++;
  115. } else if (ch < '\u0800') {
  116. length += 2;
  117. } else if (ch >= '\uD800' && ch <= '\uDBFF') {
  118. // This is the start of a surrogate pair.
  119. pair = ch;
  120. } else {
  121. length += 3;
  122. }
  123. } else if (ch >= '\uDC00' && ch <= '\uDFFF') {
  124. if (pair != 0) {
  125. // We have a surrogate pair.
  126. length += 4;
  127. pair = '\0';
  128. } else {
  129. // We have a surrogate tail without
  130. // leading surrogate. In NET_2_0 it
  131. // uses fallback. In NET_1_1 we output
  132. // wrong surrogate.
  133. length += 3;
  134. pair = '\0';
  135. }
  136. } else {
  137. // We have a surrogate start followed by a
  138. // regular character. Technically, this is
  139. // invalid, but we have to do something.
  140. // We write out the surrogate start and then
  141. // re-visit the current character again.
  142. length += 3;
  143. pair = '\0';
  144. continue;
  145. }
  146. ++index;
  147. --count;
  148. }
  149. if (flush) {
  150. if (pair != '\0')
  151. // Flush the left-over surrogate pair start.
  152. length += 3;
  153. leftOver = '\0';
  154. }
  155. else
  156. leftOver = pair;
  157. // Return the final length to the caller.
  158. return length;
  159. }
  160. // Get the number of bytes needed to encode a character buffer.
  161. public override int GetByteCount (char[] chars, int index, int count)
  162. {
  163. char dummy = '\0';
  164. return InternalGetByteCount (chars, index, count, ref dummy, true);
  165. }
  166. // Convenience wrappers for "GetByteCount".
  167. public override int GetByteCount (String s)
  168. {
  169. // Validate the parameters.
  170. if (s == null) {
  171. throw new ArgumentNullException ("s");
  172. }
  173. unsafe {
  174. fixed (char* cptr = s) {
  175. char dummy = '\0';
  176. return InternalGetByteCount (cptr, s.Length, ref dummy, true);
  177. }
  178. }
  179. }
  180. #endregion
  181. #region GetBytes()
  182. // Internal version of "GetBytes" which can handle a rolling
  183. // state between multiple calls to this method.
  184. private static int InternalGetBytes (char[] chars, int charIndex,
  185. int charCount, byte[] bytes,
  186. int byteIndex, ref char leftOver,
  187. bool flush)
  188. {
  189. // Validate the parameters.
  190. if (chars == null) {
  191. throw new ArgumentNullException ("chars");
  192. }
  193. if (bytes == null) {
  194. throw new ArgumentNullException ("bytes");
  195. }
  196. if (charIndex < 0 || charIndex > chars.Length) {
  197. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array"));
  198. }
  199. if (charCount < 0 || charCount > (chars.Length - charIndex)) {
  200. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_Array"));
  201. }
  202. if (byteIndex < 0 || byteIndex > bytes.Length) {
  203. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  204. }
  205. if (charIndex == chars.Length) {
  206. if (flush && leftOver != '\0') {
  207. #if NET_2_0
  208. // FIXME: use EncoderFallback.
  209. //
  210. // By default it is empty, so I do nothing for now.
  211. leftOver = '\0';
  212. #else
  213. // Flush the left-over surrogate pair start.
  214. if (byteIndex + 3 >= bytes.Length)
  215. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  216. bytes [byteIndex++] = 0xEF;
  217. bytes [byteIndex++] = 0xBB;
  218. bytes [byteIndex++] = 0xBF;
  219. leftOver = '\0';
  220. return 3;
  221. #endif
  222. }
  223. return 0;
  224. }
  225. unsafe {
  226. fixed (char* cptr = chars) {
  227. if (bytes.Length == byteIndex)
  228. return InternalGetBytes (
  229. cptr + charIndex, charCount,
  230. null, 0, ref leftOver, flush);
  231. fixed (byte *bptr = bytes) {
  232. return InternalGetBytes (
  233. cptr + charIndex, charCount,
  234. bptr + byteIndex, bytes.Length - byteIndex,
  235. ref leftOver, flush);
  236. }
  237. }
  238. }
  239. }
  240. private unsafe static int InternalGetBytes (char* chars, int charCount,
  241. byte* bytes, int byteCount,
  242. ref char leftOver, bool flush)
  243. {
  244. int charIndex = 0;
  245. int byteIndex = 0;
  246. // Convert the characters into bytes.
  247. // Convert the characters into bytes.
  248. char ch;
  249. int length = byteCount;
  250. char pair = leftOver;
  251. int posn = byteIndex;
  252. int code = 0;
  253. while (charCount > 0) {
  254. // Fetch the next UTF-16 character pair value.
  255. ch = chars [charIndex];
  256. if (pair == '\0') {
  257. if (ch < '\uD800' || ch >= '\uE000') {
  258. if (ch < '\x80') { // fast path optimization
  259. int end = charIndex + charCount;
  260. for (; charIndex < end; posn++, charIndex++, charCount--) {
  261. if (chars [charIndex] < '\x80')
  262. bytes [posn] = (byte) chars [charIndex];
  263. else
  264. break;
  265. }
  266. continue;
  267. }
  268. code = ch;
  269. }
  270. else if (ch < '\uDC00') {
  271. // surrogate start
  272. pair = ch;
  273. ++charIndex;
  274. --charCount;
  275. continue;
  276. } else { // ch <= '\uDFFF'
  277. // We have a surrogate tail without leading
  278. // surrogate. In NET_2_0 it uses fallback.
  279. // In NET_1_1 we output wrong surrogate.
  280. if ((posn + 3) > length) {
  281. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  282. }
  283. bytes [posn++] = (byte) (0xE0 | (ch >> 12));
  284. bytes [posn++] = (byte) (0x80 | ((ch >> 6) & 0x3F));
  285. bytes [posn++] = (byte) (0x80 | (ch & 0x3F));
  286. ++charIndex;
  287. --charCount;
  288. continue;
  289. }
  290. } else {
  291. if ('\uDC00' <= ch && ch <= '\uDFFF')
  292. code = 0x10000 + (int) ch - 0xDC00 +
  293. (((int) pair - 0xD800) << 10);
  294. else {
  295. // We have a surrogate start followed by a
  296. // regular character. Technically, this is
  297. // invalid, but we have to do something.
  298. // We write out the surrogate start and then
  299. // re-visit the current character again.
  300. if ((posn + 3) > length) {
  301. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  302. }
  303. bytes [posn++] = (byte) (0xE0 | (pair >> 12));
  304. bytes [posn++] = (byte) (0x80 | ((pair >> 6) & 0x3F));
  305. bytes [posn++] = (byte) (0x80 | (pair & 0x3F));
  306. pair = '\0';
  307. continue;
  308. }
  309. pair = '\0';
  310. }
  311. ++charIndex;
  312. --charCount;
  313. // Encode the character pair value.
  314. if (code < 0x0080) {
  315. if (posn >= length)
  316. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  317. bytes [posn++] = (byte)code;
  318. } else if (code < 0x0800) {
  319. if ((posn + 2) > length)
  320. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  321. bytes [posn++] = (byte) (0xC0 | (code >> 6));
  322. bytes [posn++] = (byte) (0x80 | (code & 0x3F));
  323. } else if (code < 0x10000) {
  324. if ((posn + 3) > length)
  325. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  326. bytes [posn++] = (byte) (0xE0 | (code >> 12));
  327. bytes [posn++] = (byte) (0x80 | ((code >> 6) & 0x3F));
  328. bytes [posn++] = (byte) (0x80 | (code & 0x3F));
  329. } else {
  330. if ((posn + 4) > length)
  331. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  332. bytes [posn++] = (byte) (0xF0 | (code >> 18));
  333. bytes [posn++] = (byte) (0x80 | ((code >> 12) & 0x3F));
  334. bytes [posn++] = (byte) (0x80 | ((code >> 6) & 0x3F));
  335. bytes [posn++] = (byte) (0x80 | (code & 0x3F));
  336. }
  337. }
  338. if (flush) {
  339. if (pair != '\0') {
  340. // Flush the left-over incomplete surrogate.
  341. if ((posn + 3) > length) {
  342. throw new ArgumentException (_("Arg_InsufficientSpace"), "bytes");
  343. }
  344. bytes [posn++] = (byte) (0xE0 | (pair >> 12));
  345. bytes [posn++] = (byte) (0x80 | ((pair >> 6) & 0x3F));
  346. bytes [posn++] = (byte) (0x80 | (pair & 0x3F));
  347. }
  348. leftOver = '\0';
  349. }
  350. else
  351. leftOver = pair;
  352. Char.IsLetterOrDigit (pair);
  353. // Return the final count to the caller.
  354. return posn - byteIndex;
  355. }
  356. private unsafe int Fallback (byte* bytes, int byteCount, char lead, char tail)
  357. {
  358. throw new NotImplementedException ();
  359. }
  360. // Get the bytes that result from encoding a character buffer.
  361. public override int GetBytes (char[] chars, int charIndex, int charCount,
  362. byte[] bytes, int byteIndex)
  363. {
  364. char leftOver = '\0';
  365. return InternalGetBytes (chars, charIndex, charCount, bytes, byteIndex, ref leftOver, true);
  366. }
  367. // Convenience wrappers for "GetBytes".
  368. public override int GetBytes (String s, int charIndex, int charCount,
  369. byte[] bytes, int byteIndex)
  370. {
  371. // Validate the parameters.
  372. if (s == null) {
  373. throw new ArgumentNullException ("s");
  374. }
  375. if (bytes == null) {
  376. throw new ArgumentNullException ("bytes");
  377. }
  378. if (charIndex < 0 || charIndex > s.Length) {
  379. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_StringIndex"));
  380. }
  381. if (charCount < 0 || charCount > (s.Length - charIndex)) {
  382. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_StringRange"));
  383. }
  384. if (byteIndex < 0 || byteIndex > bytes.Length) {
  385. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  386. }
  387. if (charIndex == s.Length)
  388. return 0;
  389. unsafe {
  390. fixed (char* cptr = s) {
  391. char dummy = '\0';
  392. if (bytes.Length == byteIndex)
  393. return InternalGetBytes (
  394. cptr + charIndex, charCount,
  395. null, 0, ref dummy, true);
  396. fixed (byte *bptr = bytes) {
  397. return InternalGetBytes (
  398. cptr + charIndex, charCount,
  399. bptr + byteIndex, bytes.Length - byteIndex,
  400. ref dummy, true);
  401. }
  402. }
  403. }
  404. }
  405. #endregion
  406. // Internal version of "GetCharCount" which can handle a rolling
  407. // state between multiple calls to this method.
  408. #if NET_2_0
  409. // Internal version of "GetCharCount" which can handle a rolling
  410. // state between multiple calls to this method.
  411. private static int InternalGetCharCount (
  412. byte[] bytes, int index, int count, uint leftOverBits,
  413. uint leftOverCount, object provider,
  414. ref DecoderFallbackBuffer fallbackBuffer, bool flush)
  415. #else
  416. private static int InternalGetCharCount (
  417. byte[] bytes, int index, int count, uint leftOverBits,
  418. uint leftOverCount, bool throwOnInvalid, bool flush)
  419. #endif
  420. {
  421. // Validate the parameters.
  422. if (bytes == null) {
  423. throw new ArgumentNullException ("bytes");
  424. }
  425. if (index < 0 || index > bytes.Length) {
  426. throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array"));
  427. }
  428. if (count < 0 || count > (bytes.Length - index)) {
  429. throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array"));
  430. }
  431. int length = 0;
  432. if (leftOverCount == 0) {
  433. int end = index + count;
  434. for (; index < end; index++, count--) {
  435. if (bytes [index] < 0x80)
  436. length++;
  437. else
  438. break;
  439. }
  440. }
  441. // Determine the number of characters that we have.
  442. uint ch;
  443. uint leftBits = leftOverBits;
  444. uint leftSoFar = (leftOverCount & (uint)0x0F);
  445. uint leftSize = ((leftOverCount >> 4) & (uint)0x0F);
  446. while (count > 0) {
  447. ch = (uint)(bytes[index++]);
  448. --count;
  449. if (leftSize == 0) {
  450. // Process a UTF-8 start character.
  451. if (ch < (uint)0x0080) {
  452. // Single-byte UTF-8 character.
  453. ++length;
  454. } else if ((ch & (uint)0xE0) == (uint)0xC0) {
  455. // Double-byte UTF-8 character.
  456. leftBits = (ch & (uint)0x1F);
  457. leftSoFar = 1;
  458. leftSize = 2;
  459. } else if ((ch & (uint)0xF0) == (uint)0xE0) {
  460. // Three-byte UTF-8 character.
  461. leftBits = (ch & (uint)0x0F);
  462. leftSoFar = 1;
  463. leftSize = 3;
  464. } else if ((ch & (uint)0xF8) == (uint)0xF0) {
  465. // Four-byte UTF-8 character.
  466. leftBits = (ch & (uint)0x07);
  467. leftSoFar = 1;
  468. leftSize = 4;
  469. } else if ((ch & (uint)0xFC) == (uint)0xF8) {
  470. // Five-byte UTF-8 character.
  471. leftBits = (ch & (uint)0x03);
  472. leftSoFar = 1;
  473. leftSize = 5;
  474. } else if ((ch & (uint)0xFE) == (uint)0xFC) {
  475. // Six-byte UTF-8 character.
  476. leftBits = (ch & (uint)0x03);
  477. leftSoFar = 1;
  478. leftSize = 6;
  479. } else {
  480. // Invalid UTF-8 start character.
  481. #if NET_2_0
  482. length += Fallback (provider, ref fallbackBuffer, bytes, index - 1);
  483. #else
  484. if (throwOnInvalid)
  485. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  486. #endif
  487. }
  488. } else {
  489. // Process an extra byte in a multi-byte sequence.
  490. if ((ch & (uint)0xC0) == (uint)0x80) {
  491. leftBits = ((leftBits << 6) | (ch & (uint)0x3F));
  492. if (++leftSoFar >= leftSize) {
  493. // We have a complete character now.
  494. if (leftBits < (uint)0x10000) {
  495. // is it an overlong ?
  496. bool overlong = false;
  497. switch (leftSize) {
  498. case 2:
  499. overlong = (leftBits <= 0x7F);
  500. break;
  501. case 3:
  502. overlong = (leftBits <= 0x07FF);
  503. break;
  504. case 4:
  505. overlong = (leftBits <= 0xFFFF);
  506. break;
  507. case 5:
  508. overlong = (leftBits <= 0x1FFFFF);
  509. break;
  510. case 6:
  511. overlong = (leftBits <= 0x03FFFFFF);
  512. break;
  513. }
  514. if (overlong) {
  515. #if NET_2_0
  516. length += Fallback (provider, ref fallbackBuffer, bytes, index - 1);
  517. #else
  518. if (throwOnInvalid)
  519. throw new ArgumentException (_("Overlong"), leftBits.ToString ());
  520. #endif
  521. }
  522. else
  523. ++length;
  524. } else if (leftBits < (uint)0x110000) {
  525. length += 2;
  526. } else {
  527. #if NET_2_0
  528. length += Fallback (provider, ref fallbackBuffer, bytes, index - 1);
  529. #else
  530. if (throwOnInvalid)
  531. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  532. #endif
  533. }
  534. leftSize = 0;
  535. }
  536. } else {
  537. // Invalid UTF-8 sequence: clear and restart.
  538. #if NET_2_0
  539. length += Fallback (provider, ref fallbackBuffer, bytes, index - 1);
  540. #else
  541. if (throwOnInvalid)
  542. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  543. #endif
  544. leftSize = 0;
  545. --index;
  546. ++count;
  547. }
  548. }
  549. }
  550. if (flush && leftSize != 0) {
  551. // We had left-over bytes that didn't make up
  552. // a complete UTF-8 character sequence.
  553. #if NET_2_0
  554. length += Fallback (provider, ref fallbackBuffer, bytes, index - 1);
  555. #else
  556. if (throwOnInvalid)
  557. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  558. #endif
  559. }
  560. // Return the final length to the caller.
  561. return length;
  562. }
  563. #if NET_2_0
  564. // for GetCharCount()
  565. static int Fallback (object provider, ref DecoderFallbackBuffer buffer, byte [] bytes, int index)
  566. {
  567. if (buffer == null) {
  568. DecoderFallback fb = provider as DecoderFallback;
  569. if (fb != null)
  570. buffer = fb.CreateFallbackBuffer ();
  571. else
  572. buffer = ((Decoder) provider).FallbackBuffer;
  573. }
  574. buffer.Fallback (bytes, index - 1);
  575. return buffer.Remaining;
  576. }
  577. // for GetChars()
  578. static void Fallback (object provider, ref DecoderFallbackBuffer buffer, byte [] bytes, int byteIndex,
  579. char [] chars, ref int charIndex)
  580. {
  581. if (buffer == null) {
  582. DecoderFallback fb = provider as DecoderFallback;
  583. if (fb != null)
  584. buffer = fb.CreateFallbackBuffer ();
  585. else
  586. buffer = ((Decoder) provider).FallbackBuffer;
  587. }
  588. buffer.Fallback (bytes, byteIndex - 1);
  589. while (buffer.Remaining > 0)
  590. chars [charIndex++] = buffer.GetNextChar ();
  591. }
  592. #endif
  593. // Get the number of characters needed to decode a byte buffer.
  594. public override int GetCharCount (byte[] bytes, int index, int count)
  595. {
  596. #if NET_2_0
  597. DecoderFallbackBuffer buf = null;
  598. return InternalGetCharCount (bytes, index, count, 0, 0, DecoderFallback, ref buf, true);
  599. #else
  600. return InternalGetCharCount (bytes, index, count, 0, 0, throwOnInvalid, true);
  601. #endif
  602. }
  603. // Get the characters that result from decoding a byte buffer.
  604. #if NET_2_0
  605. private static int InternalGetChars (
  606. byte[] bytes, int byteIndex, int byteCount, char[] chars,
  607. int charIndex, ref uint leftOverBits, ref uint leftOverCount,
  608. object provider,
  609. ref DecoderFallbackBuffer fallbackBuffer, bool flush)
  610. #else
  611. private static int InternalGetChars (
  612. byte[] bytes, int byteIndex, int byteCount, char[] chars,
  613. int charIndex, ref uint leftOverBits, ref uint leftOverCount,
  614. bool throwOnInvalid, bool flush)
  615. #endif
  616. {
  617. // Validate the parameters.
  618. if (bytes == null) {
  619. throw new ArgumentNullException ("bytes");
  620. }
  621. if (chars == null) {
  622. throw new ArgumentNullException ("chars");
  623. }
  624. if (byteIndex < 0 || byteIndex > bytes.Length) {
  625. throw new ArgumentOutOfRangeException ("byteIndex", _("ArgRange_Array"));
  626. }
  627. if (byteCount < 0 || byteCount > (bytes.Length - byteIndex)) {
  628. throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_Array"));
  629. }
  630. if (charIndex < 0 || charIndex > chars.Length) {
  631. throw new ArgumentOutOfRangeException ("charIndex", _("ArgRange_Array"));
  632. }
  633. if (charIndex == chars.Length)
  634. return 0;
  635. int posn = charIndex;
  636. if (leftOverCount == 0) {
  637. int end = byteIndex + byteCount;
  638. for (; byteIndex < end; posn++, byteIndex++, byteCount--) {
  639. if (bytes [byteIndex] < 0x80)
  640. chars [posn] = (char) bytes [byteIndex];
  641. else
  642. break;
  643. }
  644. }
  645. // Convert the bytes into the output buffer.
  646. uint ch;
  647. int length = chars.Length;
  648. uint leftBits = leftOverBits;
  649. uint leftSoFar = (leftOverCount & (uint)0x0F);
  650. uint leftSize = ((leftOverCount >> 4) & (uint)0x0F);
  651. int byteEnd = byteIndex + byteCount;
  652. if (byteEnd < 0 || byteEnd > bytes.Length)
  653. throw new SystemException (String.Format ("INTERNAL ERROR: should not happen: {0} {1} {2}", byteIndex, byteCount, byteEnd));
  654. for(; byteIndex < byteEnd; byteIndex++) {
  655. // Fetch the next character from the byte buffer.
  656. ch = (uint)(bytes[byteIndex]);
  657. if (leftSize == 0) {
  658. // Process a UTF-8 start character.
  659. if (ch < (uint)0x0080) {
  660. // Single-byte UTF-8 character.
  661. if (posn >= length) {
  662. throw new ArgumentException (_("Arg_InsufficientSpace"), "chars");
  663. }
  664. chars[posn++] = (char)ch;
  665. } else if ((ch & (uint)0xE0) == (uint)0xC0) {
  666. // Double-byte UTF-8 character.
  667. leftBits = (ch & (uint)0x1F);
  668. leftSoFar = 1;
  669. leftSize = 2;
  670. } else if ((ch & (uint)0xF0) == (uint)0xE0) {
  671. // Three-byte UTF-8 character.
  672. leftBits = (ch & (uint)0x0F);
  673. leftSoFar = 1;
  674. leftSize = 3;
  675. } else if ((ch & (uint)0xF8) == (uint)0xF0) {
  676. // Four-byte UTF-8 character.
  677. leftBits = (ch & (uint)0x07);
  678. leftSoFar = 1;
  679. leftSize = 4;
  680. } else if ((ch & (uint)0xFC) == (uint)0xF8) {
  681. // Five-byte UTF-8 character.
  682. leftBits = (ch & (uint)0x03);
  683. leftSoFar = 1;
  684. leftSize = 5;
  685. } else if ((ch & (uint)0xFE) == (uint)0xFC) {
  686. // Six-byte UTF-8 character.
  687. leftBits = (ch & (uint)0x03);
  688. leftSoFar = 1;
  689. leftSize = 6;
  690. } else {
  691. // Invalid UTF-8 start character.
  692. #if NET_2_0
  693. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  694. #else
  695. if (throwOnInvalid)
  696. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  697. #endif
  698. }
  699. } else {
  700. // Process an extra byte in a multi-byte sequence.
  701. if ((ch & (uint)0xC0) == (uint)0x80) {
  702. leftBits = ((leftBits << 6) | (ch & (uint)0x3F));
  703. if (++leftSoFar >= leftSize) {
  704. // We have a complete character now.
  705. if (leftBits < (uint)0x10000) {
  706. // is it an overlong ?
  707. bool overlong = false;
  708. switch (leftSize) {
  709. case 2:
  710. overlong = (leftBits <= 0x7F);
  711. break;
  712. case 3:
  713. overlong = (leftBits <= 0x07FF);
  714. break;
  715. case 4:
  716. overlong = (leftBits <= 0xFFFF);
  717. break;
  718. case 5:
  719. overlong = (leftBits <= 0x1FFFFF);
  720. break;
  721. case 6:
  722. overlong = (leftBits <= 0x03FFFFFF);
  723. break;
  724. }
  725. if (overlong) {
  726. #if NET_2_0
  727. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  728. #else
  729. if (throwOnInvalid)
  730. throw new ArgumentException (_("Overlong"), leftBits.ToString ());
  731. #endif
  732. }
  733. else if ((leftBits & 0xF800) == 0xD800) {
  734. // UTF-8 doesn't use surrogate characters
  735. #if NET_2_0
  736. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  737. #else
  738. if (throwOnInvalid)
  739. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  740. #endif
  741. }
  742. else {
  743. if (posn >= length) {
  744. throw new ArgumentException
  745. (_("Arg_InsufficientSpace"), "chars");
  746. }
  747. chars[posn++] = (char)leftBits;
  748. }
  749. } else if (leftBits < (uint)0x110000) {
  750. if ((posn + 2) > length) {
  751. throw new ArgumentException
  752. (_("Arg_InsufficientSpace"), "chars");
  753. }
  754. leftBits -= (uint)0x10000;
  755. chars[posn++] = (char)((leftBits >> 10) +
  756. (uint)0xD800);
  757. chars[posn++] =
  758. (char)((leftBits & (uint)0x3FF) + (uint)0xDC00);
  759. } else {
  760. #if NET_2_0
  761. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  762. #else
  763. if (throwOnInvalid)
  764. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  765. #endif
  766. }
  767. leftSize = 0;
  768. }
  769. } else {
  770. // Invalid UTF-8 sequence: clear and restart.
  771. #if NET_2_0
  772. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  773. #else
  774. if (throwOnInvalid)
  775. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  776. #endif
  777. leftSize = 0;
  778. --byteIndex;
  779. }
  780. }
  781. }
  782. if (flush && leftSize != 0) {
  783. // We had left-over bytes that didn't make up
  784. // a complete UTF-8 character sequence.
  785. #if NET_2_0
  786. Fallback (provider, ref fallbackBuffer, bytes, byteIndex, chars, ref posn);
  787. #else
  788. if (throwOnInvalid)
  789. throw new ArgumentException (_("Arg_InvalidUTF8"), "bytes");
  790. #endif
  791. }
  792. leftOverBits = leftBits;
  793. leftOverCount = (leftSoFar | (leftSize << 4));
  794. // Return the final length to the caller.
  795. return posn - charIndex;
  796. }
  797. // Get the characters that result from decoding a byte buffer.
  798. public override int GetChars (byte[] bytes, int byteIndex, int byteCount,
  799. char[] chars, int charIndex)
  800. {
  801. uint leftOverBits = 0;
  802. uint leftOverCount = 0;
  803. #if NET_2_0
  804. DecoderFallbackBuffer buf = null;
  805. return InternalGetChars (bytes, byteIndex, byteCount, chars,
  806. charIndex, ref leftOverBits, ref leftOverCount, DecoderFallback, ref buf, true);
  807. #else
  808. return InternalGetChars (bytes, byteIndex, byteCount, chars,
  809. charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid, true);
  810. #endif
  811. }
  812. // Get the maximum number of bytes needed to encode a
  813. // specified number of characters.
  814. public override int GetMaxByteCount (int charCount)
  815. {
  816. if (charCount < 0) {
  817. throw new ArgumentOutOfRangeException ("charCount", _("ArgRange_NonNegative"));
  818. }
  819. return charCount * 4;
  820. }
  821. // Get the maximum number of characters needed to decode a
  822. // specified number of bytes.
  823. public override int GetMaxCharCount (int byteCount)
  824. {
  825. if (byteCount < 0) {
  826. throw new ArgumentOutOfRangeException ("byteCount", _("ArgRange_NonNegative"));
  827. }
  828. return byteCount;
  829. }
  830. // Get a UTF8-specific decoder that is attached to this instance.
  831. public override Decoder GetDecoder ()
  832. {
  833. #if NET_2_0
  834. return new UTF8Decoder (DecoderFallback);
  835. #else
  836. return new UTF8Decoder (throwOnInvalid);
  837. #endif
  838. }
  839. // Get a UTF8-specific encoder that is attached to this instance.
  840. public override Encoder GetEncoder ()
  841. {
  842. return new UTF8Encoder (emitIdentifier);
  843. }
  844. // Get the UTF8 preamble.
  845. public override byte[] GetPreamble ()
  846. {
  847. if (emitIdentifier) {
  848. byte[] pre = new byte [3];
  849. pre[0] = (byte)0xEF;
  850. pre[1] = (byte)0xBB;
  851. pre[2] = (byte)0xBF;
  852. return pre;
  853. } else {
  854. return new byte [0];
  855. }
  856. }
  857. // Determine if this object is equal to another.
  858. public override bool Equals (Object value)
  859. {
  860. UTF8Encoding enc = (value as UTF8Encoding);
  861. if (enc != null) {
  862. #if NET_2_0
  863. return (codePage == enc.codePage &&
  864. emitIdentifier == enc.emitIdentifier &&
  865. DecoderFallback == enc.DecoderFallback &&
  866. EncoderFallback == enc.EncoderFallback);
  867. #else
  868. return (codePage == enc.codePage &&
  869. emitIdentifier == enc.emitIdentifier &&
  870. throwOnInvalid == enc.throwOnInvalid);
  871. #endif
  872. } else {
  873. return false;
  874. }
  875. }
  876. // Get the hash code for this object.
  877. public override int GetHashCode ()
  878. {
  879. return base.GetHashCode ();
  880. }
  881. public override byte [] GetBytes (String s)
  882. {
  883. if (s == null)
  884. throw new ArgumentNullException ("s");
  885. int length = GetByteCount (s);
  886. byte [] bytes = new byte [length];
  887. GetBytes (s, 0, s.Length, bytes, 0);
  888. return bytes;
  889. }
  890. // UTF-8 decoder implementation.
  891. [Serializable]
  892. private class UTF8Decoder : Decoder
  893. {
  894. #if !NET_2_0
  895. private bool throwOnInvalid;
  896. #endif
  897. private uint leftOverBits;
  898. private uint leftOverCount;
  899. // Constructor.
  900. #if NET_2_0
  901. public UTF8Decoder (DecoderFallback fallback)
  902. #else
  903. public UTF8Decoder (bool throwOnInvalid)
  904. #endif
  905. {
  906. #if NET_2_0
  907. Fallback = fallback;
  908. #else
  909. this.throwOnInvalid = throwOnInvalid;
  910. #endif
  911. leftOverBits = 0;
  912. leftOverCount = 0;
  913. }
  914. // Override inherited methods.
  915. public override int GetCharCount (byte[] bytes, int index, int count)
  916. {
  917. #if NET_2_0
  918. DecoderFallbackBuffer buf = null;
  919. return InternalGetCharCount (bytes, index, count,
  920. leftOverBits, leftOverCount, this, ref buf, false);
  921. #else
  922. return InternalGetCharCount (bytes, index, count,
  923. leftOverBits, leftOverCount, throwOnInvalid, false);
  924. #endif
  925. }
  926. public override int GetChars (byte[] bytes, int byteIndex,
  927. int byteCount, char[] chars, int charIndex)
  928. {
  929. #if NET_2_0
  930. DecoderFallbackBuffer buf = null;
  931. return InternalGetChars (bytes, byteIndex, byteCount,
  932. chars, charIndex, ref leftOverBits, ref leftOverCount, this, ref buf, false);
  933. #else
  934. return InternalGetChars (bytes, byteIndex, byteCount,
  935. chars, charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid, false);
  936. #endif
  937. }
  938. } // class UTF8Decoder
  939. // UTF-8 encoder implementation.
  940. [Serializable]
  941. private class UTF8Encoder : Encoder
  942. {
  943. private bool emitIdentifier;
  944. private char leftOverForCount;
  945. private char leftOverForConv;
  946. // Constructor.
  947. public UTF8Encoder (bool emitIdentifier)
  948. {
  949. this.emitIdentifier = emitIdentifier;
  950. leftOverForCount = '\0';
  951. leftOverForConv = '\0';
  952. }
  953. // Override inherited methods.
  954. public override int GetByteCount (char[] chars, int index,
  955. int count, bool flush)
  956. {
  957. return InternalGetByteCount (chars, index, count, ref leftOverForCount, flush);
  958. }
  959. public override int GetBytes (char[] chars, int charIndex,
  960. int charCount, byte[] bytes, int byteIndex, bool flush)
  961. {
  962. int result;
  963. result = InternalGetBytes (chars, charIndex, charCount, bytes, byteIndex, ref leftOverForConv, flush);
  964. emitIdentifier = false;
  965. return result;
  966. }
  967. #if NET_2_0
  968. public unsafe override int GetByteCount (char* chars, int count, bool flush)
  969. {
  970. return InternalGetByteCount (chars, count, ref leftOverForCount, flush);
  971. }
  972. public unsafe override int GetBytes (char* chars, int charCount,
  973. byte* bytes, int byteCount, bool flush)
  974. {
  975. int result;
  976. result = InternalGetBytes (chars, charCount, bytes, byteCount, ref leftOverForConv, flush);
  977. emitIdentifier = false;
  978. return result;
  979. }
  980. #endif
  981. } // class UTF8Encoder
  982. }; // class UTF8Encoding
  983. }; // namespace System.Text