ByteString.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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.Security;
  37. using System.Text;
  38. #if !NET35
  39. using System.Threading;
  40. using System.Threading.Tasks;
  41. #endif
  42. #if NET35
  43. using Google.Protobuf.Compatibility;
  44. #endif
  45. namespace Google.Protobuf
  46. {
  47. /// <summary>
  48. /// Immutable array of bytes.
  49. /// </summary>
  50. public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString>
  51. {
  52. private static readonly ByteString empty = new ByteString(new byte[0]);
  53. private readonly byte[] bytes;
  54. /// <summary>
  55. /// Unsafe operations that can cause IO Failure and/or other catastrophic side-effects.
  56. /// </summary>
  57. internal static class Unsafe
  58. {
  59. /// <summary>
  60. /// Constructs a new ByteString from the given byte array. The array is
  61. /// *not* copied, and must not be modified after this constructor is called.
  62. /// </summary>
  63. internal static ByteString FromBytes(byte[] bytes)
  64. {
  65. return new ByteString(bytes);
  66. }
  67. }
  68. /// <summary>
  69. /// Internal use only. Ensure that the provided array is not mutated and belongs to this instance.
  70. /// </summary>
  71. internal static ByteString AttachBytes(byte[] bytes)
  72. {
  73. return new ByteString(bytes);
  74. }
  75. /// <summary>
  76. /// Constructs a new ByteString from the given byte array. The array is
  77. /// *not* copied, and must not be modified after this constructor is called.
  78. /// </summary>
  79. private ByteString(byte[] bytes)
  80. {
  81. this.bytes = bytes;
  82. }
  83. /// <summary>
  84. /// Returns an empty ByteString.
  85. /// </summary>
  86. public static ByteString Empty
  87. {
  88. get { return empty; }
  89. }
  90. /// <summary>
  91. /// Returns the length of this ByteString in bytes.
  92. /// </summary>
  93. public int Length
  94. {
  95. get { return bytes.Length; }
  96. }
  97. /// <summary>
  98. /// Returns <c>true</c> if this byte string is empty, <c>false</c> otherwise.
  99. /// </summary>
  100. public bool IsEmpty
  101. {
  102. get { return Length == 0; }
  103. }
  104. #if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY
  105. /// <summary>
  106. /// Provides read-only access to the data of this <see cref="ByteString"/>.
  107. /// No data is copied so this is the most efficient way of accessing.
  108. /// </summary>
  109. public ReadOnlySpan<byte> Span
  110. {
  111. [SecuritySafeCritical]
  112. get
  113. {
  114. return new ReadOnlySpan<byte>(bytes);
  115. }
  116. }
  117. /// <summary>
  118. /// Provides read-only access to the data of this <see cref="ByteString"/>.
  119. /// No data is copied so this is the most efficient way of accessing.
  120. /// </summary>
  121. public ReadOnlyMemory<byte> Memory
  122. {
  123. [SecuritySafeCritical]
  124. get
  125. {
  126. return new ReadOnlyMemory<byte>(bytes);
  127. }
  128. }
  129. #endif
  130. /// <summary>
  131. /// Converts this <see cref="ByteString"/> into a byte array.
  132. /// </summary>
  133. /// <remarks>The data is copied - changes to the returned array will not be reflected in this <c>ByteString</c>.</remarks>
  134. /// <returns>A byte array with the same data as this <c>ByteString</c>.</returns>
  135. public byte[] ToByteArray()
  136. {
  137. return (byte[]) bytes.Clone();
  138. }
  139. /// <summary>
  140. /// Converts this <see cref="ByteString"/> into a standard base64 representation.
  141. /// </summary>
  142. /// <returns>A base64 representation of this <c>ByteString</c>.</returns>
  143. public string ToBase64()
  144. {
  145. return Convert.ToBase64String(bytes);
  146. }
  147. /// <summary>
  148. /// Constructs a <see cref="ByteString" /> from the Base64 Encoded String.
  149. /// </summary>
  150. public static ByteString FromBase64(string bytes)
  151. {
  152. // By handling the empty string explicitly, we not only optimize but we fix a
  153. // problem on CF 2.0. See issue 61 for details.
  154. return bytes == "" ? Empty : new ByteString(Convert.FromBase64String(bytes));
  155. }
  156. /// <summary>
  157. /// Constructs a <see cref="ByteString"/> from data in the given stream, synchronously.
  158. /// </summary>
  159. /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position
  160. /// at the start of the call.</remarks>
  161. /// <param name="stream">The stream to copy into a ByteString.</param>
  162. /// <returns>A ByteString with content read from the given stream.</returns>
  163. public static ByteString FromStream(Stream stream)
  164. {
  165. ProtoPreconditions.CheckNotNull(stream, nameof(stream));
  166. int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
  167. var memoryStream = new MemoryStream(capacity);
  168. stream.CopyTo(memoryStream);
  169. #if NETSTANDARD1_1 || NETSTANDARD2_0
  170. byte[] bytes = memoryStream.ToArray();
  171. #else
  172. // Avoid an extra copy if we can.
  173. byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
  174. #endif
  175. return AttachBytes(bytes);
  176. }
  177. #if !NET35
  178. /// <summary>
  179. /// Constructs a <see cref="ByteString"/> from data in the given stream, asynchronously.
  180. /// </summary>
  181. /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position
  182. /// at the start of the call.</remarks>
  183. /// <param name="stream">The stream to copy into a ByteString.</param>
  184. /// <param name="cancellationToken">The cancellation token to use when reading from the stream, if any.</param>
  185. /// <returns>A ByteString with content read from the given stream.</returns>
  186. public async static Task<ByteString> FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
  187. {
  188. ProtoPreconditions.CheckNotNull(stream, nameof(stream));
  189. int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
  190. var memoryStream = new MemoryStream(capacity);
  191. // We have to specify the buffer size here, as there's no overload accepting the cancellation token
  192. // alone. But it's documented to use 81920 by default if not specified.
  193. await stream.CopyToAsync(memoryStream, 81920, cancellationToken);
  194. #if NETSTANDARD1_1 || NETSTANDARD2_0
  195. byte[] bytes = memoryStream.ToArray();
  196. #else
  197. // Avoid an extra copy if we can.
  198. byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
  199. #endif
  200. return AttachBytes(bytes);
  201. }
  202. #endif
  203. /// <summary>
  204. /// Constructs a <see cref="ByteString" /> from the given array. The contents
  205. /// are copied, so further modifications to the array will not
  206. /// be reflected in the returned ByteString.
  207. /// This method can also be invoked in <c>ByteString.CopyFrom(0xaa, 0xbb, ...)</c> form
  208. /// which is primarily useful for testing.
  209. /// </summary>
  210. public static ByteString CopyFrom(params byte[] bytes)
  211. {
  212. return new ByteString((byte[]) bytes.Clone());
  213. }
  214. /// <summary>
  215. /// Constructs a <see cref="ByteString" /> from a portion of a byte array.
  216. /// </summary>
  217. public static ByteString CopyFrom(byte[] bytes, int offset, int count)
  218. {
  219. byte[] portion = new byte[count];
  220. ByteArray.Copy(bytes, offset, portion, 0, count);
  221. return new ByteString(portion);
  222. }
  223. #if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY
  224. /// <summary>
  225. /// Constructs a <see cref="ByteString" /> from a read only span. The contents
  226. /// are copied, so further modifications to the span will not
  227. /// be reflected in the returned <see cref="ByteString" />.
  228. /// </summary>
  229. public static ByteString CopyFrom(ReadOnlySpan<byte> bytes)
  230. {
  231. return new ByteString(bytes.ToArray());
  232. }
  233. #endif
  234. /// <summary>
  235. /// Creates a new <see cref="ByteString" /> by encoding the specified text with
  236. /// the given encoding.
  237. /// </summary>
  238. public static ByteString CopyFrom(string text, Encoding encoding)
  239. {
  240. return new ByteString(encoding.GetBytes(text));
  241. }
  242. /// <summary>
  243. /// Creates a new <see cref="ByteString" /> by encoding the specified text in UTF-8.
  244. /// </summary>
  245. public static ByteString CopyFromUtf8(string text)
  246. {
  247. return CopyFrom(text, Encoding.UTF8);
  248. }
  249. /// <summary>
  250. /// Returns the byte at the given index.
  251. /// </summary>
  252. public byte this[int index]
  253. {
  254. get { return bytes[index]; }
  255. }
  256. /// <summary>
  257. /// Converts this <see cref="ByteString"/> into a string by applying the given encoding.
  258. /// </summary>
  259. /// <remarks>
  260. /// This method should only be used to convert binary data which was the result of encoding
  261. /// text with the given encoding.
  262. /// </remarks>
  263. /// <param name="encoding">The encoding to use to decode the binary data into text.</param>
  264. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  265. public string ToString(Encoding encoding)
  266. {
  267. return encoding.GetString(bytes, 0, bytes.Length);
  268. }
  269. /// <summary>
  270. /// Converts this <see cref="ByteString"/> into a string by applying the UTF-8 encoding.
  271. /// </summary>
  272. /// <remarks>
  273. /// This method should only be used to convert binary data which was the result of encoding
  274. /// text with UTF-8.
  275. /// </remarks>
  276. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  277. public string ToStringUtf8()
  278. {
  279. return ToString(Encoding.UTF8);
  280. }
  281. /// <summary>
  282. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  283. /// </summary>
  284. /// <returns>An iterator over the bytes in this object.</returns>
  285. public IEnumerator<byte> GetEnumerator()
  286. {
  287. return ((IEnumerable<byte>) bytes).GetEnumerator();
  288. }
  289. /// <summary>
  290. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  291. /// </summary>
  292. /// <returns>An iterator over the bytes in this object.</returns>
  293. IEnumerator IEnumerable.GetEnumerator()
  294. {
  295. return GetEnumerator();
  296. }
  297. /// <summary>
  298. /// Creates a CodedInputStream from this ByteString's data.
  299. /// </summary>
  300. public CodedInputStream CreateCodedInput()
  301. {
  302. // We trust CodedInputStream not to reveal the provided byte array or modify it
  303. return new CodedInputStream(bytes);
  304. }
  305. /// <summary>
  306. /// Compares two byte strings for equality.
  307. /// </summary>
  308. /// <param name="lhs">The first byte string to compare.</param>
  309. /// <param name="rhs">The second byte string to compare.</param>
  310. /// <returns><c>true</c> if the byte strings are equal; false otherwise.</returns>
  311. public static bool operator ==(ByteString lhs, ByteString rhs)
  312. {
  313. if (ReferenceEquals(lhs, rhs))
  314. {
  315. return true;
  316. }
  317. if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
  318. {
  319. return false;
  320. }
  321. if (lhs.bytes.Length != rhs.bytes.Length)
  322. {
  323. return false;
  324. }
  325. for (int i = 0; i < lhs.Length; i++)
  326. {
  327. if (rhs.bytes[i] != lhs.bytes[i])
  328. {
  329. return false;
  330. }
  331. }
  332. return true;
  333. }
  334. /// <summary>
  335. /// Compares two byte strings for inequality.
  336. /// </summary>
  337. /// <param name="lhs">The first byte string to compare.</param>
  338. /// <param name="rhs">The second byte string to compare.</param>
  339. /// <returns><c>false</c> if the byte strings are equal; true otherwise.</returns>
  340. public static bool operator !=(ByteString lhs, ByteString rhs)
  341. {
  342. return !(lhs == rhs);
  343. }
  344. /// <summary>
  345. /// Compares this byte string with another object.
  346. /// </summary>
  347. /// <param name="obj">The object to compare this with.</param>
  348. /// <returns><c>true</c> if <paramref name="obj"/> refers to an equal <see cref="ByteString"/>; <c>false</c> otherwise.</returns>
  349. public override bool Equals(object obj)
  350. {
  351. return this == (obj as ByteString);
  352. }
  353. /// <summary>
  354. /// Returns a hash code for this object. Two equal byte strings
  355. /// will return the same hash code.
  356. /// </summary>
  357. /// <returns>A hash code for this object.</returns>
  358. public override int GetHashCode()
  359. {
  360. int ret = 23;
  361. foreach (byte b in bytes)
  362. {
  363. ret = (ret * 31) + b;
  364. }
  365. return ret;
  366. }
  367. /// <summary>
  368. /// Compares this byte string with another.
  369. /// </summary>
  370. /// <param name="other">The <see cref="ByteString"/> to compare this with.</param>
  371. /// <returns><c>true</c> if <paramref name="other"/> refers to an equal byte string; <c>false</c> otherwise.</returns>
  372. public bool Equals(ByteString other)
  373. {
  374. return this == other;
  375. }
  376. /// <summary>
  377. /// Used internally by CodedOutputStream to avoid creating a copy for the write
  378. /// </summary>
  379. internal void WriteRawBytesTo(CodedOutputStream outputStream)
  380. {
  381. outputStream.WriteRawBytes(bytes, 0, bytes.Length);
  382. }
  383. /// <summary>
  384. /// Copies the entire byte array to the destination array provided at the offset specified.
  385. /// </summary>
  386. public void CopyTo(byte[] array, int position)
  387. {
  388. ByteArray.Copy(bytes, 0, array, position, bytes.Length);
  389. }
  390. /// <summary>
  391. /// Writes the entire byte array to the provided stream
  392. /// </summary>
  393. public void WriteTo(Stream outputStream)
  394. {
  395. outputStream.Write(bytes, 0, bytes.Length);
  396. }
  397. }
  398. }