ByteString.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Text;
  2. using System;
  3. namespace Google.ProtocolBuffers {
  4. /// <summary>
  5. /// Immutable array of bytes.
  6. /// TODO(jonskeet): Implement the common collection interfaces?
  7. /// </summary>
  8. public sealed class ByteString {
  9. private static readonly ByteString empty = new ByteString(new byte[0]);
  10. private byte[] bytes;
  11. /// <summary>
  12. /// Constructs a new ByteString from the given byte array. The array is
  13. /// *not* copied, and must not be modified after this constructor is called.
  14. /// </summary>
  15. private ByteString(byte[] bytes) {
  16. this.bytes = bytes;
  17. }
  18. /// <summary>
  19. /// Returns an empty ByteString.
  20. /// </summary>
  21. public static ByteString Empty {
  22. get { return empty; }
  23. }
  24. /// <summary>
  25. /// Returns the length of this ByteString in bytes.
  26. /// </summary>
  27. public int Length {
  28. get { return bytes.Length; }
  29. }
  30. public bool IsEmpty {
  31. get { return Length == 0; }
  32. }
  33. public byte[] ToByteArray() {
  34. return (byte[])bytes.Clone();
  35. }
  36. /// <summary>
  37. /// Constructs a ByteString from the given array. The contents
  38. /// are copied, so further modifications to the array will not
  39. /// be reflected in the returned ByteString.
  40. /// </summary>
  41. public static ByteString CopyFrom(byte[] bytes) {
  42. return new ByteString((byte[]) bytes.Clone());
  43. }
  44. /// <summary>
  45. /// Constructs a ByteString from a portion of a byte array.
  46. /// </summary>
  47. public static ByteString CopyFrom(byte[] bytes, int offset, int count) {
  48. byte[] portion = new byte[count];
  49. Array.Copy(bytes, offset, portion, 0, count);
  50. return new ByteString(portion);
  51. }
  52. /// <summary>
  53. /// Creates a new ByteString by encoding the specified text with
  54. /// the given encoding.
  55. /// </summary>
  56. public static ByteString CopyFrom(string text, Encoding encoding) {
  57. return new ByteString(encoding.GetBytes(text));
  58. }
  59. /// <summary>
  60. /// Creates a new ByteString by encoding the specified text in UTF-8.
  61. /// </summary>
  62. public static ByteString CopyFromUtf8(string text) {
  63. return CopyFrom(text, Encoding.UTF8);
  64. }
  65. /// <summary>
  66. /// Retuns the byte at the given index.
  67. /// </summary>
  68. public byte this[int index] {
  69. get { return bytes[index]; }
  70. }
  71. public string ToString(Encoding encoding) {
  72. return encoding.GetString(bytes);
  73. }
  74. public string ToStringUtf8() {
  75. return ToString(Encoding.UTF8);
  76. }
  77. // TODO(jonskeet): CopyTo, Equals, GetHashCode if they turn out to be required
  78. // TODO(jonskeet): Input/Output stuff
  79. }
  80. }