ByteString.cs 15 KB

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