Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.ExtLibs/HeuristicLab.ProtobufCS/2.4.1/ProtobufCS/src/ProtocolBuffers/ByteString.cs @ 13400

Last change on this file since 13400 was 8295, checked in by abeham, 12 years ago

#1897:

  • Removed protocol buffers 0.9.1
  • Added protocol buffers 2.4.1
  • Updated proto processing command
File size: 9.0 KB
Line 
1#region Copyright notice and license
2
3// Protocol Buffers - Google's data interchange format
4// Copyright 2008 Google Inc.  All rights reserved.
5// http://github.com/jskeet/dotnet-protobufs/
6// Original C++/Java/Python code:
7// http://code.google.com/p/protobuf/
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions are
11// met:
12//
13//     * Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//     * Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following disclaimer
17// in the documentation and/or other materials provided with the
18// distribution.
19//     * Neither the name of Google Inc. nor the names of its
20// contributors may be used to endorse or promote products derived from
21// this software without specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35#endregion
36
37using System;
38using System.Collections;
39using System.Collections.Generic;
40using System.IO;
41using System.Text;
42
43namespace Google.ProtocolBuffers
44{
45    /// <summary>
46    /// Immutable array of bytes.
47    /// TODO(jonskeet): Implement the common collection interfaces?
48    /// </summary>
49    public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString>
50    {
51        private static readonly ByteString empty = new ByteString(new byte[0]);
52
53        private readonly byte[] bytes;
54
55        /// <summary>
56        /// Internal use only.  Ensure that the provided array is not mutated and belongs to this instance.
57        /// </summary>
58        internal static ByteString AttachBytes(byte[] bytes)
59        {
60            return new ByteString(bytes);
61        }
62
63        /// <summary>
64        /// Constructs a new ByteString from the given byte array. The array is
65        /// *not* copied, and must not be modified after this constructor is called.
66        /// </summary>
67        private ByteString(byte[] bytes)
68        {
69            this.bytes = bytes;
70        }
71
72        /// <summary>
73        /// Returns an empty ByteString.
74        /// </summary>
75        public static ByteString Empty
76        {
77            get { return empty; }
78        }
79
80        /// <summary>
81        /// Returns the length of this ByteString in bytes.
82        /// </summary>
83        public int Length
84        {
85            get { return bytes.Length; }
86        }
87
88        public bool IsEmpty
89        {
90            get { return Length == 0; }
91        }
92
93        public byte[] ToByteArray()
94        {
95            return (byte[]) bytes.Clone();
96        }
97
98        public string ToBase64()
99        {
100            return Convert.ToBase64String(bytes);
101        }
102
103        /// <summary>
104        /// Constructs a ByteString from the Base64 Encoded String.
105        /// </summary>
106        public static ByteString FromBase64(string bytes)
107        {
108            return new ByteString(Convert.FromBase64String(bytes));
109        }
110
111        /// <summary>
112        /// Constructs a ByteString from the given array. The contents
113        /// are copied, so further modifications to the array will not
114        /// be reflected in the returned ByteString.
115        /// </summary>
116        public static ByteString CopyFrom(byte[] bytes)
117        {
118            return new ByteString((byte[]) bytes.Clone());
119        }
120
121        /// <summary>
122        /// Constructs a ByteString from a portion of a byte array.
123        /// </summary>
124        public static ByteString CopyFrom(byte[] bytes, int offset, int count)
125        {
126            byte[] portion = new byte[count];
127            ByteArray.Copy(bytes, offset, portion, 0, count);
128            return new ByteString(portion);
129        }
130
131        /// <summary>
132        /// Creates a new ByteString by encoding the specified text with
133        /// the given encoding.
134        /// </summary>
135        public static ByteString CopyFrom(string text, Encoding encoding)
136        {
137            return new ByteString(encoding.GetBytes(text));
138        }
139
140        /// <summary>
141        /// Creates a new ByteString by encoding the specified text in UTF-8.
142        /// </summary>
143        public static ByteString CopyFromUtf8(string text)
144        {
145            return CopyFrom(text, Encoding.UTF8);
146        }
147
148        /// <summary>
149        /// Retuns the byte at the given index.
150        /// </summary>
151        public byte this[int index]
152        {
153            get { return bytes[index]; }
154        }
155
156        public string ToString(Encoding encoding)
157        {
158            return encoding.GetString(bytes, 0, bytes.Length);
159        }
160
161        public string ToStringUtf8()
162        {
163            return ToString(Encoding.UTF8);
164        }
165
166        public IEnumerator<byte> GetEnumerator()
167        {
168            return ((IEnumerable<byte>) bytes).GetEnumerator();
169        }
170
171        IEnumerator IEnumerable.GetEnumerator()
172        {
173            return GetEnumerator();
174        }
175
176        /// <summary>
177        /// Creates a CodedInputStream from this ByteString's data.
178        /// </summary>
179        public CodedInputStream CreateCodedInput()
180        {
181            // We trust CodedInputStream not to reveal the provided byte array or modify it
182            return CodedInputStream.CreateInstance(bytes);
183        }
184
185        // TODO(jonskeet): CopyTo if it turns out to be required
186
187        public override bool Equals(object obj)
188        {
189            ByteString other = obj as ByteString;
190            if (obj == null)
191            {
192                return false;
193            }
194            return Equals(other);
195        }
196
197        public override int GetHashCode()
198        {
199            int ret = 23;
200            foreach (byte b in bytes)
201            {
202                ret = (ret << 8) | b;
203            }
204            return ret;
205        }
206
207        public bool Equals(ByteString other)
208        {
209            if (other.bytes.Length != bytes.Length)
210            {
211                return false;
212            }
213            for (int i = 0; i < bytes.Length; i++)
214            {
215                if (other.bytes[i] != bytes[i])
216                {
217                    return false;
218                }
219            }
220            return true;
221        }
222
223        /// <summary>
224        /// Builder for ByteStrings which allows them to be created without extra
225        /// copying being involved. This has to be a nested type in order to have access
226        /// to the private ByteString constructor.
227        /// </summary>
228        internal sealed class CodedBuilder
229        {
230            private readonly CodedOutputStream output;
231            private readonly byte[] buffer;
232
233            internal CodedBuilder(int size)
234            {
235                buffer = new byte[size];
236                output = CodedOutputStream.CreateInstance(buffer);
237            }
238
239            internal ByteString Build()
240            {
241                output.CheckNoSpaceLeft();
242
243                // We can be confident that the CodedOutputStream will not modify the
244                // underlying bytes anymore because it already wrote all of them.  So,
245                // no need to make a copy.
246                return new ByteString(buffer);
247            }
248
249            internal CodedOutputStream CodedOutput
250            {
251                get { return output; }
252            }
253        }
254
255        /// <summary>
256        /// Used internally by CodedOutputStream to avoid creating a copy for the write
257        /// </summary>
258        internal void WriteRawBytesTo(CodedOutputStream outputStream)
259        {
260            outputStream.WriteRawBytes(bytes, 0, bytes.Length);
261        }
262
263        /// <summary>
264        /// Copies the entire byte array to the destination array provided at the offset specified.
265        /// </summary>
266        public void CopyTo(byte[] array, int position)
267        {
268            ByteArray.Copy(bytes, 0, array, position, bytes.Length);
269        }
270
271        /// <summary>
272        /// Writes the entire byte array to the provided stream
273        /// </summary>
274        public void WriteTo(Stream outputStream)
275        {
276            outputStream.Write(bytes, 0, bytes.Length);
277        }
278    }
279}
Note: See TracBrowser for help on using the repository browser.