Skip to content

Commit 894974b

Browse files
committed
crbytes: add AllocAligned, CopyAligned
Add facilities for allocating byte slices such that the address of the first byte of the slice is aligned.
1 parent 3474b32 commit 894974b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

crbytes/crbytes.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Copyright 2024 The Cockroach Authors.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12+
// implied. See the License for the specific language governing
13+
// permissions and limitations under the License.
14+
15+
package crbytes
16+
17+
import (
18+
"fmt"
19+
"unsafe"
20+
)
21+
22+
// AllocAligned allocates a new byte slice of length n, ensuring the address of
23+
// the beginning of the slice is word aligned. Go does not guarantee that a
24+
// simple make([]byte, n) is aligned.
25+
func AllocAligned(n int) []byte {
26+
if n == 0 {
27+
return nil
28+
}
29+
a := make([]uint64, (n+7)/8)
30+
b := unsafe.Slice((*byte)(unsafe.Pointer(&a[0])), n)
31+
32+
// Verify alignment.
33+
ptr := uintptr(unsafe.Pointer(&b[0]))
34+
if ptr&7 != 0 {
35+
panic(fmt.Sprintf("allocated []uint64 slice not 8-aligned: pointer %p", &b[0]))
36+
}
37+
return b
38+
}
39+
40+
// CopyAligned copies the provided byte slice into an aligned byte slice of the
41+
// same length.
42+
func CopyAligned(s []byte) []byte {
43+
dst := AllocAligned(len(s))
44+
copy(dst, s)
45+
return dst
46+
}

0 commit comments

Comments
 (0)