func BenchmarkOutMessageReset(b *testing.B) { // A single buffer, which should fit in some level of CPU cache. b.Run("Single buffer", func(b *testing.B) { var om OutMessage for i := 0; i < b.N; i++ { om.Reset() } b.SetBytes(int64(unsafe.Offsetof(om.payload))) }) // Many megabytes worth of buffers, which should defeat the CPU cache. b.Run("Many buffers", func(b *testing.B) { // The number of messages; intentionally a power of two. const numMessages = 128 var oms [numMessages]OutMessage if s := unsafe.Sizeof(oms); s < 128<<20 { panic(fmt.Sprintf("Array is too small; total size: %d", s)) } for i := 0; i < b.N; i++ { oms[i%numMessages].Reset() } b.SetBytes(int64(unsafe.Offsetof(oms[0].payload))) }) }
func testDeep() { var s1 S1 switch { case unsafe.Offsetof(s1.A) != 0: panic("unsafe.Offsetof(s1.A) != 0") case unsafe.Offsetof(s1.B) != 4: panic("unsafe.Offsetof(s1.B) != 4") case unsafe.Offsetof(s1.C) != 8: panic("unsafe.Offsetof(s1.C) != 8") case unsafe.Offsetof(s1.D) != 12: panic("unsafe.Offsetof(s1.D) != 12") case unsafe.Offsetof(s1.E) != 16: panic("unsafe.Offsetof(s1.E) != 16") case unsafe.Offsetof(s1.F) != 20: panic("unsafe.Offsetof(s1.F) != 20") case unsafe.Offsetof(s1.G) != 24: panic("unsafe.Offsetof(s1.G) != 24") case unsafe.Offsetof(s1.H) != 28: panic("unsafe.Offsetof(s1.H) != 28") case unsafe.Offsetof(s1.S1) != 32: panic("unsafe.Offsetof(s1.S1) != 32") case unsafe.Offsetof(s1.S1.S2.S3.S4.S5.S6.S7.S8.S1.S2) != 4: panic("unsafe.Offsetof(s1.S1.S2.S3.S4.S5.S6.S7.S8.S1.S2) != 4") } }
func main() { v := "12139a532f3c29d678d879135532843838" log.Println(v) log.Println([]byte(v)) v2 := hex2bytes(v) log.Println(v2) log.Println([]byte(v2)) log.Println(revert([]byte(v2))) log.Println("@sizeOf v:", unsafe.Sizeof(v)) log.Println("@sizeOf v2:", unsafe.Sizeof(&v2)) v3 := `// 定義一個 Student 的結構 type Student struct { name string id int grade float32 friends []string } // 宣告一個內容為空的 student 變數代表這個結構 student := Student{}` log.Println("@sizeOf v3:", unsafe.Sizeof(&v3)) log.Println("@cap v:", cap([]byte(v))) log.Println("@cap v2:", cap([]byte(v2))) log.Println("@cap v3:", cap([]byte(v3))) s1 := &SH{v: v} s2 := &SH{v: v2} s3 := &SH{v: v3} log.Println("szo s1:", unsafe.Sizeof(s1.v)) log.Println("szo s2:", unsafe.Sizeof(s2.v)) log.Println("szo s3:", unsafe.Sizeof(s3.v)) log.Println("szo s1:", unsafe.Offsetof(s1.v)) log.Println("szo s2:", unsafe.Offsetof(s2.v)) log.Println("szo s3:", unsafe.Offsetof(s3.v)) }
func NewRenderer(bufferSize int) (r *Renderer, err error) { var ( instance renderInstance instanceStride = unsafe.Sizeof(instance) ) r = &Renderer{ shader: core.NewProgram(), bufferSize: bufferSize, buffer: make([]renderInstance, bufferSize), stride: instanceStride, } if err = r.shader.Load(VERTEX, FRAGMENT); err != nil { return } r.shader.Bind() r.vbo = core.NewArrayBuffer() r.shader.Attrib("f_InstanceFrame", instanceStride).Float(unsafe.Offsetof(instance.frame), 1) r.shader.Attrib("m_Model", instanceStride).Mat4(unsafe.Offsetof(instance.model), 1) r.shader.Attrib("v_Color", instanceStride).Vec4(unsafe.Offsetof(instance.color), 1) r.textureData = r.shader.UniformBlock("TextureData", 1) r.uView = r.shader.Uniform("m_View") r.uProj = r.shader.Uniform("m_Projection") if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func main() { example := &Example{ BoolValue: true, } exampleNext := &Example{ BoolValue: true, } alignmentBoundary := unsafe.Alignof(example) sizeBool := unsafe.Sizeof(example.BoolValue) offsetBool := unsafe.Offsetof(example.BoolValue) sizeBoolNext := unsafe.Sizeof(exampleNext.BoolValue) offsetBoolNext := unsafe.Offsetof(exampleNext.BoolValue) fmt.Printf("Alignment Boundary: %d\n", alignmentBoundary) fmt.Printf("BoolValue = Size: %d Offset: %d Addr: %v\n", sizeBool, offsetBool, &example.BoolValue) fmt.Printf("Next = Size: %d Offset: %d Addr: %v\n", sizeBoolNext, offsetBoolNext, &exampleNext.BoolValue) }
// main is the entry point for the application. func main() { var e example alignmentBoundary := unsafe.Alignof(e) sizeE := unsafe.Sizeof(e) sizeBool := unsafe.Sizeof(e.flag) offsetBool := unsafe.Offsetof(e.flag) sizeInt := unsafe.Sizeof(e.counter) offsetInt := unsafe.Offsetof(e.counter) sizeBool2 := unsafe.Sizeof(e.flag2) offsetBool2 := unsafe.Offsetof(e.flag2) sizeFloat := unsafe.Sizeof(e.pi) offsetFloat := unsafe.Offsetof(e.pi) fmt.Printf("Alignment(%d):\tSize: %d\n", alignmentBoundary, sizeE) fmt.Printf("flag:\t\tSize: %d\t\tOffset: %d\tAddr: %v\n", sizeBool, offsetBool, &e.flag) fmt.Printf("counter:\tSize: %d\t\tOffset: %d\tAddr: %v\n", sizeInt, offsetInt, &e.counter) fmt.Printf("flag1:\t\tSize: %d\t\tOffset: %d\tAddr: %v\n", sizeBool2, offsetBool2, &e.flag2) fmt.Printf("pi\t\tSize: %d\t\tOffset: %d\tAddr: %v\n", sizeFloat, offsetFloat, &e.pi) }
func main() { var s S println(unsafe.Offsetof(s.a)) println(unsafe.Offsetof(s.b)) println(unsafe.Offsetof(s.c)) println(unsafe.Offsetof(s.d)) }
func NewLinesRenderer(camera *Camera) (lr *LinesRenderer, err error) { var ( program uint32 vbos = make([]uint32, 2) point TexturedPoint ) if program, err = BuildProgram(LINES_VERTEX, LINES_FRAGMENT); err != nil { return } gl.GenBuffers(2, &vbos[0]) lr = &LinesRenderer{ Renderer: NewRenderer(camera), program: program, buffer: vbos[0], indexBuffer: vbos[1], bufferBytes: 0, positionLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Position\x00"))), normalLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Normal\x00"))), miterLoc: uint32(gl.GetAttribLocation(program, gl.Str("f_Miter\x00"))), modelviewLoc: gl.GetUniformLocation(program, gl.Str("m_ModelView\x00")), projectionLoc: gl.GetUniformLocation(program, gl.Str("m_Projection\x00")), thicknessLoc: gl.GetUniformLocation(program, gl.Str("f_Thickness\x00")), colorLoc: gl.GetUniformLocation(program, gl.Str("v_Color\x00")), innerLoc: gl.GetUniformLocation(program, gl.Str("f_Inner\x00")), offPosition: gl.PtrOffset(int(unsafe.Offsetof(point.X))), offNormal: gl.PtrOffset(int(unsafe.Offsetof(point.TextureX))), offMiter: gl.PtrOffset(int(unsafe.Offsetof(point.Z))), stride: int32(unsafe.Sizeof(point)), } if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func attrOutSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 9}): return unsafe.Offsetof(attrOut{}.Attr) + unsafe.Offsetof(attrOut{}.Attr.Blksize) default: return unsafe.Sizeof(attrOut{}) } }
func f() { defer int(0) // ERROR "defer requires function call, not conversion" go string([]byte("abc")) // ERROR "go requires function call, not conversion" var c complex128 var f float64 var t struct{ X int } var x []int defer append(x, 1) // ERROR "defer discards result of append" defer cap(x) // ERROR "defer discards result of cap" defer complex(1, 2) // ERROR "defer discards result of complex" defer complex(f, 1) // ERROR "defer discards result of complex" defer imag(1i) // ERROR "defer discards result of imag" defer imag(c) // ERROR "defer discards result of imag" defer len(x) // ERROR "defer discards result of len" defer make([]int, 1) // ERROR "defer discards result of make" defer make(chan bool) // ERROR "defer discards result of make" defer make(map[string]int) // ERROR "defer discards result of make" defer new(int) // ERROR "defer discards result of new" defer real(1i) // ERROR "defer discards result of real" defer real(c) // ERROR "defer discards result of real" defer append(x, 1) // ERROR "defer discards result of append" defer append(x, 1) // ERROR "defer discards result of append" defer unsafe.Alignof(t.X) // ERROR "defer discards result of unsafe.Alignof" defer unsafe.Offsetof(t.X) // ERROR "defer discards result of unsafe.Offsetof" defer unsafe.Sizeof(t) // ERROR "defer discards result of unsafe.Sizeof" defer copy(x, x) // ok m := make(map[int]int) defer delete(m, 1) // ok defer panic(1) // ok defer print(1) // ok defer println(1) // ok defer recover() // ok int(0) // ERROR "int\(0\) evaluated but not used" string([]byte("abc")) // ERROR "string\(.*\) evaluated but not used" append(x, 1) // ERROR "not used" cap(x) // ERROR "not used" complex(1, 2) // ERROR "not used" complex(f, 1) // ERROR "not used" imag(1i) // ERROR "not used" imag(c) // ERROR "not used" len(x) // ERROR "not used" make([]int, 1) // ERROR "not used" make(chan bool) // ERROR "not used" make(map[string]int) // ERROR "not used" new(int) // ERROR "not used" real(1i) // ERROR "not used" real(c) // ERROR "not used" append(x, 1) // ERROR "not used" append(x, 1) // ERROR "not used" unsafe.Alignof(t.X) // ERROR "not used" unsafe.Offsetof(t.X) // ERROR "not used" unsafe.Sizeof(t) // ERROR "not used" }
func Test_FieldsAligned(t *testing.T) { p1 := new(DB) testAligned(t, "DB.seq", unsafe.Offsetof(p1.seq)) p2 := new(session) testAligned(t, "session.stFileNum", unsafe.Offsetof(p2.stFileNum)) testAligned(t, "session.stJournalNum", unsafe.Offsetof(p2.stJournalNum)) testAligned(t, "session.stPrevJournalNum", unsafe.Offsetof(p2.stPrevJournalNum)) testAligned(t, "session.stSeq", unsafe.Offsetof(p2.stSeq)) }
func (b *TrackHeaderBoxVersion1) Dimensions(atomPosition int64) *Dimensions { return &Dimensions{ Width: b.Width, WidthPosition: atomPosition + int64(unsafe.Offsetof(TrackHeaderBoxVersion1{}.Width)), Height: b.Height, HeightPosition: int64(unsafe.Offsetof(TrackHeaderBoxVersion1{}.Height)) + atomPosition, SwapHeightAndWidth: calculateSwapHeightAndWidth(b.Matrix), } }
func main() { // Test unsafe.Sizeof, unsafe.Alignof, and unsafe.Offsetof all return uintptr. isUintptr(unsafe.Sizeof(t)) isUintptr(unsafe.Alignof(t)) isUintptr(unsafe.Offsetof(t.X)) // Test correctness of Offsetof with respect to embedded fields (issue 4909). if unsafe.Offsetof(t2.C) != 8 { println(unsafe.Offsetof(t2.C), "!= 8") panic("unsafe.Offsetof(t2.C) != 8") } if unsafe.Offsetof(p2.C) != 8 { println(unsafe.Offsetof(p2.C), "!= 8") panic("unsafe.Offsetof(p2.C) != 8") } if unsafe.Offsetof(t2.U2.C) != 4 { println(unsafe.Offsetof(t2.U2.C), "!= 4") panic("unsafe.Offsetof(t2.U2.C) != 4") } if unsafe.Offsetof(p2.U2.C) != 4 { println(unsafe.Offsetof(p2.U2.C), "!= 4") panic("unsafe.Offsetof(p2.U2.C) != 4") } testDeep() testNotEmbedded() }
func (r *Renderer) registerGeometry(geometry *Geometry) { var ( pt Point ptStride = unsafe.Sizeof(pt) ) geometry.Bind() geometry.Upload() r.shader.Attrib("v_Position", ptStride).Vec3(unsafe.Offsetof(pt.Position), 0) r.shader.Attrib("v_Texture", ptStride).Vec2(unsafe.Offsetof(pt.Texture), 0) r.shader.Attrib("f_VertexFrame", ptStride).Float(unsafe.Offsetof(pt.Frame), 0) }
func init() { var memStats MemStats if sizeof_C_MStats != unsafe.Sizeof(memStats) { println(sizeof_C_MStats, unsafe.Sizeof(memStats)) throw("MStats vs MemStatsType size mismatch") } if unsafe.Offsetof(memstats.heap_live)%8 != 0 { println(unsafe.Offsetof(memstats.heap_live)) throw("memstats.heap_live not aligned to 8 bytes") } }
func FormHeapTuple(values []system.Datum, tupdesc *TupleDesc) *HeapTuple { natts := len(tupdesc.Attrs) hasnull := false for _, value := range values { if value == nil { hasnull = true //} else if att.attlen == -1 // TODO: flatten toast value } } length := unsafe.Offsetof(HeapTupleHeader{}.bits) if hasnull { length += uintptr(bitmapLength(natts)) } if tupdesc.hasOid { length += unsafe.Sizeof(system.Oid(0)) } length = system.MaxAlign(length) hoff := uint8(length) data_len := computeHeapDataSize(values, tupdesc) length += data_len tuple_data := make([]byte, length) tuple := &HeapTuple{ tupdesc: tupdesc, tableOid: system.InvalidOid, } tuple.SetData(tuple_data, system.InvalidItemPointer) td := tuple.data td.SetNatts(system.AttrNumber(natts)) td.hoff = hoff if tupdesc.hasOid { td.infomask = heapHasOid } bits := []byte(nil) if hasnull { bits = tuple.bytes[unsafe.Offsetof(td.bits):hoff] } data := tuple.bytes[hoff:] td.fill(values, tupdesc, bits, data) return tuple }
func (any *anyMessage) parseInterfaceMessage(b []byte) *InterfaceMessage { p := (*InterfaceMessage)(unsafe.Pointer(any)) // FreeBSD 10 and beyond have a restructured mbuf // packet header view. // See http://svnweb.freebsd.org/base?view=revision&revision=254804. if freebsdVersion >= 1000000 { m := (*ifMsghdr)(unsafe.Pointer(any)) p.Header.Data.Hwassist = uint32(m.Data.Hwassist) p.Header.Data.Epoch = m.Data.Epoch p.Header.Data.Lastchange = m.Data.Lastchange return &InterfaceMessage{Header: p.Header, Data: b[int(unsafe.Offsetof(p.Header.Data))+int(p.Header.Data.Datalen) : any.Msglen]} } return &InterfaceMessage{Header: p.Header, Data: b[int(unsafe.Offsetof(p.Header.Data))+int(p.Header.Data.Datalen) : any.Msglen]} }
func TestSockFilter(t *testing.T) { var f SockFilter var cf sock_filter tests := []struct { desc string g, c uintptr }{ { "Sizeof(SockFilter)", unsafe.Sizeof(f), unsafe.Sizeof(cf), }, { "Sizeof(SockFilter.Code)", unsafe.Sizeof(f.Code), unsafe.Sizeof(cf.code), }, { "Offsetof(SockFilter.Code)", unsafe.Offsetof(f.Code), unsafe.Offsetof(cf.code), }, { "Sizeof(SockFilter.Jt)", unsafe.Sizeof(f.JT), unsafe.Sizeof(cf.jt), }, { "Offsetof(SockFilter.Jt)", unsafe.Offsetof(f.JT), unsafe.Offsetof(cf.jt), }, { "Sizeof(SockFilter.Jf)", unsafe.Sizeof(f.JF), unsafe.Sizeof(cf.jf), }, { "Offsetof(SockFilter.Jf)", unsafe.Offsetof(f.JF), unsafe.Offsetof(cf.jf), }, { "Sizeof(SockFilter.K)", unsafe.Sizeof(f.K), unsafe.Sizeof(cf.k), }, { "Offsetof(SockFilter.K)", unsafe.Offsetof(f.K), unsafe.Offsetof(cf.k), }, } for _, test := range tests { if test.g != test.c { t.Errorf("%s = %v; want %v", test.desc, test.g, test.c) } } }
func TestPointer(t *testing.T) { person := person{"a", 1} fmt.Printf("%v\n", person) pp := &person fmt.Printf("%p\n", pp) puptr := uintptr(unsafe.Pointer(pp)) fmt.Printf("%x\n", puptr) namePtr := puptr + unsafe.Offsetof(pp.Name) agePtr := puptr + unsafe.Offsetof(pp.Age) fmt.Printf("namePtr:%x,agePtr:%x\n", namePtr, agePtr) pp.Name = "ab" namePtr = puptr + unsafe.Offsetof(pp.Name) agePtr = puptr + unsafe.Offsetof(pp.Age) fmt.Printf("namePtr:%x,agePtr:%x\n", namePtr, agePtr) }
// main is the entry point for the application. func main() { // Declare variable of type example and init using // a struct literal. e := example{ flag: true, counter: 10, pi: 3.141592, } // Declare variable of type example and init using // a struct literal. eNext := example{ flag: true, counter: 10, pi: 3.141592, } // By placing both value one after the other on the stack // we can see the actual padding and where it is located. alignmentBoundary := unsafe.Alignof(e) sizeBool := unsafe.Sizeof(e.flag) offsetBool := unsafe.Offsetof(e.flag) sizeInt := unsafe.Sizeof(e.counter) offsetInt := unsafe.Offsetof(e.counter) sizeFloat := unsafe.Sizeof(e.pi) offsetFloat := unsafe.Offsetof(e.pi) sizeBoolNext := unsafe.Sizeof(eNext.flag) offsetBoolNext := unsafe.Offsetof(eNext.flag) fmt.Printf("Alignment Boundary: %d\n", alignmentBoundary) fmt.Printf("flag = Size: %d Offset: %d Addr: %v\n", sizeBool, offsetBool, &e.flag) fmt.Printf("counter = Size: %d Offset: %d Addr: %v\n", sizeInt, offsetInt, &e.counter) fmt.Printf("pi = Size: %d Offset: %d Addr: %v\n", sizeFloat, offsetFloat, &e.pi) fmt.Printf("Next = Size: %d Offset: %d Addr: %v\n", sizeBoolNext, offsetBoolNext, &eNext.flag) }
func (endianSupport) little(idx uint32) uint32 { if idx < 0 || idx >= 6 { return 0 } return uint32(unsafe.Offsetof(secData.args)) + uint32(unsafe.Alignof(secData.args[0]))*idx + uint32(unsafe.Sizeof(secData.arch)) }
func newLink(m *syscall.InterfaceMessage) ([]Interface, os.Error) { var ift []Interface sas, e := syscall.ParseRoutingSockaddr(m) if e != 0 { return nil, os.NewSyscallError("route sockaddr", e) } for _, s := range sas { switch v := s.(type) { case *syscall.SockaddrDatalink: // NOTE: SockaddrDatalink.Data is minimum work area, // can be larger. m.Data = m.Data[unsafe.Offsetof(v.Data):] ifi := Interface{Index: int(m.Header.Index), Flags: linkFlags(m.Header.Flags)} var name [syscall.IFNAMSIZ]byte for i := 0; i < int(v.Nlen); i++ { name[i] = byte(m.Data[i]) } ifi.Name = string(name[:v.Nlen]) ifi.MTU = int(m.Header.Data.Mtu) addr := make([]byte, v.Alen) for i := 0; i < int(v.Alen); i++ { addr[i] = byte(m.Data[int(v.Nlen)+i]) } ifi.HardwareAddr = addr[:v.Alen] ift = append(ift, ifi) } } return ift, nil }
func direntNamlen(buf []byte) (uint64, bool) { reclen, ok := direntReclen(buf) if !ok { return 0, false } return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true }
func newLink(m *syscall.InterfaceMessage) (*Interface, error) { sas, err := syscall.ParseRoutingSockaddr(m) if err != nil { return nil, os.NewSyscallError("route sockaddr", err) } ifi := &Interface{Index: int(m.Header.Index), Flags: linkFlags(m.Header.Flags)} for _, sa := range sas { switch sa := sa.(type) { case *syscall.SockaddrDatalink: // NOTE: SockaddrDatalink.Data is minimum work area, // can be larger. m.Data = m.Data[unsafe.Offsetof(sa.Data):] var name [syscall.IFNAMSIZ]byte for i := 0; i < int(sa.Nlen); i++ { name[i] = byte(m.Data[i]) } ifi.Name = string(name[:sa.Nlen]) ifi.MTU = int(m.Header.Data.Mtu) addr := make([]byte, sa.Alen) for i := 0; i < int(sa.Alen); i++ { addr[i] = byte(m.Data[int(sa.Nlen)+i]) } ifi.HardwareAddr = addr[:sa.Alen] } } return ifi, nil }
func (ct *commonType) ptrTo() *commonType { if p := ct.ptrToThis; p != nil { return toCommonType(p) } // Otherwise, synthesize one. // This only happens for pointers with no methods. // We keep the mapping in a map on the side, because // this operation is rare and a separate map lets us keep // the type structures in read-only memory. ptrMap.RLock() if m := ptrMap.m; m != nil { if p := m[ct]; p != nil { ptrMap.RUnlock() return &p.commonType } } ptrMap.RUnlock() ptrMap.Lock() if ptrMap.m == nil { ptrMap.m = make(map[*commonType]*ptrType) } p := ptrMap.m[ct] if p != nil { // some other goroutine won the race and created it ptrMap.Unlock() return &p.commonType } var rt struct { i runtime.Type ptrType } rt.i = (*runtime.PtrType)(unsafe.Pointer(&rt.ptrType)) // initialize p using *byte's ptrType as a prototype. // have to do assignment as ptrType, not runtime.PtrType, // in order to write to unexported fields. p = &rt.ptrType bp := (*ptrType)(unsafe.Pointer(unsafe.Typeof((*byte)(nil)).(*runtime.PtrType))) *p = *bp s := "*" + *ct.string p.string = &s // For the type structures linked into the binary, the // compiler provides a good hash of the string. // Create a good hash for the new string by using // the FNV-1 hash's mixing function to combine the // old hash and the new "*". p.hash = ct.hash*16777619 ^ '*' p.uncommonType = nil p.ptrToThis = nil p.elem = (*runtime.Type)(unsafe.Pointer(uintptr(unsafe.Pointer(ct)) - unsafe.Offsetof(rt.ptrType))) ptrMap.m[ct] = p ptrMap.Unlock() return &p.commonType }
func mkdirInSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 12}): return unsafe.Offsetof(mkdirIn{}.Umask) + 4 default: return unsafe.Sizeof(mkdirIn{}) } }
func createInSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 12}): return unsafe.Offsetof(createIn{}.Umask) default: return unsafe.Sizeof(createIn{}) } }
func readInSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 9}): return unsafe.Offsetof(readIn{}.ReadFlags) + 4 default: return unsafe.Sizeof(readIn{}) } }
func lkInSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 9}): return unsafe.Offsetof(lkIn{}.LkFlags) default: return unsafe.Sizeof(lkIn{}) } }
func writeInSize(p Protocol) uintptr { switch { case p.LT(Protocol{7, 9}): return unsafe.Offsetof(writeIn{}.LockOwner) default: return unsafe.Sizeof(writeIn{}) } }