safeish

package module
v0.0.0-...-67c0a2c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 4 Imported by: 6

README

honnef.co/go/safeish

Somewhat safe unsafe helpers for Go. See documentation.

Documentation

Overview

Package safeish provides safe-ish unsafe helpers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsBytes

func AsBytes[E any, T *E](ptr T) []byte

AsBytes returns the underlying byte representation of the value pointed to by ptr.

func Cast

func Cast[Dst, Src any](x Src) Dst

Cast casts x from type Src to type Dst. It uses generics to provide a syntactic alternative to the common unsafe.Pointer conversion pattern.

Example:

var x Foo

_ = Cast[Bar](x)
// the above is identical to the below
_ = *(*Bar)(unsafe.Pointer(&x))

func FindNull

func FindNull(s *byte) int

func Index

func Index[E any, S ~[]E, Int constraints.Integer](ptr S, idx Int) *E

Index provides unsafe slice indexing without bounds checks. This function has absolutely no safety checks.

func SliceCast

func SliceCast[Dst ~[]DstE, Src ~[]SrcE, DstE, SrcE any](x Src) Dst

SliceCast casts a slice of underlying type []SrcE to a slice of underlying type []DstE, automatically adjusting the length and capacity based on the ratio of sizeof(SrcE) to sizeof(DstE). sizeof(DstE) may be both larger or smaller than sizeof(SrcE).

The ratio is expected to be integer, but non-integer ratios will not cause invalid memory accesses.

The type parameters are ordered so that at most the first one has to be provided explicitly.

SliceCast is fully inlinable.

Example
type S struct {
	A, B uint32
}

x := make([]byte, 32, 60)
s := SliceCast[[]S](x)
fmt.Println(len(s), cap(s))
Output:

4 7

func SliceCastPtr

func SliceCastPtr[Dst ~*DstE, Src ~[]SrcE, DstE, SrcE any](x Src) Dst

SliceCastPtr casts a slice of underlying type []SrcE to a pointer of underlying type *DstE to the slice's first element, or nil if the slice's capacity is 0. It ensures that the pointer doesn't extend past the end of the slice.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL