support.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Package support implements support functions and errors that are used by by other libsodium-go packages.
  2. package support
  3. import (
  4. "fmt"
  5. "unsafe"
  6. )
  7. // CheckSize checks if the length of a byte slice is equal to the expected length,
  8. // and panics when this is not the case.
  9. func CheckSize(buf []byte, expected int, descrip string) {
  10. if len(buf) != expected {
  11. panic(fmt.Sprintf("Incorrect %s buffer size, expected (%d), got (%d).", descrip, expected, len(buf)))
  12. }
  13. }
  14. // CheckSizeMin checks if the length of a byte slice is greater or equal than a minimum length,
  15. // and panics when this is not the case.
  16. func CheckSizeMin(buf []byte, min int, descrip string) {
  17. if len(buf) < min {
  18. panic(fmt.Sprintf("Incorrect %s buffer size, expected (>%d), got (%d).", descrip, min, len(buf)))
  19. }
  20. }
  21. // CheckIntInRange checks if the size of an integer is between a lower and upper boundaries.
  22. func CheckIntInRange(n int, min int, max int, descrip string) {
  23. if n < min || n > max {
  24. panic(fmt.Sprintf("Incorrect %s size, expected (%d - %d), got (%d).", descrip, min, max, n))
  25. }
  26. }
  27. // CheckSizeInRange checks if the length of a byte slice is between a lower and upper boundaries.
  28. func CheckSizeInRange(buf []byte, min int, max int, descrip string) {
  29. if len(buf) < min || len(buf) > max {
  30. panic(fmt.Sprintf("Incorrect %s buffer size, expected (%d - %d), got (%d).", descrip, min, max, len(buf)))
  31. }
  32. }
  33. // CheckSizeGreaterOrEqual checks if the length of a byte slice is greater or equal to that of a second byte slice.
  34. func CheckSizeGreaterOrEqual(a, b []byte, aDescription, bDescription string) {
  35. if len(a) < len(b) {
  36. panic(fmt.Sprintf("%s smaller than %s", aDescription, bDescription))
  37. }
  38. }
  39. // NilPanic is a shorthand that results in a panic when called with true.
  40. func NilPanic(t bool, description string) {
  41. if t {
  42. panic(description + " is a nil pointer")
  43. }
  44. }
  45. // BytePointer returns a pointer to the start of a byte slice, or nil when the slice is empty.
  46. func BytePointer(b []byte) *uint8 {
  47. if len(b) > 0 {
  48. return &b[0]
  49. } else {
  50. return nil
  51. }
  52. }
  53. // AlignedSlice returns a memory aligned slice
  54. func AlignedSlice(size, alignment int) []byte {
  55. slice := make([]byte, size+alignment)
  56. offset := alignment - int(uintptr(unsafe.Pointer(&slice[0])))%alignment
  57. return slice[offset : offset+size]
  58. }