diff options
| author | 2026-02-21 10:05:19 +0800 | |
|---|---|---|
| committer | 2026-02-21 11:00:52 +0800 | |
| commit | 1334ea3e45aaf9d2620223215763443647aae5a7 (patch) | |
| tree | efe900b59f7f70ddc13d830ea027db7e7bd44ad6 /objectid | |
| parent | testgit: Add git repack (diff) | |
| signature | No signature | |
objectid: Add RawBytes
Diffstat (limited to 'objectid')
| -rw-r--r-- | objectid/objectid.go | 11 | ||||
| -rw-r--r-- | objectid/objectid_test.go | 23 |
2 files changed, 34 insertions, 0 deletions
diff --git a/objectid/objectid.go b/objectid/objectid.go index 4058bc20..a2fa28c4 100644 --- a/objectid/objectid.go +++ b/objectid/objectid.go @@ -159,6 +159,17 @@ func (id ObjectID) Bytes() []byte { return append([]byte(nil), id.data[:size]...) } +// RawBytes returns a direct byte slice view of the object ID bytes. +// +// The returned slice aliases the object ID's internal storage. Callers MUST +// treat it as read-only and MUST NOT modify its contents. +// +// Use Bytes when an independent copy is required. +func (id *ObjectID) RawBytes() []byte { + size := id.Size() + return id.data[:size:size] +} + // ParseHex parses an object ID from hex for the specified algorithm. func ParseHex(algo Algorithm, s string) (ObjectID, error) { var id ObjectID diff --git a/objectid/objectid_test.go b/objectid/objectid_test.go index ea4e9f44..7abeb963 100644 --- a/objectid/objectid_test.go +++ b/objectid/objectid_test.go @@ -127,6 +127,29 @@ func TestBytesReturnsCopy(t *testing.T) { } } +func TestRawBytesAliasesStorage(t *testing.T) { + t.Parallel() + + id, err := objectid.ParseHex(objectid.AlgorithmSHA1, "0123456789abcdef0123456789abcdef01234567") + if err != nil { + t.Fatalf("ParseHex failed: %v", err) + } + + b := id.RawBytes() + if len(b) != id.Size() { + t.Fatalf("RawBytes len = %d, want %d", len(b), id.Size()) + } + if cap(b) != len(b) { + t.Fatalf("RawBytes cap = %d, want %d", cap(b), len(b)) + } + + orig := id.String() + b[0] ^= 0xff + if id.String() == orig { + t.Fatalf("RawBytes should alias object ID storage") + } +} + func TestAlgorithmSum(t *testing.T) { t.Parallel() |
