func convertValueToString(field reflect.Value) (string, bool) { switch field.Kind() { case reflect.Float64: if field.Float() != 0.0 { return fmt.Sprintf("%f", field.Float()), true } case reflect.Bool: return fmt.Sprintf("%t", field.Bool()), true case reflect.Int: if field.Int() != 0 { return fmt.Sprintf("%d", field.Int()), true } case reflect.String: if field.String() != "" { return fmt.Sprintf("%s", field.String()), true } case reflect.Ptr: if field.Pointer() != 0 { field := field.Elem() if field.Kind() == reflect.Int { return fmt.Sprintf("%d", field.Int()), true } else if field.Kind() == reflect.Bool { return fmt.Sprintf("%t", field.Int()), true } } } return "", false }
// validateNewFacade ensures that the facade factory we have has the right // input and output parameters for being used as a NewFoo function. func validateNewFacade(funcValue reflect.Value) error { if !funcValue.IsValid() { return fmt.Errorf("cannot wrap nil") } if funcValue.Kind() != reflect.Func { return fmt.Errorf("wrong type %q is not a function", funcValue.Kind()) } funcType := funcValue.Type() funcName := runtime.FuncForPC(funcValue.Pointer()).Name() if funcType.NumIn() != 3 || funcType.NumOut() != 2 { return fmt.Errorf("function %q does not take 3 parameters and return 2", funcName) } facadeType := reflect.TypeOf((*FacadeFactory)(nil)).Elem() isSame := true for i := 0; i < 3; i++ { if funcType.In(i) != facadeType.In(i) { isSame = false break } } if funcType.Out(1) != facadeType.Out(1) { isSame = false } if !isSame { return fmt.Errorf("function %q does not have the signature func (*state.State, *common.Resources, common.Authorizer) (*Type, error)", funcName) } return nil }
func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) { switch verb { case 'p', 'v', 'b', 'd', 'o', 'x', 'X': // ok default: p.badVerb(verb) return } var u uintptr switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: u = value.Pointer() default: p.badVerb(verb) return } if goSyntax { p.add('(') p.buf.WriteString(value.Type().String()) p.add(')') p.add('(') if u == 0 { p.buf.Write(nilBytes) } else { p.fmt0x64(uint64(u), true) } p.add(')') } else if verb == 'v' && u == 0 { p.buf.Write(nilAngleBytes) } else { p.fmt0x64(uint64(u), !p.fmt.sharp) } }
func fname(v reflect.Value) (name string) { name = runtime.FuncForPC(v.Pointer()).Name() if i := strings.LastIndex(name, "."); i != -1 { name = name[i+1:] } return name }
/* Returns `true` if the given reflect.Value is a struct method. */ func isMethod(v reflect.Value) bool { /* Based on a hack by Steven Blenkinsop. http://play.golang.org/p/GD_ZoSpnRe */ t := v.Type() if v.Kind() != reflect.Func { // Not a function. return false } if t.NumIn() == 0 { // Methods have at least one parameter. return false } fullname := runtime.FuncForPC(v.Pointer()).Name() funcname := fullname[strings.LastIndex(fullname, ".")+1:] // 0 arg is the struct pointer, if it's a method. method, ok := t.In(0).MethodByName(funcname) if ok == false { // No such method with that name. return false } return v.Pointer() == method.Func.Pointer() }
// formatAtom formats a value without inspecting its internal structure. // It is a copy of the the function in gopl.io/ch11/format. func formatAtom(v reflect.Value) string { switch v.Kind() { case reflect.Invalid: return "invalid" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(v.Int(), 10) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return strconv.FormatUint(v.Uint(), 10) // ...floating-point and complex cases omitted for brevity... case reflect.Bool: if v.Bool() { return "true" } return "false" case reflect.String: return strconv.Quote(v.String()) case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map: return v.Type().String() + " 0x" + strconv.FormatUint(uint64(v.Pointer()), 16) default: // reflect.Array, reflect.Struct, reflect.Interface return v.Type().String() + " value" } }
func formatValue(value reflect.Value, indentation uint) string { if indentation > MaxDepth { return "..." } if isNilValue(value) { return "nil" } if UseStringerRepresentation { if value.CanInterface() { obj := value.Interface() switch x := obj.(type) { case fmt.GoStringer: return x.GoString() case fmt.Stringer: return x.String() } } } switch value.Kind() { case reflect.Bool: return fmt.Sprintf("%v", value.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return fmt.Sprintf("%v", value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return fmt.Sprintf("%v", value.Uint()) case reflect.Uintptr: return fmt.Sprintf("0x%x", value.Uint()) case reflect.Float32, reflect.Float64: return fmt.Sprintf("%v", value.Float()) case reflect.Complex64, reflect.Complex128: return fmt.Sprintf("%v", value.Complex()) case reflect.Chan: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Func: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Ptr: return formatValue(value.Elem(), indentation) case reflect.Slice: return formatSlice(value, indentation) case reflect.String: return formatString(value.String(), indentation) case reflect.Array: return formatSlice(value, indentation) case reflect.Map: return formatMap(value, indentation) case reflect.Struct: return formatStruct(value, indentation) case reflect.Interface: return formatValue(value.Elem(), indentation) default: if value.CanInterface() { return fmt.Sprintf("%#v", value.Interface()) } else { return fmt.Sprintf("%#v", value) } } }
func (s *Shader) assign(ptr unsafe.Pointer, val reflect.Value, typ reflect.Type, name string) error { u := s.prog.GetUniformLocation(name) if u < 0 { return fmt.Errorf("gfx: unknown uniform variable '%s'", name) } if typ.Kind() == reflect.Ptr { if s.assignPrimitive(unsafe.Pointer(val.Pointer()), typ.Elem(), u) { return nil } } else if s.assignPrimitive(ptr, typ, u) { return nil } iface := val.Interface() switch iface.(type) { // special types case *Sampler2D: sampler := iface.(*Sampler2D) texunit := s.texunit(u) gl.ActiveTexture(gl.TEXTURE0 + gl.GLenum(texunit)) sampler.bind() u.Uniform1i(texunit) default: return fmt.Errorf("gfx: invalid uniform type %v", typ) } return nil }
func nonzero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() != 0 case reflect.Float32, reflect.Float64: return v.Float() != 0 case reflect.Complex64, reflect.Complex128: return v.Complex() != complex(0, 0) case reflect.String: return v.String() != "" case reflect.Struct: for i := 0; i < v.NumField(); i++ { if nonzero(getField(v, i)) { return true } } return false case reflect.Array: for i := 0; i < v.Len(); i++ { if nonzero(v.Index(i)) { return true } } return false case reflect.Map, reflect.Interface, reflect.Slice, reflect.Ptr, reflect.Chan, reflect.Func: return !v.IsNil() case reflect.UnsafePointer: return v.Pointer() != 0 } return true }
func (lua *Lua) PushGoValue(value reflect.Value) { switch t := value.Type(); t.Kind() { case reflect.Bool: if value.Bool() { C.lua_pushboolean(lua.State, C.int(1)) } else { C.lua_pushboolean(lua.State, C.int(0)) } case reflect.String: C.lua_pushstring(lua.State, C.CString(value.String())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: C.lua_pushnumber(lua.State, C.lua_Number(C.longlong(value.Int()))) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: C.lua_pushnumber(lua.State, C.lua_Number(C.ulonglong(value.Uint()))) case reflect.Float32, reflect.Float64: C.lua_pushnumber(lua.State, C.lua_Number(C.double(value.Float()))) case reflect.Slice: length := value.Len() C.lua_createtable(lua.State, C.int(length), 0) for i := 0; i < length; i++ { C.lua_pushnumber(lua.State, C.lua_Number(i+1)) lua.PushGoValue(value.Index(i)) C.lua_settable(lua.State, -3) } case reflect.Interface: lua.PushGoValue(value.Elem()) case reflect.Ptr, reflect.UnsafePointer: C.lua_pushlightuserdata(lua.State, unsafe.Pointer(value.Pointer())) default: lua.Panic("wrong return value %v %v", value, t.Kind()) } }
// GetFuncValueSourceAsString returns the source of the func value fv. func GetFuncValueSourceAsString(fv reflect.Value) string { // Checking the kind catches cases where f was nil, resulting in fv being a zero Value (i.e. invalid kind), // as well as when fv is non-func. if fv.Kind() != reflect.Func { return "kind not func" } pc := fv.Pointer() if pc == 0 { return "nil" } function := runtime.FuncForPC(pc) if function == nil { return "nil" } file, line := function.FileLine(pc) var startIndex, endIndex int { b, err := ioutil.ReadFile(file) if err != nil { return "<file not found>" } startIndex, endIndex = getLineStartEndIndicies(b, line-1) } fs := token.NewFileSet() fileAst, err := parser.ParseFile(fs, file, nil, 0*parser.ParseComments) if err != nil { return "<ParseFile failed>" } // TODO: Consider using ast.Walk() instead of custom FindFirst() query := func(i interface{}) bool { // TODO: Factor-out the unusual overlap check if f, ok := i.(*ast.FuncLit); ok && ((startIndex <= int(f.Pos())-1 && int(f.Pos())-1 <= endIndex) || (int(f.Pos())-1 <= startIndex && startIndex <= int(f.End())-1)) { return true } return false } funcAst := reflectfind.First(fileAst, query) // If func literal wasn't found, try again looking for func declaration if funcAst == nil { query := func(i interface{}) bool { // TODO: Factor-out the unusual overlap check if f, ok := i.(*ast.FuncDecl); ok && ((startIndex <= int(f.Pos())-1 && int(f.Pos())-1 <= endIndex) || (int(f.Pos())-1 <= startIndex && startIndex <= int(f.End())-1)) { return true } return false } funcAst = reflectfind.First(fileAst, query) } if funcAst == nil { return fmt.Sprintf("<func src not found at %v:%v>", file, line) } return printerutil.SprintAst(fs, funcAst) }
func funcName(val reflect.Value) string { ptr := val.Pointer() fn := runtime.FuncForPC(ptr) if fn == nil { return fmt.Sprintf("unknown function at %p", ptr) } return fn.Name() }
// valueToXpc converts a go Value to an xpc object // // note that not all the types are supported, but only the subset required for Blued func valueToXpc(val r.Value) C.xpc_object_t { if !val.IsValid() { return nil } var xv C.xpc_object_t switch val.Kind() { case r.Int, r.Int8, r.Int16, r.Int32, r.Int64: xv = C.xpc_int64_create(C.int64_t(val.Int())) case r.Uint, r.Uint8, r.Uint16, r.Uint32: xv = C.xpc_int64_create(C.int64_t(val.Uint())) case r.String: xv = C.xpc_string_create(C.CString(val.String())) case r.Map: xv = C.xpc_dictionary_create(nil, nil, 0) for _, k := range val.MapKeys() { v := valueToXpc(val.MapIndex(k)) C.xpc_dictionary_set_value(xv, C.CString(k.String()), v) if v != nil { C.xpc_release(v) } } case r.Array, r.Slice: if val.Type() == TYPE_OF_UUID { // array of bytes var uuid [16]byte r.Copy(r.ValueOf(uuid[:]), val) xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0]))) } else if val.Type() == TYPE_OF_BYTES { // slice of bytes xv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len())) } else { xv = C.xpc_array_create(nil, 0) l := val.Len() for i := 0; i < l; i++ { v := valueToXpc(val.Index(i)) C.xpc_array_append_value(xv, v) if v != nil { C.xpc_release(v) } } } case r.Interface, r.Ptr: xv = valueToXpc(val.Elem()) default: log.Fatalf("unsupported %#v", val.String()) } return xv }
func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method { for i := 0; i < recvType.NumMethod(); i++ { method := recvType.Method(i) if method.Func.Pointer() == funcVal.Pointer() { return &method } } return nil }
// Mark value on top of the stack as visited using the registry index. func (v *visitor) mark(val reflect.Value) { ptr := val.Pointer() v.L.RawGeti(lua.LUA_REGISTRYINDEX, v.index) // Copy value on top. v.L.PushValue(-2) // Set value to table. v.L.RawSeti(-2, int(ptr)) v.L.Pop(1) }
// Increments SendChanRefCount func (n *Graph) IncSendChanRefCount(c reflect.Value) { n.sendChanMutex.Lock() defer n.sendChanMutex.Unlock() ptr := c.Pointer() cnt := n.sendChanRefCount[ptr] cnt += 1 n.sendChanRefCount[ptr] = cnt }
func (e *Encoder) encodePointer(by []byte, rv reflect.Value, strTable map[string]int, ptrTable map[uintptr]int) ([]byte, error) { // ikruglov // I don't fully understand this logic, so leave it as is :-) if rv.Elem().Kind() == reflect.Struct { switch rv.Elem().Interface().(type) { case PerlRegexp: return e.encode(by, rv.Elem(), false, false, strTable, ptrTable) case PerlUndef: return e.encode(by, rv.Elem(), false, false, strTable, ptrTable) case PerlObject: return e.encode(by, rv.Elem(), false, false, strTable, ptrTable) case PerlWeakRef: return e.encode(by, rv.Elem(), false, false, strTable, ptrTable) } } rvptr := rv.Pointer() rvptr2 := getPointer(rv.Elem()) offs, ok := ptrTable[rvptr] if !ok && rvptr2 != 0 { offs, ok = ptrTable[rvptr2] if ok { rvptr = rvptr2 } } if ok { // seen this before by = append(by, typeREFP) by = varint(by, uint(offs)) by[offs] |= trackFlag // original offset now tracked } else { lenbOrig := len(by) by = append(by, typeREFN) if rvptr != 0 { ptrTable[rvptr] = lenbOrig } var err error by, err = e.encode(by, rv.Elem(), false, true, strTable, ptrTable) if err != nil { return nil, err } if rvptr2 != 0 { // The thing this this points to starts one after the current pointer ptrTable[rvptr2] = lenbOrig + 1 } } return by, nil }
func (encoder *Encoder) encodeStruct(value reflect.Value) error { err := encoder.writeMarker(OBJECT_MARKER) if err != nil { return err } index, ok := encoder.objectCache[value.Pointer()] if ok { index <<= 1 encoder.writeU29(uint32(index << 1)) return nil } err = encoder.writeMarker(0x0b) if err != nil { return err } err = encoder.writeString("") if err != nil { return err } v := reflect.Indirect(value) t := v.Type() switch t.Kind() { case reflect.Struct: for i := 0; i < t.NumField(); i++ { f := t.Field(i) key := encoder.getFieldName(f) if key == "" { continue } err = encoder.writeString(key) if err != nil { return err } fv := v.FieldByName(f.Name) if fv.Kind() == reflect.Struct { fv = fv.Addr() } err = encoder.encode(fv) if err != nil { return err } } default: panic("not a struct") } return encoder.writeString("") }
func funcDebugName(name string, fn reflect.Value) string { if fn.IsValid() && fn.Kind() == reflect.Func { if rf := runtime.FuncForPC(fn.Pointer()); rf != nil { file, line := rf.FileLine(fn.Pointer()) return fmt.Sprintf("%s (%s @ %s:%d)", name, rf.Name(), file, line) } } return name }
// Decrements SendChanRefCount // It returns true if the RefCount has reached 0 func (n *Graph) DecSendChanRefCount(c reflect.Value) bool { ptr := c.Pointer() cnt := n.sendChanRefCount[ptr] if cnt == 0 { return true //yes you may try to close a nonexistant channel, see what happens... } cnt -= 1 n.sendChanRefCount[ptr] = cnt return cnt == 0 }
func compare_value(a, b reflect.Value) bool { if a.Type() != b.Type() { return false } m := a.MethodByName("Equal") if m.IsValid() { res := m.Call([]reflect.Value{b}) return res[0].Bool() } switch a.Kind() { case reflect.Bool: return a.Bool() == b.Bool() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return a.Uint() == b.Uint() case reflect.Array: for i := 0; i < a.Len(); i++ { if !compare_value(a.Index(i), b.Index(i)) { return false } } return true case reflect.Slice: if a.IsNil() != b.IsNil() { return false } if a.Len() != b.Len() { return false } if a.Pointer() == b.Pointer() { return true } for i := 0; i < a.Len(); i++ { if !compare_value(a.Index(i), b.Index(i)) { return false } } return true case reflect.Interface: return true default: return false } }
func snapvalue(w io.Writer, v reflect.Value) { var q string switch v.Kind() { case reflect.Bool: // Not addressable q = strconv.FormatBool(v.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: q = strconv.FormatInt(v.Int(), 36) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: q = strconv.FormatUint(v.Uint(), 36) case reflect.Uintptr: panic("n/s") case reflect.Float32, reflect.Float64: q = strconv.FormatFloat(v.Float(), 'g', 65, 64) case reflect.Complex64, reflect.Complex128: c := v.Complex() q = "(" + strconv.FormatFloat(real(c), 'g', 65, 64) + ", " + strconv.FormatFloat(imag(c), 'g', 65, 64) + "i)" case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: // Addressable q = strconv.FormatUint(uint64(v.Pointer()), 36) // uintptr case reflect.Interface: d := v.InterfaceData() // [2]uintptr q = "<" + strconv.FormatUint(uint64(d[0]), 36) + "," + strconv.FormatUint(uint64(d[1]), 36) + ">" case reflect.String: q = v.String() case reflect.Array: w.Write([]byte("{")) for i := 0; i < v.Len(); i++ { snapvalue(w, v.Index(i)) w.Write([]byte(",")) } w.Write([]byte("}")) return case reflect.Struct: w.Write([]byte("{")) for i := 0; i < v.NumField(); i++ { snapvalue(w, v.FieldByIndex([]int{i})) w.Write([]byte(",")) } w.Write([]byte("}")) default: panic("u") } w.Write([]byte(q)) }
//function type, get the function name func encodePlainFunc(v reflect.Value) (str string) { var buf bytes.Buffer if v.Kind() != reflect.Func { return buf.String() } buf.WriteString(createRow(runtime.FuncForPC(v.Pointer()).Name())) return buf.String() }
// Return the reflect.Method, given a Receiver type and Func value. func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method { // It is not possible to get the name of the method from the Func. // Instead, compare it to each method of the Controller. for i := 0; i < recvType.NumMethod(); i++ { method := recvType.Method(i) if method.Func.Pointer() == funcVal.Pointer() { return &method } } return nil }
// Push visited value on top of the stack. // If the value was not visited, return false. func (v *visitor) push(val reflect.Value) bool { ptr := val.Pointer() v.L.RawGeti(lua.LUA_REGISTRYINDEX, v.index) v.L.RawGeti(-1, int(ptr)) if v.L.IsNil(-1) { // Not visited. v.L.Pop(2) return false } v.L.Replace(-2) return true }
func putPointer(value reflect.Value) { elem := value.Elem().Type() p, ok := ptrMap[elem.String()] if !ok { lock.Lock() p = new(sync.Pool) ptrMap[elem.String()] = p lock.Unlock() } ClearData(elem.Size(), unsafe.Pointer(value.Pointer())) p.Put(value) }
func convertToBytes(intSize int, v reflect.Value) []byte { if !v.IsValid() { return nil } nbytes := intSize / 8 sh := &reflect.SliceHeader{} sh.Cap = v.Cap() * nbytes sh.Len = v.Len() * nbytes sh.Data = v.Pointer() return *(*[]uint8)(unsafe.Pointer(sh)) }
func checkAgainstUnsafePointer(e reflect.Value, c reflect.Value) (err error) { // Make sure c is a pointer. if c.Kind() != reflect.UnsafePointer { err = NewFatalError("which is not a unsafe.Pointer") return } err = errors.New("") if c.Pointer() == e.Pointer() { err = nil } return }
func checkAgainstMap(e reflect.Value, c reflect.Value) (err error) { // Make sure c is a map. if c.Kind() != reflect.Map { err = NewFatalError("which is not a map") return } err = errors.New("") if c.Pointer() == e.Pointer() { err = nil } return }
func checkAgainstFunc(e reflect.Value, c reflect.Value) (err error) { // Make sure c is a function. if c.Kind() != reflect.Func { err = NewFatalError("which is not a function") return } err = errors.New("") if c.Pointer() == e.Pointer() { err = nil } return }