CStringUtf8Encoding.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Copyright 2016 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;
  16. using System.IO;
  17. using System.Text;
  18. namespace MongoDB.Bson.IO
  19. {
  20. internal static class CStringUtf8Encoding
  21. {
  22. public static int GetBytes(string value, byte[] bytes, int byteIndex, UTF8Encoding fallbackEncoding)
  23. {
  24. var charLength = value.Length;
  25. var initialByteIndex = byteIndex;
  26. for (var charIndex = 0; charIndex < charLength; charIndex++)
  27. {
  28. var c = (int)value[charIndex];
  29. if (c == 0)
  30. {
  31. throw new ArgumentException("A CString cannot contain null bytes.", "value");
  32. }
  33. else if (c <= 0x7f)
  34. {
  35. bytes[byteIndex++] = (byte)c;
  36. }
  37. else if (c <= 0x7ff)
  38. {
  39. var byte1 = 0xc0 | (c >> 6);
  40. var byte2 = 0x80 | (c & 0x3f);
  41. bytes[byteIndex++] = (byte)byte1;
  42. bytes[byteIndex++] = (byte)byte2;
  43. }
  44. else if (c <= 0xd7ff || c >= 0xe000)
  45. {
  46. var byte1 = 0xe0 | (c >> 12);
  47. var byte2 = 0x80 | ((c >> 6) & 0x3f);
  48. var byte3 = 0x80 | (c & 0x3f);
  49. bytes[byteIndex++] = (byte)byte1;
  50. bytes[byteIndex++] = (byte)byte2;
  51. bytes[byteIndex++] = (byte)byte3;
  52. }
  53. else
  54. {
  55. // let fallback encoding handle surrogate pairs
  56. var bytesWritten = fallbackEncoding.GetBytes(value, 0, value.Length, bytes, byteIndex);
  57. if (Array.IndexOf<byte>(bytes, 0, initialByteIndex, bytesWritten) != -1)
  58. {
  59. throw new ArgumentException("A CString cannot contain null bytes.", "value");
  60. }
  61. return bytesWritten;
  62. }
  63. }
  64. return byteIndex - initialByteIndex;
  65. }
  66. public static int GetMaxByteCount(int charCount)
  67. {
  68. return charCount * 3;
  69. }
  70. }
  71. }