github.com/primecitizens/pcz/std@v0.2.1/builtin/type/type.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  //
     4  // Copyright 2009 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  package stdtype
     9  
    10  import (
    11  	"unsafe"
    12  
    13  	"github.com/primecitizens/pcz/std/core/abi"
    14  	"github.com/primecitizens/pcz/std/core/mark"
    15  )
    16  
    17  // Eface is the definition for interfaces with no method.
    18  //
    19  //   - interface{}
    20  //   - any
    21  //   - type Foo interface{}
    22  type Eface struct {
    23  	Type *abi.Type
    24  	Data unsafe.Pointer
    25  }
    26  
    27  func Type[T any]() *abi.Type {
    28  	var x any = (*T)(nil)
    29  	return mark.NoEscape(
    30  		EfaceOf(mark.NoEscape(&x)).Type.PointerTypeUnsafe().Elem,
    31  	)
    32  }
    33  
    34  // TypeOf returns the runtime type of x.
    35  func TypeOf(x any) *abi.Type {
    36  	return mark.NoEscape(EfaceOf(mark.NoEscape(&x)).Type)
    37  }
    38  
    39  // ValueOf returns the data in x.
    40  func ValueOf(x any) unsafe.Pointer {
    41  	return EfaceOf(mark.NoEscape(&x)).Data
    42  }
    43  
    44  // EfaceOf returns the underlay Eface data of *ep.
    45  func EfaceOf(ep *any) *Eface {
    46  	return (*Eface)(mark.NoEscapePointer(ep))
    47  }
    48  
    49  func FromEface(ep *Eface) any {
    50  	return *(*any)(mark.NoEscapePointer(ep))
    51  }
    52  
    53  func FormatEface(typ *abi.Type, data unsafe.Pointer) any {
    54  	eface := Eface{
    55  		Type: typ,
    56  		Data: data,
    57  	}
    58  
    59  	return FromEface((*Eface)(mark.NoEscapePointer(&eface)))
    60  }
    61  
    62  // Iface is the definition for interfaces with at least one method.
    63  type Iface struct {
    64  	Itab *abi.Itab
    65  	Data unsafe.Pointer
    66  }
    67  
    68  // IfaceOf returns the underlay Iface data of T.
    69  //
    70  // NOTE: T MUST be an interface type with at least one method.
    71  func IfaceOf[T any](ip *T) *Iface {
    72  	return (*Iface)(mark.NoEscapePointer(ip))
    73  }
    74  
    75  // NOTE: T MUST be an interface type with at least one method.
    76  func FromIface[T any](ip *Iface) T {
    77  	return *(*T)(mark.NoEscapePointer(ip))
    78  }
    79  
    80  // NOTE: T MUST be an interface type with at least one method.
    81  func FormatIface[T any](itab *abi.Itab, data unsafe.Pointer) T {
    82  	iface := Iface{
    83  		Itab: itab,
    84  		Data: data,
    85  	}
    86  
    87  	return FromIface[T]((*Iface)(mark.NoEscapePointer(&iface)))
    88  }