diff options
| author | Joe Richey joerichey@google.com <joerichey@google.com> | 2017-07-17 15:40:02 -0700 |
|---|---|---|
| committer | Joe Richey joerichey@google.com <joerichey@google.com> | 2017-07-17 15:40:02 -0700 |
| commit | 0b643ea0976f7bbd3cebef08c449090869701226 (patch) | |
| tree | 35c98f585201d48aecb5175763cd9330f7475997 /util/util_test.go | |
| parent | 6f32bbc8bf51d615ef23ed37aa40910ec23cd587 (diff) | |
util: Add conversions for byte/pointer arrays
Diffstat (limited to 'util/util_test.go')
| -rw-r--r-- | util/util_test.go | 41 |
1 files changed, 37 insertions, 4 deletions
diff --git a/util/util_test.go b/util/util_test.go index 33ce2ff..7739edd 100644 --- a/util/util_test.go +++ b/util/util_test.go @@ -20,19 +20,52 @@ package util import ( + "bytes" "testing" + "unsafe" ) const offset = 3 +var ( + byteArr = []byte{'a', 'b', 'c', 'd'} + ptrArr = []*int{&a, &b, &c, &d} + a = 1 + b = 2 + c = 3 + d = 4 +) + // Make sure the address behaves well under slicing func TestPtrOffset(t *testing.T) { - arr := []byte{'a', 'b', 'c', 'd'} - i1 := uintptr(Ptr(arr[offset:])) - i2 := uintptr(Ptr(arr)) + i1 := uintptr(Ptr(byteArr[offset:])) + i2 := uintptr(Ptr(byteArr)) if i1 != i2+offset { - t.Fatalf("pointers %v and %v do not have an offset of %v", i1, i2, offset) + t.Errorf("pointers %v and %v do not have an offset of %v", i1, i2, offset) + } +} + +// Tests that the ByteSlice method essentially reverses the Ptr method +func TestByteSlice(t *testing.T) { + ptr := Ptr(byteArr) + generatedArr := ByteSlice(ptr)[:len(byteArr)] + + if !bytes.Equal(byteArr, generatedArr) { + t.Errorf("generated array (%v) and original array (%v) do not agree", + generatedArr, byteArr) + } +} + +// Tests that the PointerSlice method correctly handles Go Pointers +func TestPointerSlice(t *testing.T) { + arrPtr := unsafe.Pointer(&ptrArr[0]) + + // Convert an array of unsafe pointers to int pointers. + for i, ptr := range PointerSlice(arrPtr)[:len(ptrArr)] { + if ptrArr[i] != (*int)(ptr) { + t.Errorf("generated array and original array disagree at %d", i) + } } } |