ByteString.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. [SecuritySafeCritical]
  230. public static ByteString CopyFrom(ReadOnlySpan<byte> bytes)
  231. {
  232. return new ByteString(bytes.ToArray());
  233. }
  234. #endif
  235. /// <summary>
  236. /// Creates a new <see cref="ByteString" /> by encoding the specified text with
  237. /// the given encoding.
  238. /// </summary>
  239. public static ByteString CopyFrom(string text, Encoding encoding)
  240. {
  241. return new ByteString(encoding.GetBytes(text));
  242. }
  243. /// <summary>
  244. /// Creates a new <see cref="ByteString" /> by encoding the specified text in UTF-8.
  245. /// </summary>
  246. public static ByteString CopyFromUtf8(string text)
  247. {
  248. return CopyFrom(text, Encoding.UTF8);
  249. }
  250. /// <summary>
  251. /// Returns the byte at the given index.
  252. /// </summary>
  253. public byte this[int index]
  254. {
  255. get { return bytes[index]; }
  256. }
  257. /// <summary>
  258. /// Converts this <see cref="ByteString"/> into a string by applying the given encoding.
  259. /// </summary>
  260. /// <remarks>
  261. /// This method should only be used to convert binary data which was the result of encoding
  262. /// text with the given encoding.
  263. /// </remarks>
  264. /// <param name="encoding">The encoding to use to decode the binary data into text.</param>
  265. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  266. public string ToString(Encoding encoding)
  267. {
  268. return encoding.GetString(bytes, 0, bytes.Length);
  269. }
  270. /// <summary>
  271. /// Converts this <see cref="ByteString"/> into a string by applying the UTF-8 encoding.
  272. /// </summary>
  273. /// <remarks>
  274. /// This method should only be used to convert binary data which was the result of encoding
  275. /// text with UTF-8.
  276. /// </remarks>
  277. /// <returns>The result of decoding the binary data with the given decoding.</returns>
  278. public string ToStringUtf8()
  279. {
  280. return ToString(Encoding.UTF8);
  281. }
  282. /// <summary>
  283. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  284. /// </summary>
  285. /// <returns>An iterator over the bytes in this object.</returns>
  286. public IEnumerator<byte> GetEnumerator()
  287. {
  288. return ((IEnumerable<byte>) bytes).GetEnumerator();
  289. }
  290. /// <summary>
  291. /// Returns an iterator over the bytes in this <see cref="ByteString"/>.
  292. /// </summary>
  293. /// <returns>An iterator over the bytes in this object.</returns>
  294. IEnumerator IEnumerable.GetEnumerator()
  295. {
  296. return GetEnumerator();
  297. }
  298. /// <summary>
  299. /// Creates a CodedInputStream from this ByteString's data.
  300. /// </summary>
  301. public CodedInputStream CreateCodedInput()
  302. {
  303. // We trust CodedInputStream not to reveal the provided byte array or modify it
  304. return new CodedInputStream(bytes);
  305. }
  306. /// <summary>
  307. /// Compares two byte strings for equality.
  308. /// </summary>
  309. /// <param name="lhs">The first byte string to compare.</param>
  310. /// <param name="rhs">The second byte string to compare.</param>
  311. /// <returns><c>true</c> if the byte strings are equal; false otherwise.</returns>
  312. public static bool operator ==(ByteString lhs, ByteString rhs)
  313. {
  314. if (ReferenceEquals(lhs, rhs))
  315. {
  316. return true;
  317. }
  318. if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
  319. {
  320. return false;
  321. }
  322. if (lhs.bytes.Length != rhs.bytes.Length)
  323. {
  324. return false;
  325. }
  326. for (int i = 0; i < lhs.Length; i++)
  327. {
  328. if (rhs.bytes[i] != lhs.bytes[i])
  329. {
  330. return false;
  331. }
  332. }
  333. return true;
  334. }
  335. /// <summary>
  336. /// Compares two byte strings for inequality.
  337. /// </summary>
  338. /// <param name="lhs">The first byte string to compare.</param>
  339. /// <param name="rhs">The second byte string to compare.</param>
  340. /// <returns><c>false</c> if the byte strings are equal; true otherwise.</returns>
  341. public static bool operator !=(ByteString lhs, ByteString rhs)
  342. {
  343. return !(lhs == rhs);
  344. }
  345. /// <summary>
  346. /// Compares this byte string with another object.
  347. /// </summary>
  348. /// <param name="obj">The object to compare this with.</param>
  349. /// <returns><c>true</c> if <paramref name="obj"/> refers to an equal <see cref="ByteString"/>; <c>false</c> otherwise.</returns>
  350. public override bool Equals(object obj)
  351. {
  352. return this == (obj as ByteString);
  353. }
  354. /// <summary>
  355. /// Returns a hash code for this object. Two equal byte strings
  356. /// will return the same hash code.
  357. /// </summary>
  358. /// <returns>A hash code for this object.</returns>
  359. public override int GetHashCode()
  360. {
  361. int ret = 23;
  362. foreach (byte b in bytes)
  363. {
  364. ret = (ret * 31) + b;
  365. }
  366. return ret;
  367. }
  368. /// <summary>
  369. /// Compares this byte string with another.
  370. /// </summary>
  371. /// <param name="other">The <see cref="ByteString"/> to compare this with.</param>
  372. /// <returns><c>true</c> if <paramref name="other"/> refers to an equal byte string; <c>false</c> otherwise.</returns>
  373. public bool Equals(ByteString other)
  374. {
  375. return this == other;
  376. }
  377. /// <summary>
  378. /// Used internally by CodedOutputStream to avoid creating a copy for the write
  379. /// </summary>
  380. internal void WriteRawBytesTo(CodedOutputStream outputStream)
  381. {
  382. outputStream.WriteRawBytes(bytes, 0, bytes.Length);
  383. }
  384. /// <summary>
  385. /// Copies the entire byte array to the destination array provided at the offset specified.
  386. /// </summary>
  387. public void CopyTo(byte[] array, int position)
  388. {
  389. ByteArray.Copy(bytes, 0, array, position, bytes.Length);
  390. }
  391. /// <summary>
  392. /// Writes the entire byte array to the provided stream
  393. /// </summary>
  394. public void WriteTo(Stream outputStream)
  395. {
  396. outputStream.Write(bytes, 0, bytes.Length);
  397. }
  398. }
  399. }