Skip to content

Commit 92fde78

Browse files
committed
Make GitOid blittable
GitOid held its bytes in a managed array marshaled as ByValArray, so every P/Invoke taking a ref or out GitOid went through a marshaling stub, and each ref call allocated a new 20 byte array when copying the result back. GitOid now stores the bytes in a fixed buffer, as git_oid already does, so those calls pass a pointer straight through. ObjectId keeps the GitOid inline instead of a separate array. RawId creates its array on first access, or returns the array the ObjectId was constructed from, and returns the same array on every call as before.
1 parent eaa698d commit 92fde78

5 files changed

Lines changed: 72 additions & 48 deletions

File tree

‎LibGit2Sharp/BlameHunkCollection.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,15 @@ internal unsafe BlameHunkCollection(Repository repo, RepositoryHandle repoHandle
3737
{
3838
fixed (byte* p = rawopts.newest_commit.Id)
3939
{
40-
Marshal.Copy(repo.Committish(options.StartingAt).Oid.Id, 0, new IntPtr(p), git_oid.Size);
40+
*(GitOid*)p = repo.Committish(options.StartingAt).Oid;
4141
}
4242
}
4343

4444
if (options.StoppingAt != null)
4545
{
4646
fixed (byte* p = rawopts.oldest_commit.Id)
4747
{
48-
Marshal.Copy(repo.Committish(options.StoppingAt).Oid.Id, 0, new IntPtr(p), git_oid.Size);
48+
*(GitOid*)p = repo.Committish(options.StoppingAt).Oid;
4949
}
5050
}
5151

‎LibGit2Sharp/Core/GitOid.cs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System.Runtime.InteropServices;
2-
3-
namespace LibGit2Sharp.Core
1+
namespace LibGit2Sharp.Core
42
{
53
internal struct git_oid
64
{
@@ -11,7 +9,11 @@ internal struct git_oid
119
/// <summary>
1210
/// Represents a unique id in git which is the sha1 hash of this id's content.
1311
/// </summary>
14-
internal struct GitOid
12+
/// <remarks>
13+
/// The bytes are stored inline, so the struct is blittable: it is passed to and
14+
/// from libgit2 without being copied or allocating a managed array.
15+
/// </remarks>
16+
internal unsafe struct GitOid
1517
{
1618
/// <summary>
1719
/// Number of bytes in the Id.
@@ -21,8 +23,7 @@ internal struct GitOid
2123
/// <summary>
2224
/// The raw binary 20 byte Id.
2325
/// </summary>
24-
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Size)]
25-
public byte[] Id;
26+
public fixed byte Id[Size];
2627

2728
public static implicit operator ObjectId(GitOid oid)
2829
{

‎LibGit2Sharp/Index.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ private unsafe void AddEntryToTheIndex(string path, ObjectId id, Mode mode)
249249
mode = (uint)mode,
250250
path = (char*)pathPtr,
251251
};
252-
Marshal.Copy(id.RawId, 0, new IntPtr(indexEntry.id.Id), GitOid.Size);
252+
*(GitOid*)indexEntry.id.Id = id.Oid;
253253

254254
Proxy.git_index_add(handle, &indexEntry);
255255
EncodingMarshaler.Cleanup(pathPtr);

‎LibGit2Sharp/ObjectId.cs‎

Lines changed: 55 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Globalization;
33
using System.Linq;
4+
using System.Threading;
45
using LibGit2Sharp.Core;
56

67
namespace LibGit2Sharp
@@ -14,6 +15,10 @@ public sealed class ObjectId : IEquatable<ObjectId>
1415
private const int rawSize = GitOid.Size;
1516
private readonly string sha;
1617

18+
// The bytes live inline in oid. This array is only created when RawId is read,
19+
// so ids that never expose their raw bytes don't carry a second copy of them.
20+
private byte[] rawId;
21+
1722
/// <summary>
1823
/// Size of the string-based representation of a SHA-1.
1924
/// </summary>
@@ -37,24 +42,27 @@ public sealed class ObjectId : IEquatable<ObjectId>
3742
/// <param name="oid">The oid.</param>
3843
internal ObjectId(GitOid oid)
3944
{
40-
if (oid.Id == null || oid.Id.Length != rawSize)
41-
{
42-
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "A non null array of {0} bytes is expected.", rawSize), nameof(oid));
43-
}
44-
4545
this.oid = oid;
46-
sha = ToString(oid.Id, oid.Id.Length * 2);
46+
sha = ToString(oid, HexSize);
4747
}
4848

4949
/// <summary>
5050
/// Initializes a new instance of the <see cref="ObjectId"/> class.
5151
/// </summary>
5252
/// <param name="rawId">The byte array.</param>
53-
public ObjectId(byte[] rawId)
54-
: this(new GitOid { Id = rawId })
53+
public unsafe ObjectId(byte[] rawId)
5554
{
5655
Ensure.ArgumentNotNull(rawId, "rawId");
5756
Ensure.ArgumentConformsTo(rawId, b => b.Length == rawSize, "rawId");
57+
58+
fixed (byte* source = rawId)
59+
{
60+
oid = *(GitOid*)source;
61+
}
62+
63+
// Keep the caller's array so RawId keeps returning it, as it always has.
64+
this.rawId = rawId;
65+
sha = ToString(oid, HexSize);
5866
}
5967

6068
internal static unsafe ObjectId BuildFromPtr(IntPtr ptr)
@@ -69,18 +77,8 @@ internal static unsafe ObjectId BuildFromPtr(git_oid* id)
6977

7078
internal unsafe ObjectId(byte* rawId)
7179
{
72-
byte[] id = new byte[GitOid.Size];
73-
74-
fixed (byte* p = id)
75-
{
76-
for (int i = 0; i < rawSize; i++)
77-
{
78-
p[i] = rawId[i];
79-
}
80-
}
81-
82-
this.oid = new GitOid { Id = id };
83-
this.sha = ToString(oid.Id, oid.Id.Length * 2);
80+
oid = *(GitOid*)rawId;
81+
sha = ToString(oid, HexSize);
8482
}
8583

8684
/// <summary>
@@ -110,7 +108,28 @@ internal GitOid Oid
110108
/// </summary>
111109
public byte[] RawId
112110
{
113-
get { return oid.Id; }
111+
get
112+
{
113+
if (rawId == null)
114+
{
115+
// CompareExchange keeps every caller on the same array if two threads race here.
116+
Interlocked.CompareExchange(ref rawId, CreateRawId(), null);
117+
}
118+
119+
return rawId;
120+
}
121+
}
122+
123+
private unsafe byte[] CreateRawId()
124+
{
125+
var bytes = new byte[rawSize];
126+
127+
fixed (byte* destination = bytes)
128+
{
129+
*(GitOid*)destination = oid;
130+
}
131+
132+
return bytes;
114133
}
115134

116135
/// <summary>
@@ -257,35 +276,43 @@ private static byte[] BuildReverseHexDigits()
257276
return bytes;
258277
}
259278

260-
internal static string ToString(byte[] id, int lengthInNibbles)
279+
internal static unsafe string ToString(GitOid id, int lengthInNibbles)
261280
{
262281
// Inspired from http://stackoverflow.com/questions/623104/c-byte-to-hex-string/3974535#3974535
263282

283+
// Indexing the inline buffer isn't bounds checked, so check the length up front.
284+
if ((uint)lengthInNibbles > HexSize)
285+
{
286+
throw new ArgumentOutOfRangeException(nameof(lengthInNibbles));
287+
}
288+
264289
var c = new char[lengthInNibbles];
265290

266291
for (int i = 0; i < (lengthInNibbles & -2); i++)
267292
{
268293
int index0 = i >> 1;
269-
var b = ((byte)(id[index0] >> 4));
294+
var b = ((byte)(id.Id[index0] >> 4));
270295
c[i++] = hexDigits[b];
271296

272-
b = ((byte)(id[index0] & 0x0F));
297+
b = ((byte)(id.Id[index0] & 0x0F));
273298
c[i] = hexDigits[b];
274299
}
275300

276301
if ((lengthInNibbles & 1) == 1)
277302
{
278303
int index0 = lengthInNibbles >> 1;
279-
var b = ((byte)(id[index0] >> 4));
304+
var b = ((byte)(id.Id[index0] >> 4));
280305
c[lengthInNibbles - 1] = hexDigits[b];
281306
}
282307

283308
return new string(c);
284309
}
285310

286-
private static GitOid ToOid(string sha)
311+
// Only called once LooksValid has checked sha is exactly HexSize characters,
312+
// which keeps the writes inside the 20 byte buffer.
313+
private static unsafe GitOid ToOid(string sha)
287314
{
288-
var bytes = new byte[rawSize];
315+
var oid = new GitOid();
289316

290317
if ((sha.Length & 1) == 1)
291318
{
@@ -297,10 +324,9 @@ private static GitOid ToOid(string sha)
297324
int c1 = byteConverter(sha[i++]) << 4;
298325
int c2 = byteConverter(sha[i]);
299326

300-
bytes[i >> 1] = (byte)(c1 + c2);
327+
oid.Id[i >> 1] = (byte)(c1 + c2);
301328
}
302329

303-
var oid = new GitOid { Id = bytes };
304330
return oid;
305331
}
306332

‎LibGit2Sharp/OdbBackend.cs‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ private unsafe static int ReadPrefix(
326326

327327
try
328328
{
329-
var shortSha = ObjectId.ToString(short_oid.Id, (int)len);
329+
var shortSha = ObjectId.ToString(short_oid, (int)len);
330330

331331
ObjectId oid;
332332
ObjectType objectType;
@@ -343,7 +343,7 @@ private unsafe static int ReadPrefix(
343343
return (int)GitErrorCode.Error;
344344
}
345345

346-
out_oid.Id = oid.RawId;
346+
out_oid = oid.Oid;
347347
len_p = new UIntPtr((ulong)memoryStream.Capacity);
348348
type_p = objectType.ToGitObjectType();
349349

@@ -536,14 +536,14 @@ private static int ExistsPrefix(
536536
try
537537
{
538538
ObjectId found;
539-
var shortSha = ObjectId.ToString(short_oid.Id, (int)len);
539+
var shortSha = ObjectId.ToString(short_oid, (int)len);
540540

541-
found_oid.Id = ObjectId.Zero.RawId;
541+
found_oid = ObjectId.Zero.Oid;
542542
int result = odbBackend.ExistsPrefix(shortSha, out found);
543543

544544
if (result == (int)GitErrorCode.Ok)
545545
{
546-
found_oid.Id = found.RawId;
546+
found_oid = found.Oid;
547547
}
548548

549549
return result;
@@ -616,12 +616,9 @@ public ForeachState(GitOdbBackend.foreach_callback_callback cb, IntPtr data)
616616

617617
private unsafe int CallbackMethod(ObjectId id)
618618
{
619-
var oid = id.RawId;
619+
GitOid oid = id.Oid;
620620

621-
fixed (void* ptr = &oid[0])
622-
{
623-
return cb(new IntPtr(ptr), data);
624-
}
621+
return cb(new IntPtr(&oid), data);
625622
}
626623

627624
public readonly ForEachCallback ManagedCallback;

0 commit comments

Comments
 (0)