ByteString.cs 17 KB

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