Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ObjectId.cs « LibGit2Sharp - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f93817a4841394a1c5fb53d1656f48ce3b11e64f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using System;
using System.Globalization;
using System.Linq;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// Uniquely identifies a <see cref="GitObject"/>.
    /// </summary>
    public sealed class ObjectId : IEquatable<ObjectId>
    {
        private readonly GitOid oid;
        private const int rawSize = GitOid.Size;
        private readonly string sha;

        /// <summary>
        /// Size of the string-based representation of a SHA-1.
        /// </summary>
        internal const int HexSize = rawSize * 2;

        private const string hexDigits = "0123456789abcdef";
        private static readonly byte[] reverseHexDigits = BuildReverseHexDigits();
        private static readonly Func<int, byte> byteConverter = i => reverseHexDigits[i - '0'];

        private static readonly LambdaEqualityHelper<ObjectId> equalityHelper =
            new LambdaEqualityHelper<ObjectId>(x => x.Sha);

        /// <summary>
        /// Zero ObjectId
        /// </summary>
        public static ObjectId Zero = new ObjectId(new string('0', HexSize));

        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectId"/> class.
        /// </summary>
        /// <param name="oid">The oid.</param>
        internal ObjectId(GitOid oid)
        {
            if (oid.Id == null || oid.Id.Length != rawSize)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "A non null array of {0} bytes is expected.", rawSize), "oid");
            }

            this.oid = oid;
            sha = ToString(oid.Id, oid.Id.Length * 2);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectId"/> class.
        /// </summary>
        /// <param name="rawId">The byte array.</param>
        public ObjectId(byte[] rawId)
            : this(new GitOid { Id = rawId })
        {
            Ensure.ArgumentNotNull(rawId, "rawId");
            Ensure.ArgumentConformsTo(rawId, b => b.Length == rawSize, "rawId");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectId"/> class.
        /// </summary>
        /// <param name="sha">The sha.</param>
        public ObjectId(string sha)
        {
            GitOid? parsedOid = BuildOidFrom(sha, true);

            if (!parsedOid.HasValue)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid Sha-1.", sha));
            }

            oid = parsedOid.Value;
            this.sha = sha;
        }

        internal GitOid Oid
        {
            get { return oid; }
        }

        /// <summary>
        /// Gets the raw id.
        /// </summary>
        public byte[] RawId
        {
            get { return oid.Id; }
        }

        /// <summary>
        /// Gets the sha.
        /// </summary>
        public string Sha
        {
            get { return sha; }
        }

        /// <summary>
        /// Converts the specified string representation of a Sha-1 to its <see cref="ObjectId"/> equivalent and returns a value that indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="sha">A string containing a Sha-1 to convert.</param>
        /// <param name="result">When this method returns, contains the <see cref="ObjectId"/> value equivalent to the Sha-1 contained in <paramref name="sha"/>, if the conversion succeeded, or <code>null</code> if the conversion failed.</param>
        /// <returns>true if the <paramref name="sha"/> parameter was converted successfully; otherwise, false.</returns>
        public static bool TryParse(string sha, out ObjectId result)
        {
            result = BuildOidFrom(sha, false);

            return result != null;
        }

        private static GitOid? BuildOidFrom(string sha, bool shouldThrowIfInvalid)
        {
            if (!LooksValid(sha, shouldThrowIfInvalid))
            {
                return null;
            }

            return ToOid(sha);
        }

        /// <summary>
        /// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="ObjectId"/>.
        /// </summary>
        /// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="ObjectId"/>.</param>
        /// <returns>True if the specified <see cref="Object"/> is equal to the current <see cref="ObjectId"/>; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            return Equals(obj as ObjectId);
        }

        /// <summary>
        /// Determines whether the specified <see cref="ObjectId"/> is equal to the current <see cref="ObjectId"/>.
        /// </summary>
        /// <param name="other">The <see cref="ObjectId"/> to compare with the current <see cref="ObjectId"/>.</param>
        /// <returns>True if the specified <see cref="ObjectId"/> is equal to the current <see cref="ObjectId"/>; otherwise, false.</returns>
        public bool Equals(ObjectId other)
        {
            return equalityHelper.Equals(this, other);
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        /// <returns>A 32-bit signed integer hash code.</returns>
        public override int GetHashCode()
        {
            return equalityHelper.GetHashCode(this);
        }

        /// <summary>
        /// Returns the <see cref="Sha"/>, a <see cref="String"/> representation of the current <see cref="ObjectId"/>.
        /// </summary>
        /// <returns>The <see cref="Sha"/> that represents the current <see cref="ObjectId"/>.</returns>
        public override string ToString()
        {
            return Sha;
        }

        /// <summary>
        /// Returns the <see cref="Sha"/>, a <see cref="String"/> representation of the current <see cref="ObjectId"/>.
        /// </summary>
        /// <param name="prefixLength">The number of chars the <see cref="Sha"/> should be truncated to.</param>
        /// <returns>The <see cref="Sha"/> that represents the current <see cref="ObjectId"/>.</returns>
        public string ToString(int prefixLength)
        {
            int normalizedLength = NormalizeLength(prefixLength);
            return Sha.Substring(0, Math.Min(Sha.Length, normalizedLength));
        }

        private static int NormalizeLength(int prefixLength)
        {
            if (prefixLength < 1)
            {
                return 1;
            }

            if (prefixLength > HexSize)
            {
                return HexSize;
            }

            return prefixLength;
        }

        /// <summary>
        /// Tests if two <see cref="ObjectId"/> are equal.
        /// </summary>
        /// <param name="left">First <see cref="ObjectId"/> to compare.</param>
        /// <param name="right">Second <see cref="ObjectId"/> to compare.</param>
        /// <returns>True if the two objects are equal; false otherwise.</returns>
        public static bool operator ==(ObjectId left, ObjectId right)
        {
            return Equals(left, right);
        }

        /// <summary>
        /// Tests if two <see cref="ObjectId"/> are different.
        /// </summary>
        /// <param name="left">First <see cref="ObjectId"/> to compare.</param>
        /// <param name="right">Second <see cref="ObjectId"/> to compare.</param>
        /// <returns>True if the two objects are different; false otherwise.</returns>
        public static bool operator !=(ObjectId left, ObjectId right)
        {
            return !Equals(left, right);
        }

        /// <summary>
        /// Create an <see cref="ObjectId"/> for the given <paramref name="sha"/>.
        /// </summary>
        /// <param name="sha">The object SHA.</param>
        /// <returns>An <see cref="ObjectId"/>, or null if <paramref name="sha"/> is null.</returns>
        public static explicit operator ObjectId(string sha)
        {
            return sha == null ? null : new ObjectId(sha);
        }

        private static byte[] BuildReverseHexDigits()
        {
            var bytes = new byte['f' - '0' + 1];

            for (int i = 0; i < 10; i++)
            {
                bytes[i] = (byte)i;
            }

            for (int i = 10; i < 16; i++)
            {
                bytes[i + 'a' - '0' - 0x0a] = (byte)(i);
            }

            return bytes;
        }

        internal static string ToString(byte[] id, int lengthInNibbles)
        {
            // Inspired from http://stackoverflow.com/questions/623104/c-byte-to-hex-string/3974535#3974535

            var c = new char[lengthInNibbles];

            for (int i = 0; i < (lengthInNibbles & -2); i++)
            {
                int index0 = i >> 1;
                var b = ((byte)(id[index0] >> 4));
                c[i++] = hexDigits[b];

                b = ((byte)(id[index0] & 0x0F));
                c[i] = hexDigits[b];
            }

            if ((lengthInNibbles & 1) == 1)
            {
                int index0 = lengthInNibbles >> 1;
                var b = ((byte)(id[index0] >> 4));
                c[lengthInNibbles - 1] = hexDigits[b];
            }

            return new string(c);
        }

        private static GitOid ToOid(string sha)
        {
            var bytes = new byte[rawSize];

            if ((sha.Length & 1) == 1)
            {
                sha += "0";
            }

            for (int i = 0; i < sha.Length; i++)
            {
                int c1 = byteConverter(sha[i++]) << 4;
                int c2 = byteConverter(sha[i]);

                bytes[i >> 1] = (byte)(c1 + c2);
            }

            var oid = new GitOid { Id = bytes };
            return oid;
        }

        private static bool LooksValid(string objectId, bool throwIfInvalid)
        {
            if (string.IsNullOrEmpty(objectId))
            {
                if (!throwIfInvalid)
                {
                    return false;
                }

                Ensure.ArgumentNotNullOrEmptyString(objectId, "objectId");
            }

            if ((objectId.Length != HexSize))
            {
                if (!throwIfInvalid)
                {
                    return false;
                }

                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, 
                                                          "'{0}' is not a valid object identifier. Its length should be {1}.", 
                                                          objectId, 
                                                          HexSize),
                                            "objectId");
            }

            return objectId.All(c => hexDigits.Contains(c.ToString(CultureInfo.InvariantCulture)));
        }

        /// <summary>
        /// Determine whether <paramref name="shortSha"/> matches the hexified
        /// representation of the first nibbles of this instance.
        /// <para>
        ///   Comparison is made in a case insensitive-manner.
        /// </para>
        /// </summary>
        /// <returns>True if this instance starts with <paramref name="shortSha"/>,
        /// false otherwise.</returns>
        public bool StartsWith(string shortSha)
        {
            Ensure.ArgumentNotNullOrEmptyString(shortSha, "shortSha");

            return Sha.StartsWith(shortSha, StringComparison.OrdinalIgnoreCase);
        }
    }
}