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