ByteString.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.IO;
  36. using System.Linq;
  37. using System.Text;
  38. using Google.Protobuf.Compatibility;
  39. using MongoDB.Bson.Serialization.Attributes;
  40. namespace Google.Protobuf
  41. {
  42. /// <summary>
  43. /// Immutable array of bytes.
  44. /// </summary>
  45. public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString>
  46. {
  47. private static readonly ByteString empty = new ByteString(new byte[0]);
  48. public byte[] bytes;
  49. /// <summary>
  50. /// Unsafe operations that can cause IO Failure and/or other catestrophic side-effects.
  51. /// </summary>
  52. public static class Unsafe
  53. {
  54. /// <summary>
  55. /// Constructs a new ByteString from the given byte array. The array is
  56. /// *not* copied, and must not be modified after this constructor is called.
  57. /// </summary>
  58. public static ByteString FromBytes(byte[] bytes)
  59. {
  60. return new ByteString(bytes);
  61. }
  62. /// <summary>
  63. /// Provides direct, unrestricted access to the bytes contained in this instance.
  64. /// You must not modify or resize the byte array returned by this method.
  65. /// </summary>
  66. public static byte[] GetBuffer(ByteString bytes)
  67. {
  68. return bytes.bytes;
  69. }
  70. }
  71. /// <summary>
  72. /// Internal use only. Ensure that the provided array is not mutated and belongs to this instance.
  73. /// </summary>
  74. internal static ByteString AttachBytes(byte[] bytes)
  75. {
  76. return new ByteString(bytes);
  77. }
  78. public ByteString()
  79. {}
  80. public ByteString(List<byte> list)
  81. {
  82. this.bytes = list.ToArray();
  83. }
  84. /// <summary>
  85. /// Constructs a new ByteString from the given byte array. The array is
  86. /// *not* copied, and must not be modified after this constructor is called.
  87. /// </summary>
  88. public ByteString(byte[] bytes)
  89. {
  90. this.bytes = bytes;
  91. }
  92. /// <summary>
  93. /// Returns an empty ByteString.
  94. /// </summary>
  95. public static ByteString Empty
  96. {
  97. get { return empty; }
  98. }
  99. /// <summary>
  100. /// Returns the length of this ByteString in bytes.
  101. /// </summary>
  102. [BsonIgnore]
  103. public int Length
  104. {
  105. get { return bytes.Length; }
  106. }
  107. /// <summary>
  108. /// Returns <c>true</c> if this byte string is empty, <c>false</c> otherwise.
  109. /// </summary>
  110. [BsonIgnore]
  111. public bool IsEmpty
  112. {
  113. get { return Length == 0; }
  114. }
  115. /// <summary>
  116. /// Converts this <see cref="ByteString"/> into a byte array.
  117. /// </summary>
  118. /// <remarks>The data is copied - changes to the returned array will not be reflected in this <c>ByteString</c>.</remarks>
  119. /// <returns>A byte array with the same data as this <c>ByteString</c>.</returns>
  120. public byte[] ToByteArray()
  121. {
  122. return (byte[]) bytes.Clone();
  123. }
  124. /// <summary>
  125. /// Converts this <see cref="ByteString"/> into a standard base64 representation.
  126. /// </summary>
  127. /// <returns>A base64 representation of this <c>ByteString</c>.</returns>
  128. public string ToBase64()
  129. {
  130. return Convert.ToBase64String(bytes);
  131. }
  132. /// <summary>
  133. /// Constructs a <see cref="ByteString" /> from the Base64 Encoded String.
  134. /// </summary>
  135. public static ByteString FromBase64(string bytes)
  136. {
  137. // By handling the empty string explicitly, we not only optimize but we fix a
  138. // problem on CF 2.0. See issue 61 for details.
  139. return bytes == "" ? Empty : new ByteString(Convert.FromBase64String(bytes));
  140. }
  141. /// <summary>
  142. /// Constructs a <see cref="ByteString"/> from data in the given stream, synchronously.
  143. /// </summary>
  144. /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position
  145. /// at the start of the call.</remarks>
  146. /// <param name="stream">The stream to copy into a ByteString.</param>
  147. /// <returns>A ByteString with content read from the given stream.</returns>
  148. public static ByteString FromStream(Stream stream)
  149. {
  150. ProtoPreconditions.CheckNotNull(stream, "stream");
  151. int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
  152. var memoryStream = new MemoryStream(capacity);
  153. stream.CopyTo(memoryStream);
  154. // Avoid an extra copy if we can.
  155. byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
  156. return AttachBytes(bytes);
  157. }
  158. /// <summary>
  159. /// Constructs a <see cref="ByteString" /> from the given array. The contents
  160. /// are copied, so further modifications to the array will not
  161. /// be reflected in the returned ByteString.
  162. /// This method can also be invoked in <c>ByteString.CopyFrom(0xaa, 0xbb, ...)</c> form
  163. /// which is primarily useful for testing.
  164. /// </summary>
  165. public static ByteString CopyFrom(params byte[] bytes)
  166. {
  167. return new ByteString((byte[]) bytes.Clone());
  168. }
  169. /// <summary>
  170. /// Constructs a <see cref="ByteString" /> from a portion of a byte array.
  171. /// </summary>
  172. public static ByteString CopyFrom(byte[] bytes, int offset, int count)
  173. {
  174. byte[] portion = new byte[count];
  175. ByteArray.Copy(bytes, offset, portion, 0, count);
  176. return new ByteString(portion);
  177. }
  178. /// <summary>
  179. /// Creates a new <see cref="ByteString" /> by encoding the specified text with
  180. /// the given encoding.
  181. /// </summary>
  182. public static ByteString CopyFrom(string text, Encoding encoding)
  183. {
  184. return new ByteString(encoding.GetBytes(text));
  185. }
  186. /// <summary>
  187. /// Creates a new <see cref="ByteString" /> by encoding the specified text in UTF-8.
  188. /// </summary>
  189. public static ByteString CopyFromUtf8(string text)
  190. {
  191. return CopyFrom(text, Encoding.UTF8);
  192. }
  193. /// <summary>
  194. /// Retuns the byte at the given index.
  195. /// </summary>
  196. [BsonIgnore]
  197. public byte this[int index]
  198. {
  199. get { return bytes[index]; }
  200. }
  201. /// <summary>
  202. /// Converts this <see cref="ByteString"/> into a string by applying the given encoding.
  203. /// </summary>
  204. /// <remarks>
  205. /// This method should only be used to convert binary data which was the result of encoding
  206. /// text with the given encoding.
  207. /// </remarks>
  208. /// <param name="encoding">The encoding to use to decode the binary data into text.</param>
  209. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  210. public string ToString(Encoding encoding)
  211. {
  212. return encoding.GetString(bytes, 0, bytes.Length);
  213. }
  214. /// <summary>
  215. /// Converts this <see cref="ByteString"/> into a string by applying the UTF-8 encoding.
  216. /// </summary>
  217. /// <remarks>
  218. /// This method should only be used to convert binary data which was the result of encoding
  219. /// text with UTF-8.
  220. /// </remarks>
  221. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  222. public string ToStringUtf8()
  223. {
  224. return ToString(Encoding.UTF8);
  225. }
  226. /// <summary>
  227. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  228. /// </summary>
  229. /// <returns>An iterator over the bytes in this object.</returns>
  230. public IEnumerator<byte> GetEnumerator()
  231. {
  232. return ((IEnumerable<byte>) bytes).GetEnumerator();
  233. }
  234. /// <summary>
  235. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  236. /// </summary>
  237. /// <returns>An iterator over the bytes in this object.</returns>
  238. IEnumerator IEnumerable.GetEnumerator()
  239. {
  240. return GetEnumerator();
  241. }
  242. /// <summary>
  243. /// Creates a CodedInputStream from this ByteString's data.
  244. /// </summary>
  245. public CodedInputStream CreateCodedInput()
  246. {
  247. // We trust CodedInputStream not to reveal the provided byte array or modify it
  248. return new CodedInputStream(bytes);
  249. }
  250. /// <summary>
  251. /// Compares two byte strings for equality.
  252. /// </summary>
  253. /// <param name="lhs">The first byte string to compare.</param>
  254. /// <param name="rhs">The second byte string to compare.</param>
  255. /// <returns><c>true</c> if the byte strings are equal; false otherwise.</returns>
  256. public static bool operator ==(ByteString lhs, ByteString rhs)
  257. {
  258. if (ReferenceEquals(lhs, rhs))
  259. {
  260. return true;
  261. }
  262. if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
  263. {
  264. return false;
  265. }
  266. if (lhs.bytes.Length != rhs.bytes.Length)
  267. {
  268. return false;
  269. }
  270. for (int i = 0; i < lhs.Length; i++)
  271. {
  272. if (rhs.bytes[i] != lhs.bytes[i])
  273. {
  274. return false;
  275. }
  276. }
  277. return true;
  278. }
  279. /// <summary>
  280. /// Compares two byte strings for inequality.
  281. /// </summary>
  282. /// <param name="lhs">The first byte string to compare.</param>
  283. /// <param name="rhs">The second byte string to compare.</param>
  284. /// <returns><c>false</c> if the byte strings are equal; true otherwise.</returns>
  285. public static bool operator !=(ByteString lhs, ByteString rhs)
  286. {
  287. return !(lhs == rhs);
  288. }
  289. /// <summary>
  290. /// Compares this byte string with another object.
  291. /// </summary>
  292. /// <param name="obj">The object to compare this with.</param>
  293. /// <returns><c>true</c> if <paramref name="obj"/> refers to an equal <see cref="ByteString"/>; <c>false</c> otherwise.</returns>
  294. public override bool Equals(object obj)
  295. {
  296. return this == (obj as ByteString);
  297. }
  298. /// <summary>
  299. /// Returns a hash code for this object. Two equal byte strings
  300. /// will return the same hash code.
  301. /// </summary>
  302. /// <returns>A hash code for this object.</returns>
  303. public override int GetHashCode()
  304. {
  305. int ret = 23;
  306. foreach (byte b in bytes)
  307. {
  308. ret = (ret * 31) + b;
  309. }
  310. return ret;
  311. }
  312. /// <summary>
  313. /// Compares this byte string with another.
  314. /// </summary>
  315. /// <param name="other">The <see cref="ByteString"/> to compare this with.</param>
  316. /// <returns><c>true</c> if <paramref name="other"/> refers to an equal byte string; <c>false</c> otherwise.</returns>
  317. public bool Equals(ByteString other)
  318. {
  319. return this == other;
  320. }
  321. /// <summary>
  322. /// Used internally by CodedOutputStream to avoid creating a copy for the write
  323. /// </summary>
  324. internal void WriteRawBytesTo(CodedOutputStream outputStream)
  325. {
  326. outputStream.WriteRawBytes(bytes, 0, bytes.Length);
  327. }
  328. /// <summary>
  329. /// Copies the entire byte array to the destination array provided at the offset specified.
  330. /// </summary>
  331. public void CopyTo(byte[] array, int position)
  332. {
  333. ByteArray.Copy(bytes, 0, array, position, bytes.Length);
  334. }
  335. /// <summary>
  336. /// Writes the entire byte array to the provided stream
  337. /// </summary>
  338. public void WriteTo(Stream outputStream)
  339. {
  340. outputStream.Write(bytes, 0, bytes.Length);
  341. }
  342. }
  343. }