Utf8Helper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System.Text;
  16. namespace MongoDB.Bson.IO
  17. {
  18. /// <summary>
  19. /// Represents a class that has some helper methods for decoding UTF8 strings.
  20. /// </summary>
  21. public static class Utf8Helper
  22. {
  23. // private static fields
  24. private static readonly string[] __asciiStringTable = new string[128];
  25. // static constructor
  26. static Utf8Helper()
  27. {
  28. for (int i = 0; i < __asciiStringTable.Length; ++i)
  29. {
  30. __asciiStringTable[i] = new string((char)i, 1);
  31. }
  32. }
  33. // public static methods
  34. /// <summary>
  35. /// Decodes a UTF8 string.
  36. /// </summary>
  37. /// <param name="bytes">The bytes.</param>
  38. /// <param name="index">The index.</param>
  39. /// <param name="count">The count.</param>
  40. /// <param name="encoding">The encoding.</param>
  41. /// <returns>The decoded string.</returns>
  42. public static string DecodeUtf8String(byte[] bytes, int index, int count, UTF8Encoding encoding)
  43. {
  44. switch (count)
  45. {
  46. // special case empty strings
  47. case 0:
  48. return "";
  49. // special case single character strings
  50. case 1:
  51. var byte1 = (int)bytes[index];
  52. if (byte1 < __asciiStringTable.Length)
  53. {
  54. return __asciiStringTable[byte1];
  55. }
  56. break;
  57. }
  58. return encoding.GetString(bytes, index, count);
  59. }
  60. }
  61. }