github.com/eh-steve/goloader@v0.0.0-20240111193454-90ff3cfdae39/reflectlite/reflectlite1.18/value.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package reflectlite 6 7 import ( 8 "errors" 9 "github.com/eh-steve/goloader/reflectlite/internal/goarch" 10 "github.com/eh-steve/goloader/reflectlite/internal/itoa" 11 "github.com/eh-steve/goloader/reflectlite/internal/unsafeheader" 12 "math" 13 "runtime" 14 "unsafe" 15 ) 16 17 // Value is the reflection interface to a Go value. 18 // 19 // Not all methods apply to all kinds of values. Restrictions, 20 // if interface{}, are noted in the documentation for each method. 21 // Use the Kind method to find out the kind of value before 22 // calling kind-specific methods. Calling a method 23 // inappropriate to the kind of type causes a run time panic. 24 // 25 // The zero Value represents no value. 26 // Its IsValid method returns false, its Kind method returns Invalid, 27 // its String method returns "<invalid Value>", and all other methods panic. 28 // Most functions and methods never return an invalid value. 29 // If one does, its documentation states the conditions explicitly. 30 // 31 // A Value can be used concurrently by multiple goroutines provided that 32 // the underlying Go value can be used concurrently for the equivalent 33 // direct operations. 34 // 35 // To compare two Values, compare the results of the Interface method. 36 // Using == on two Values does not compare the underlying values 37 // they represent. 38 type Value struct { 39 // typ holds the type of the value represented by a Value. 40 typ *rtype 41 42 // Pointer-valued data or, if flagIndir is set, pointer to data. 43 // Valid when either flagIndir is set or typ.pointers() is true. 44 ptr unsafe.Pointer 45 46 // flag holds metadata about the value. 47 // The lowest bits are flag bits: 48 // - flagStickyRO: obtained via unexported not embedded field, so read-only 49 // - flagEmbedRO: obtained via unexported embedded field, so read-only 50 // - flagIndir: val holds a pointer to the data 51 // - flagAddr: v.CanAddr is true (implies flagIndir) 52 // - flagMethod: v is a method value. 53 // The next five bits give the Kind of the value. 54 // This repeats typ.Kind() except for method values. 55 // The remaining 23+ bits give a method number for method values. 56 // If flag.kind() != Func, code can assume that flagMethod is unset. 57 // If ifaceIndir(typ), code can assume that flagIndir is set. 58 flag 59 60 // A method value represents a curried method invocation 61 // like r.Read for some receiver r. The typ+val+flag bits describe 62 // the receiver r, but the flag's Kind bits say Func (methods are 63 // functions), and the top bits of the flag give the method number 64 // in r's type's method table. 65 } 66 67 type flag uintptr 68 69 const ( 70 flagKindWidth = 5 // there are 27 kinds 71 flagKindMask flag = 1<<flagKindWidth - 1 72 flagStickyRO flag = 1 << 5 73 flagEmbedRO flag = 1 << 6 74 flagIndir flag = 1 << 7 75 flagAddr flag = 1 << 8 76 flagMethod flag = 1 << 9 77 flagMethodShift = 10 78 flagRO flag = flagStickyRO | flagEmbedRO 79 ) 80 81 func (f flag) kind() Kind { 82 return Kind(f & flagKindMask) 83 } 84 85 func (f flag) ro() flag { 86 if f&flagRO != 0 { 87 return flagStickyRO 88 } 89 return 0 90 } 91 92 // pointer returns the underlying pointer represented by v. 93 // v.Kind() must be Pointer, Map, Chan, Func, or UnsafePointer 94 // if v.Kind() == Pointer, the base type must not be go:notinheap. 95 func (v Value) pointer() unsafe.Pointer { 96 if v.typ.size != goarch.PtrSize || !v.typ.pointers() { 97 panic("can't call pointer on a non-pointer Value") 98 } 99 if v.flag&flagIndir != 0 { 100 return *(*unsafe.Pointer)(v.ptr) 101 } 102 return v.ptr 103 } 104 105 // packEface converts v to the empty interface. 106 func packEface(v Value) interface{} { 107 t := v.typ 108 var i interface{} 109 e := (*emptyInterface)(unsafe.Pointer(&i)) 110 // First, fill in the data portion of the interface. 111 switch { 112 case ifaceIndir(t): 113 if v.flag&flagIndir == 0 { 114 panic("bad indir") 115 } 116 // Value is indirect, and so is the interface we're making. 117 ptr := v.ptr 118 if v.flag&flagAddr != 0 { 119 // TODO: pass safe boolean from valueInterface so 120 // we don't need to copy if safe==true? 121 c := unsafe_New(t) 122 typedmemmove(t, c, ptr) 123 ptr = c 124 } 125 e.word = ptr 126 case v.flag&flagIndir != 0: 127 // Value is indirect, but interface is direct. We need 128 // to load the data at v.ptr into the interface data word. 129 e.word = *(*unsafe.Pointer)(v.ptr) 130 default: 131 // Value is direct, and so is the interface. 132 e.word = v.ptr 133 } 134 // Now, fill in the type portion. We're very careful here not 135 // to have interface{} operation between the e.word and e.typ assignments 136 // that would let the garbage collector observe the partially-built 137 // interface value. 138 e.typ = t 139 return i 140 } 141 142 // unpackEface converts the empty interface i to a Value. 143 func unpackEface(i interface{}) Value { 144 e := (*emptyInterface)(unsafe.Pointer(&i)) 145 // NOTE: don't read e.word until we know whether it is really a pointer or not. 146 t := e.typ 147 if t == nil { 148 return Value{} 149 } 150 f := flag(t.Kind()) 151 if ifaceIndir(t) { 152 f |= flagIndir 153 } 154 return Value{t, e.word, f} 155 } 156 157 // A ValueError occurs when a Value method is invoked on 158 // a Value that does not support it. Such cases are documented 159 // in the description of each method. 160 type ValueError struct { 161 Method string 162 Kind Kind 163 } 164 165 func (e *ValueError) Error() string { 166 if e.Kind == 0 { 167 return "reflect: call of " + e.Method + " on zero Value" 168 } 169 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value" 170 } 171 172 // methodName returns the name of the calling method, 173 // assumed to be two stack frames above. 174 func methodName() string { 175 pc, _, _, _ := runtime.Caller(2) 176 f := runtime.FuncForPC(pc) 177 if f == nil { 178 return "unknown method" 179 } 180 return f.Name() 181 } 182 183 // methodNameSkip is like methodName, but skips another stack frame. 184 // This is a separate function so that reflect.flag.mustBe will be inlined. 185 func methodNameSkip() string { 186 pc, _, _, _ := runtime.Caller(3) 187 f := runtime.FuncForPC(pc) 188 if f == nil { 189 return "unknown method" 190 } 191 return f.Name() 192 } 193 194 // emptyInterface is the header for an interface{} value. 195 type emptyInterface struct { 196 typ *rtype 197 word unsafe.Pointer 198 } 199 200 // mustBe panics if f's kind is not expected. 201 // Making this a method on flag instead of on Value 202 // (and embedding flag in Value) means that we can write 203 // the very clear v.mustBe(Bool) and have it compile into 204 // v.flag.mustBe(Bool), which will only bother to copy the 205 // single important word for the receiver. 206 func (f flag) mustBe(expected Kind) { 207 // TODO(mvdan): use f.kind() again once mid-stack inlining gets better 208 if Kind(f&flagKindMask) != expected { 209 panic(&ValueError{methodName(), f.kind()}) 210 } 211 } 212 213 // mustBeAssignable panics if f records that the value is not assignable, 214 // which is to say that either it was obtained using an unexported field 215 // or it is not addressable. 216 func (f flag) mustBeAssignable() { 217 if f&flagRO != 0 || f&flagAddr == 0 { 218 f.mustBeAssignableSlow() 219 } 220 } 221 222 func (f flag) mustBeAssignableSlow() { 223 if f == 0 { 224 panic(&ValueError{methodNameSkip(), Invalid}) 225 } 226 // Assignable if addressable. 227 if f&flagAddr == 0 { 228 panic("reflect: " + methodNameSkip() + " using unaddressable value") 229 } 230 } 231 232 // Addr returns a pointer value representing the address of v. 233 // It panics if CanAddr() returns false. 234 // Addr is typically used to obtain a pointer to a struct field 235 // or slice element in order to call a method that requires a 236 // pointer receiver. 237 func (v Value) Addr() Value { 238 if v.flag&flagAddr == 0 { 239 panic("reflect.Value.Addr of unaddressable value") 240 } 241 // Preserve flagRO instead of using v.flag.ro() so that 242 // v.Addr().Elem() is equivalent to v (#32772) 243 fl := v.flag & flagRO 244 return Value{v.typ.ptrTo(), v.ptr, fl | flag(Pointer)} 245 } 246 247 // Bool returns v's underlying value. 248 // It panics if v's kind is not Bool. 249 func (v Value) Bool() bool { 250 v.mustBe(Bool) 251 return *(*bool)(v.ptr) 252 } 253 254 // Bytes returns v's underlying value. 255 // It panics if v's underlying value is not a slice of bytes. 256 func (v Value) Bytes() []byte { 257 v.mustBe(Slice) 258 if v.typ.Elem().Kind() != Uint8 { 259 panic("reflect.Value.Bytes of non-byte slice") 260 } 261 // Slice is always bigger than a word; assume flagIndir. 262 return *(*[]byte)(v.ptr) 263 } 264 265 // runes returns v's underlying value. 266 // It panics if v's underlying value is not a slice of runes (int32s). 267 func (v Value) runes() []rune { 268 v.mustBe(Slice) 269 if v.typ.Elem().Kind() != Int32 { 270 panic("reflect.Value.Bytes of non-rune slice") 271 } 272 // Slice is always bigger than a word; assume flagIndir. 273 return *(*[]rune)(v.ptr) 274 } 275 276 // CanAddr reports whether the value's address can be obtained with Addr. 277 // Such values are called addressable. A value is addressable if it is 278 // an element of a slice, an element of an addressable array, 279 // a field of an addressable struct, or the result of dereferencing a pointer. 280 // If CanAddr returns false, calling Addr will panic. 281 func (v Value) CanAddr() bool { 282 return v.flag&flagAddr != 0 283 } 284 285 // CanSet reports whether the value of v can be changed. 286 // A Value can be changed only if it is addressable and was not 287 // obtained by the use of unexported struct fields. 288 // If CanSet returns false, calling Set or interface{} type-specific 289 // setter (e.g., SetBool, SetInt) will panic. 290 func (v Value) CanSet() bool { 291 return v.flag&(flagAddr|flagRO) == flagAddr 292 } 293 294 // CanComplex reports whether Complex can be used without panicking. 295 func (v Value) CanComplex() bool { 296 switch v.kind() { 297 case Complex64, Complex128: 298 return true 299 default: 300 return false 301 } 302 } 303 304 // Complex returns v's underlying value, as a complex128. 305 // It panics if v's Kind is not Complex64 or Complex128 306 func (v Value) Complex() complex128 { 307 k := v.kind() 308 switch k { 309 case Complex64: 310 return complex128(*(*complex64)(v.ptr)) 311 case Complex128: 312 return *(*complex128)(v.ptr) 313 } 314 panic(&ValueError{"reflect.Value.Complex", v.kind()}) 315 } 316 317 // Elem returns the value that the interface v contains 318 // or that the pointer v points to. 319 // It panics if v's Kind is not Interface or Pointer. 320 // It returns the zero Value if v is nil. 321 func (v Value) Elem() Value { 322 k := v.kind() 323 switch k { 324 case Interface: 325 var eface interface{} 326 if v.typ.NumMethod() == 0 { 327 eface = *(*interface{})(v.ptr) 328 } else { 329 eface = (interface{})(*(*interface { 330 M() 331 })(v.ptr)) 332 } 333 x := unpackEface(eface) 334 if x.flag != 0 { 335 x.flag |= v.flag.ro() 336 } 337 return x 338 case Pointer: 339 ptr := v.ptr 340 if v.flag&flagIndir != 0 { 341 if ifaceIndir(v.typ) { 342 // This is a pointer to a not-in-heap object. ptr points to a uintptr 343 // in the heap. That uintptr is the address of a not-in-heap object. 344 // In general, pointers to not-in-heap objects can be total junk. 345 // But Elem() is asking to dereference it, so the user has asserted 346 // that at least it is a valid pointer (not just an integer stored in 347 // a pointer slot). So let's check, to make sure that it isn't a pointer 348 // that the runtime will crash on if it sees it during GC or write barriers. 349 // Since it is a not-in-heap pointer, all pointers to the heap are 350 // forbidden! That makes the test pretty easy. 351 // See issue 48399. 352 if !verifyNotInHeapPtr(*(*uintptr)(ptr)) { 353 panic("reflect: reflect.Value.Elem on an invalid notinheap pointer") 354 } 355 } 356 ptr = *(*unsafe.Pointer)(ptr) 357 } 358 // The returned value's address is v's value. 359 if ptr == nil { 360 return Value{} 361 } 362 tt := (*ptrType)(unsafe.Pointer(v.typ)) 363 typ := tt.elem 364 fl := v.flag&flagRO | flagIndir | flagAddr 365 fl |= flag(typ.Kind()) 366 return Value{typ, ptr, fl} 367 } 368 panic(&ValueError{"reflect.Value.Elem", v.kind()}) 369 } 370 371 // Field returns the i'th field of the struct v. 372 // It panics if v's Kind is not Struct or i is out of range. 373 func (v Value) Field(i int) Value { 374 if v.kind() != Struct { 375 panic(&ValueError{"reflect.Value.Field", v.kind()}) 376 } 377 tt := (*structType)(unsafe.Pointer(v.typ)) 378 if uint(i) >= uint(len(tt.fields)) { 379 panic("reflect: Field index out of range") 380 } 381 field := &tt.fields[i] 382 typ := field.typ 383 384 // Inherit permission bits from v, but clear flagEmbedRO. 385 fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind()) 386 // Using an unexported field forces flagRO. 387 if !field.name.isExported() { 388 if field.embedded() { 389 fl |= flagEmbedRO 390 } else { 391 fl |= flagStickyRO 392 } 393 } 394 // Either flagIndir is set and v.ptr points at struct, 395 // or flagIndir is not set and v.ptr is the actual struct data. 396 // In the former case, we want v.ptr + offset. 397 // In the latter case, we must have field.offset = 0, 398 // so v.ptr + field.offset is still the correct address. 399 ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field") 400 return Value{typ, ptr, fl} 401 } 402 403 // FieldByIndex returns the nested field corresponding to index. 404 // It panics if evaluation requires stepping through a nil 405 // pointer or a field that is not a struct. 406 func (v Value) FieldByIndex(index []int) Value { 407 if len(index) == 1 { 408 return v.Field(index[0]) 409 } 410 v.mustBe(Struct) 411 for i, x := range index { 412 if i > 0 { 413 if v.Kind() == Pointer && v.typ.Elem().Kind() == Struct { 414 if v.IsNil() { 415 panic("reflect: indirection through nil pointer to embedded struct") 416 } 417 v = v.Elem() 418 } 419 } 420 v = v.Field(x) 421 } 422 return v 423 } 424 425 // FieldByIndexErr returns the nested field corresponding to index. 426 // It returns an error if evaluation requires stepping through a nil 427 // pointer, but panics if it must step through a field that 428 // is not a struct. 429 func (v Value) FieldByIndexErr(index []int) (Value, error) { 430 if len(index) == 1 { 431 return v.Field(index[0]), nil 432 } 433 v.mustBe(Struct) 434 for i, x := range index { 435 if i > 0 { 436 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct { 437 if v.IsNil() { 438 return Value{}, errors.New("reflect: indirection through nil pointer to embedded struct field " + v.typ.Elem().Name()) 439 } 440 v = v.Elem() 441 } 442 } 443 v = v.Field(x) 444 } 445 return v, nil 446 } 447 448 // FieldByName returns the struct field with the given name. 449 // It returns the zero Value if no field was found. 450 // It panics if v's Kind is not struct. 451 func (v Value) FieldByName(name string) Value { 452 v.mustBe(Struct) 453 if f, ok := v.typ.FieldByName(name); ok { 454 return v.FieldByIndex(f.Index) 455 } 456 return Value{} 457 } 458 459 // FieldByNameFunc returns the struct field with a name 460 // that satisfies the match function. 461 // It panics if v's Kind is not struct. 462 // It returns the zero Value if no field was found. 463 func (v Value) FieldByNameFunc(match func(string) bool) Value { 464 if f, ok := v.typ.FieldByNameFunc(match); ok { 465 return v.FieldByIndex(f.Index) 466 } 467 return Value{} 468 } 469 470 // CanFloat reports whether Float can be used without panicking. 471 func (v Value) CanFloat() bool { 472 switch v.kind() { 473 case Float32, Float64: 474 return true 475 default: 476 return false 477 } 478 } 479 480 // Float returns v's underlying value, as a float64. 481 // It panics if v's Kind is not Float32 or Float64 482 func (v Value) Float() float64 { 483 k := v.kind() 484 switch k { 485 case Float32: 486 return float64(*(*float32)(v.ptr)) 487 case Float64: 488 return *(*float64)(v.ptr) 489 } 490 panic(&ValueError{"reflect.Value.Float", v.kind()}) 491 } 492 493 var uint8Type = TypeOf(uint8(0)).(*rtype) 494 495 // Index returns v's i'th element. 496 // It panics if v's Kind is not Array, Slice, or String or i is out of range. 497 func (v Value) Index(i int) Value { 498 switch v.kind() { 499 case Array: 500 tt := (*arrayType)(unsafe.Pointer(v.typ)) 501 if uint(i) >= uint(tt.len) { 502 panic("reflect: array index out of range") 503 } 504 typ := tt.elem 505 offset := uintptr(i) * typ.size 506 507 // Either flagIndir is set and v.ptr points at array, 508 // or flagIndir is not set and v.ptr is the actual array data. 509 // In the former case, we want v.ptr + offset. 510 // In the latter case, we must be doing Index(0), so offset = 0, 511 // so v.ptr + offset is still the correct address. 512 val := add(v.ptr, offset, "same as &v[i], i < tt.len") 513 fl := (flagIndir | flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array 514 return Value{typ, val, fl} 515 516 case Slice: 517 // Element flag same as Elem of Pointer. 518 // Addressable, indirect, possibly read-only. 519 s := (*unsafeheader.Slice)(v.ptr) 520 if uint(i) >= uint(s.Len) { 521 panic("reflect: slice index out of range") 522 } 523 tt := (*sliceType)(unsafe.Pointer(v.typ)) 524 typ := tt.elem 525 val := arrayAt(s.Data, i, typ.size, "i < s.Len") 526 fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind()) 527 return Value{typ, val, fl} 528 529 case String: 530 s := (*unsafeheader.String)(v.ptr) 531 if uint(i) >= uint(s.Len) { 532 panic("reflect: string index out of range") 533 } 534 p := arrayAt(s.Data, i, 1, "i < s.Len") 535 fl := v.flag.ro() | flag(Uint8) | flagIndir 536 return Value{uint8Type, p, fl} 537 } 538 panic(&ValueError{"reflect.Value.Index", v.kind()}) 539 } 540 541 // CanInt reports whether Int can be used without panicking. 542 func (v Value) CanInt() bool { 543 switch v.kind() { 544 case Int, Int8, Int16, Int32, Int64: 545 return true 546 default: 547 return false 548 } 549 } 550 551 // Int returns v's underlying value, as an int64. 552 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. 553 func (v Value) Int() int64 { 554 k := v.kind() 555 p := v.ptr 556 switch k { 557 case Int: 558 return int64(*(*int)(p)) 559 case Int8: 560 return int64(*(*int8)(p)) 561 case Int16: 562 return int64(*(*int16)(p)) 563 case Int32: 564 return int64(*(*int32)(p)) 565 case Int64: 566 return *(*int64)(p) 567 } 568 panic(&ValueError{"reflect.Value.Int", v.kind()}) 569 } 570 571 // CanInterface reports whether Interface can be used without panicking. 572 func (v Value) CanInterface() bool { 573 if v.flag == 0 { 574 panic(&ValueError{"reflect.Value.CanInterface", Invalid}) 575 } 576 return v.flag&flagRO == 0 577 } 578 579 // Interface returns v's current value as an interface{}. 580 // It is equivalent to: 581 // 582 // var i interface{} = (v's underlying value) 583 // 584 // It panics if the Value was obtained by accessing 585 // unexported struct fields. 586 func (v Value) Interface() (i interface{}) { 587 return valueInterface(v, true) 588 } 589 590 func valueInterface(v Value, safe bool) interface{} { 591 if v.flag == 0 { 592 panic(&ValueError{"reflect.Value.Interface", Invalid}) 593 } 594 if safe && v.flag&flagRO != 0 { 595 // Do not allow access to unexported values via Interface, 596 // because they might be pointers that should not be 597 // writable or methods or function that should not be callable. 598 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method") 599 } 600 if v.flag&flagMethod != 0 { 601 panic("method values not supported in reflectlite") 602 } 603 604 if v.kind() == Interface { 605 // Special case: return the element inside the interface. 606 // Empty interface has one layout, all interfaces with 607 // methods have a second layout. 608 if v.NumMethod() == 0 { 609 return *(*interface{})(v.ptr) 610 } 611 return *(*interface { 612 M() 613 })(v.ptr) 614 } 615 616 // TODO: pass safe to packEface so we don't need to copy if safe==true? 617 return packEface(v) 618 } 619 620 // InterfaceData returns a pair of unspecified uintptr values. 621 // It panics if v's Kind is not Interface. 622 // 623 // In earlier versions of Go, this function returned the interface's 624 // value as a uintptr pair. As of Go 1.4, the implementation of 625 // interface values precludes interface{} defined use of InterfaceData. 626 // 627 // Deprecated: The memory representation of interface values is not 628 // compatible with InterfaceData. 629 func (v Value) InterfaceData() [2]uintptr { 630 v.mustBe(Interface) 631 // We treat this as a read operation, so we allow 632 // it even for unexported data, because the caller 633 // has to import "unsafe" to turn it into something 634 // that can be abused. 635 // Interface value is always bigger than a word; assume flagIndir. 636 return *(*[2]uintptr)(v.ptr) 637 } 638 639 // IsNil reports whether its argument v is nil. The argument must be 640 // a chan, func, interface, map, pointer, or slice value; if it is 641 // not, IsNil panics. Note that IsNil is not always equivalent to a 642 // regular comparison with nil in Go. For example, if v was created 643 // by calling ValueOf with an uninitialized interface variable i, 644 // i==nil will be true but v.IsNil will panic as v will be the zero 645 // Value. 646 func (v Value) IsNil() bool { 647 k := v.kind() 648 switch k { 649 case Chan, Func, Map, Pointer, UnsafePointer: 650 if v.flag&flagMethod != 0 { 651 return false 652 } 653 ptr := v.ptr 654 if v.flag&flagIndir != 0 { 655 ptr = *(*unsafe.Pointer)(ptr) 656 } 657 return ptr == nil 658 case Interface, Slice: 659 // Both interface and slice are nil if first word is 0. 660 // Both are always bigger than a word; assume flagIndir. 661 return *(*unsafe.Pointer)(v.ptr) == nil 662 } 663 panic(&ValueError{"reflect.Value.IsNil", v.kind()}) 664 } 665 666 // IsValid reports whether v represents a value. 667 // It returns false if v is the zero Value. 668 // If IsValid returns false, all other methods except String panic. 669 // Most functions and methods never return an invalid Value. 670 // If one does, its documentation states the conditions explicitly. 671 func (v Value) IsValid() bool { 672 return v.flag != 0 673 } 674 675 // IsZero reports whether v is the zero value for its type. 676 // It panics if the argument is invalid. 677 func (v Value) IsZero() bool { 678 switch v.kind() { 679 case Bool: 680 return !v.Bool() 681 case Int, Int8, Int16, Int32, Int64: 682 return v.Int() == 0 683 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 684 return v.Uint() == 0 685 case Float32, Float64: 686 return math.Float64bits(v.Float()) == 0 687 case Complex64, Complex128: 688 c := v.Complex() 689 return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 690 case Array: 691 for i := 0; i < v.Len(); i++ { 692 if !v.Index(i).IsZero() { 693 return false 694 } 695 } 696 return true 697 case Chan, Func, Interface, Map, Pointer, Slice, UnsafePointer: 698 return v.IsNil() 699 case String: 700 return v.Len() == 0 701 case Struct: 702 for i := 0; i < v.NumField(); i++ { 703 if !v.Field(i).IsZero() { 704 return false 705 } 706 } 707 return true 708 default: 709 // This should never happens, but will act as a safeguard for 710 // later, as a default value doesn't makes sense here. 711 panic(&ValueError{"reflect.Value.IsZero", v.Kind()}) 712 } 713 } 714 715 // Kind returns v's Kind. 716 // If v is the zero Value (IsValid returns false), Kind returns Invalid. 717 func (v Value) Kind() Kind { 718 return v.kind() 719 } 720 721 // Len returns v's length. 722 // It panics if v's Kind is not Array, Chan, Map, Slice, or String. 723 func (v Value) Len() int { 724 k := v.kind() 725 switch k { 726 case Array: 727 tt := (*arrayType)(unsafe.Pointer(v.typ)) 728 return int(tt.len) 729 case Chan: 730 return chanlen(v.pointer()) 731 case Map: 732 return maplen(v.pointer()) 733 case Slice: 734 // Slice is bigger than a word; assume flagIndir. 735 return (*unsafeheader.Slice)(v.ptr).Len 736 case String: 737 // String is bigger than a word; assume flagIndir. 738 return (*unsafeheader.String)(v.ptr).Len 739 } 740 panic(&ValueError{"reflect.Value.Len", v.kind()}) 741 } 742 743 var stringType = TypeOf("").(*rtype) 744 745 // MapIndex returns the value associated with key in the map v. 746 // It panics if v's Kind is not Map. 747 // It returns the zero Value if key is not found in the map or if v represents a nil map. 748 // As in Go, the key's value must be assignable to the map's key type. 749 func (v Value) MapIndex(key Value) Value { 750 v.mustBe(Map) 751 tt := (*mapType)(unsafe.Pointer(v.typ)) 752 753 // Do not require key to be exported, so that DeepEqual 754 // and other programs can use all the keys returned by 755 // MapKeys as arguments to MapIndex. If either the map 756 // or the key is unexported, though, the result will be 757 // considered unexported. This is consistent with the 758 // behavior for structs, which allow read but not write 759 // of unexported fields. 760 761 var e unsafe.Pointer 762 if (tt.key == stringType || key.kind() == String) && tt.key == key.typ && tt.elem.size <= maxValSize { 763 k := *(*string)(key.ptr) 764 e = mapaccess_faststr(v.typ, v.pointer(), k) 765 } else { 766 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil) 767 var k unsafe.Pointer 768 if key.flag&flagIndir != 0 { 769 k = key.ptr 770 } else { 771 k = unsafe.Pointer(&key.ptr) 772 } 773 e = mapaccess(v.typ, v.pointer(), k) 774 } 775 if e == nil { 776 return Value{} 777 } 778 typ := tt.elem 779 fl := (v.flag | key.flag).ro() 780 fl |= flag(typ.Kind()) 781 return copyVal(typ, fl, e) 782 } 783 784 // MapKeys returns a slice containing all the keys present in the map, 785 // in unspecified order. 786 // It panics if v's Kind is not Map. 787 // It returns an empty slice if v represents a nil map. 788 func (v Value) MapKeys() []Value { 789 v.mustBe(Map) 790 tt := (*mapType)(unsafe.Pointer(v.typ)) 791 keyType := tt.key 792 793 fl := v.flag.ro() | flag(keyType.Kind()) 794 795 m := v.pointer() 796 mlen := int(0) 797 if m != nil { 798 mlen = maplen(m) 799 } 800 var it hiter 801 mapiterinit(v.typ, m, &it) 802 a := make([]Value, mlen) 803 var i int 804 for i = 0; i < len(a); i++ { 805 key := mapiterkey(&it) 806 if key == nil { 807 // Someone deleted an entry from the map since we 808 // called maplen above. It's a data race, but nothing 809 // we can do about it. 810 break 811 } 812 a[i] = copyVal(keyType, fl, key) 813 mapiternext(&it) 814 } 815 return a[:i] 816 } 817 818 // hiter's structure matches runtime.hiter's structure. 819 // Having a clone here allows us to embed a map iterator 820 // inside type MapIter so that MapIters can be re-used 821 // without doing interface{} allocations. 822 type hiter struct { 823 key unsafe.Pointer 824 elem unsafe.Pointer 825 t unsafe.Pointer 826 h unsafe.Pointer 827 buckets unsafe.Pointer 828 bptr unsafe.Pointer 829 overflow *[]unsafe.Pointer 830 oldoverflow *[]unsafe.Pointer 831 startBucket uintptr 832 offset uint8 833 wrapped bool 834 B uint8 835 i uint8 836 bucket uintptr 837 checkBucket uintptr 838 } 839 840 func (h *hiter) initialized() bool { 841 return h.t != nil 842 } 843 844 // A MapIter is an iterator for ranging over a map. 845 // See Value.MapRange. 846 type MapIter struct { 847 m Value 848 hiter hiter 849 } 850 851 // Key returns the key of iter's current map entry. 852 func (iter *MapIter) Key() Value { 853 if !iter.hiter.initialized() { 854 panic("MapIter.Key called before Next") 855 } 856 iterkey := mapiterkey(&iter.hiter) 857 if iterkey == nil { 858 panic("MapIter.Key called on exhausted iterator") 859 } 860 861 t := (*mapType)(unsafe.Pointer(iter.m.typ)) 862 ktype := t.key 863 return copyVal(ktype, iter.m.flag.ro()|flag(ktype.Kind()), iterkey) 864 } 865 866 // SetIterKey assigns to v the key of iter's current map entry. 867 // It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value. 868 // As in Go, the key must be assignable to v's type. 869 func (v Value) SetIterKey(iter *MapIter) { 870 if !iter.hiter.initialized() { 871 panic("reflect: Value.SetIterKey called before Next") 872 } 873 iterkey := mapiterkey(&iter.hiter) 874 if iterkey == nil { 875 panic("reflect: Value.SetIterKey called on exhausted iterator") 876 } 877 878 v.mustBeAssignable() 879 var target unsafe.Pointer 880 if v.kind() == Interface { 881 target = v.ptr 882 } 883 884 t := (*mapType)(unsafe.Pointer(iter.m.typ)) 885 ktype := t.key 886 887 key := Value{ktype, iterkey, iter.m.flag | flag(ktype.Kind()) | flagIndir} 888 key = key.assignTo("reflect.MapIter.SetKey", v.typ, target) 889 typedmemmove(v.typ, v.ptr, key.ptr) 890 } 891 892 // Value returns the value of iter's current map entry. 893 func (iter *MapIter) Value() Value { 894 if !iter.hiter.initialized() { 895 panic("MapIter.Value called before Next") 896 } 897 iterelem := mapiterelem(&iter.hiter) 898 if iterelem == nil { 899 panic("MapIter.Value called on exhausted iterator") 900 } 901 902 t := (*mapType)(unsafe.Pointer(iter.m.typ)) 903 vtype := t.elem 904 return copyVal(vtype, iter.m.flag.ro()|flag(vtype.Kind()), iterelem) 905 } 906 907 // SetIterValue assigns to v the value of iter's current map entry. 908 // It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value. 909 // As in Go, the value must be assignable to v's type. 910 func (v Value) SetIterValue(iter *MapIter) { 911 if !iter.hiter.initialized() { 912 panic("reflect: Value.SetIterValue called before Next") 913 } 914 iterelem := mapiterelem(&iter.hiter) 915 if iterelem == nil { 916 panic("reflect: Value.SetIterValue called on exhausted iterator") 917 } 918 919 v.mustBeAssignable() 920 var target unsafe.Pointer 921 if v.kind() == Interface { 922 target = v.ptr 923 } 924 925 t := (*mapType)(unsafe.Pointer(iter.m.typ)) 926 vtype := t.elem 927 928 elem := Value{vtype, iterelem, iter.m.flag | flag(vtype.Kind()) | flagIndir} 929 elem = elem.assignTo("reflect.MapIter.SetValue", v.typ, target) 930 typedmemmove(v.typ, v.ptr, elem.ptr) 931 } 932 933 // Next advances the map iterator and reports whether there is another 934 // entry. It returns false when iter is exhausted; subsequent 935 // calls to Key, Value, or Next will panic. 936 func (iter *MapIter) Next() bool { 937 if !iter.m.IsValid() { 938 panic("MapIter.Next called on an iterator that does not have an associated map Value") 939 } 940 if !iter.hiter.initialized() { 941 mapiterinit(iter.m.typ, iter.m.pointer(), &iter.hiter) 942 } else { 943 if mapiterkey(&iter.hiter) == nil { 944 panic("MapIter.Next called on exhausted iterator") 945 } 946 mapiternext(&iter.hiter) 947 } 948 return mapiterkey(&iter.hiter) != nil 949 } 950 951 // Reset modifies iter to iterate over v. 952 // It panics if v's Kind is not Map and v is not the zero Value. 953 // Reset(Value{}) causes iter to not to refer to interface{} map, 954 // which may allow the previously iterated-over map to be garbage collected. 955 func (iter *MapIter) Reset(v Value) { 956 if v.IsValid() { 957 v.mustBe(Map) 958 } 959 iter.m = v 960 iter.hiter = hiter{} 961 } 962 963 // MapRange returns a range iterator for a map. 964 // It panics if v's Kind is not Map. 965 // 966 // Call Next to advance the iterator, and Key/Value to access each entry. 967 // Next returns false when the iterator is exhausted. 968 // MapRange follows the same iteration semantics as a range statement. 969 // 970 // Example: 971 // 972 // iter := reflect.ValueOf(m).MapRange() 973 // for iter.Next() { 974 // k := iter.Key() 975 // v := iter.Value() 976 // ... 977 // } 978 func (v Value) MapRange() *MapIter { 979 v.mustBe(Map) 980 return &MapIter{m: v} 981 } 982 983 // copyVal returns a Value containing the map key or value at ptr, 984 // allocating a new variable as needed. 985 func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value { 986 if ifaceIndir(typ) { 987 // Copy result so future changes to the map 988 // won't change the underlying value. 989 c := unsafe_New(typ) 990 typedmemmove(typ, c, ptr) 991 return Value{typ, c, fl | flagIndir} 992 } 993 return Value{typ, *(*unsafe.Pointer)(ptr), fl} 994 } 995 996 // Method returns a function value corresponding to v's i'th method. 997 // The arguments to a Call on the returned function should not include 998 // a receiver; the returned function will always use v as the receiver. 999 // Method panics if i is out of range or if v is a nil interface value. 1000 func (v Value) Method(i int) Value { 1001 if v.typ == nil { 1002 panic(&ValueError{"reflect.Value.Method", Invalid}) 1003 } 1004 if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) { 1005 panic("reflect: Method index out of range") 1006 } 1007 if v.typ.Kind() == Interface && v.IsNil() { 1008 panic("reflect: Method on nil interface value") 1009 } 1010 fl := v.flag.ro() | (v.flag & flagIndir) 1011 fl |= flag(Func) 1012 fl |= flag(i)<<flagMethodShift | flagMethod 1013 return Value{v.typ, v.ptr, fl} 1014 } 1015 1016 // NumMethod returns the number of exported methods in the value's method set. 1017 func (v Value) NumMethod() int { 1018 if v.typ == nil { 1019 panic(&ValueError{"reflect.Value.NumMethod", Invalid}) 1020 } 1021 if v.flag&flagMethod != 0 { 1022 return 0 1023 } 1024 return v.typ.NumMethod() 1025 } 1026 1027 // NumField returns the number of fields in the struct v. 1028 // It panics if v's Kind is not Struct. 1029 func (v Value) NumField() int { 1030 v.mustBe(Struct) 1031 tt := (*structType)(unsafe.Pointer(v.typ)) 1032 return len(tt.fields) 1033 } 1034 1035 // OverflowComplex reports whether the complex128 x cannot be represented by v's type. 1036 // It panics if v's Kind is not Complex64 or Complex128. 1037 func (v Value) OverflowComplex(x complex128) bool { 1038 k := v.kind() 1039 switch k { 1040 case Complex64: 1041 return overflowFloat32(real(x)) || overflowFloat32(imag(x)) 1042 case Complex128: 1043 return false 1044 } 1045 panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()}) 1046 } 1047 1048 // OverflowFloat reports whether the float64 x cannot be represented by v's type. 1049 // It panics if v's Kind is not Float32 or Float64. 1050 func (v Value) OverflowFloat(x float64) bool { 1051 k := v.kind() 1052 switch k { 1053 case Float32: 1054 return overflowFloat32(x) 1055 case Float64: 1056 return false 1057 } 1058 panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()}) 1059 } 1060 1061 func overflowFloat32(x float64) bool { 1062 if x < 0 { 1063 x = -x 1064 } 1065 return math.MaxFloat32 < x && x <= math.MaxFloat64 1066 } 1067 1068 // OverflowInt reports whether the int64 x cannot be represented by v's type. 1069 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. 1070 func (v Value) OverflowInt(x int64) bool { 1071 k := v.kind() 1072 switch k { 1073 case Int, Int8, Int16, Int32, Int64: 1074 bitSize := v.typ.size * 8 1075 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1076 return x != trunc 1077 } 1078 panic(&ValueError{"reflect.Value.OverflowInt", v.kind()}) 1079 } 1080 1081 // OverflowUint reports whether the uint64 x cannot be represented by v's type. 1082 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1083 func (v Value) OverflowUint(x uint64) bool { 1084 k := v.kind() 1085 switch k { 1086 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64: 1087 bitSize := v.typ.size * 8 1088 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1089 return x != trunc 1090 } 1091 panic(&ValueError{"reflect.Value.OverflowUint", v.kind()}) 1092 } 1093 1094 //go:nocheckptr 1095 // This prevents inlining Value.Pointer when -d=checkptr is enabled, 1096 // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer()) 1097 // and make an exception. 1098 1099 // Pointer returns v's value as a uintptr. 1100 // It returns uintptr instead of unsafe.Pointer so that 1101 // code using reflect cannot obtain unsafe.Pointers 1102 // without importing the unsafe package explicitly. 1103 // It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer. 1104 // 1105 // If v's Kind is Func, the returned pointer is an underlying 1106 // code pointer, but not necessarily enough to identify a 1107 // single function uniquely. The only guarantee is that the 1108 // result is zero if and only if v is a nil func Value. 1109 // 1110 // If v's Kind is Slice, the returned pointer is to the first 1111 // element of the slice. If the slice is nil the returned value 1112 // is 0. If the slice is empty but non-nil the return value is non-zero. 1113 // 1114 // It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result. 1115 func (v Value) Pointer() uintptr { 1116 k := v.kind() 1117 switch k { 1118 case Pointer: 1119 if v.typ.ptrdata == 0 { 1120 val := *(*uintptr)(v.ptr) 1121 // Since it is a not-in-heap pointer, all pointers to the heap are 1122 // forbidden! See comment in Value.Elem and issue #48399. 1123 if !verifyNotInHeapPtr(val) { 1124 panic("reflect: reflect.Value.Pointer on an invalid notinheap pointer") 1125 } 1126 return val 1127 } 1128 fallthrough 1129 case Chan, Map, UnsafePointer: 1130 return uintptr(v.pointer()) 1131 case Func: 1132 if v.flag&flagMethod != 0 { 1133 panic("method values not supported in reflectlite") 1134 } 1135 p := v.pointer() 1136 // Non-nil func value points at data block. 1137 // First word of data block is actual code. 1138 if p != nil { 1139 p = *(*unsafe.Pointer)(p) 1140 } 1141 return uintptr(p) 1142 1143 case Slice: 1144 return (*SliceHeader)(v.ptr).Data 1145 } 1146 panic(&ValueError{"reflect.Value.Pointer", v.kind()}) 1147 } 1148 1149 // Set assigns x to the value v. 1150 // It panics if CanSet returns false. 1151 // As in Go, x's value must be assignable to v's type. 1152 func (v Value) Set(x Value) { 1153 v.mustBeAssignable() 1154 var target unsafe.Pointer 1155 if v.kind() == Interface { 1156 target = v.ptr 1157 } 1158 x = x.assignTo("reflect.Set", v.typ, target) 1159 if x.flag&flagIndir != 0 { 1160 if x.ptr == unsafe.Pointer(&zeroVal[0]) { 1161 typedmemclr(v.typ, v.ptr) 1162 } else { 1163 typedmemmove(v.typ, v.ptr, x.ptr) 1164 } 1165 } else { 1166 *(*unsafe.Pointer)(v.ptr) = x.ptr 1167 } 1168 } 1169 1170 // SetBool sets v's underlying value. 1171 // It panics if v's Kind is not Bool or if CanSet() is false. 1172 func (v Value) SetBool(x bool) { 1173 v.mustBeAssignable() 1174 v.mustBe(Bool) 1175 *(*bool)(v.ptr) = x 1176 } 1177 1178 // SetBytes sets v's underlying value. 1179 // It panics if v's underlying value is not a slice of bytes. 1180 func (v Value) SetBytes(x []byte) { 1181 v.mustBeAssignable() 1182 v.mustBe(Slice) 1183 if v.typ.Elem().Kind() != Uint8 { 1184 panic("reflect.Value.SetBytes of non-byte slice") 1185 } 1186 *(*[]byte)(v.ptr) = x 1187 } 1188 1189 // setRunes sets v's underlying value. 1190 // It panics if v's underlying value is not a slice of runes (int32s). 1191 func (v Value) setRunes(x []rune) { 1192 v.mustBeAssignable() 1193 v.mustBe(Slice) 1194 if v.typ.Elem().Kind() != Int32 { 1195 panic("reflect.Value.setRunes of non-rune slice") 1196 } 1197 *(*[]rune)(v.ptr) = x 1198 } 1199 1200 // SetComplex sets v's underlying value to x. 1201 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false. 1202 func (v Value) SetComplex(x complex128) { 1203 v.mustBeAssignable() 1204 switch k := v.kind(); k { 1205 default: 1206 panic(&ValueError{"reflect.Value.SetComplex", v.kind()}) 1207 case Complex64: 1208 *(*complex64)(v.ptr) = complex64(x) 1209 case Complex128: 1210 *(*complex128)(v.ptr) = x 1211 } 1212 } 1213 1214 // SetFloat sets v's underlying value to x. 1215 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false. 1216 func (v Value) SetFloat(x float64) { 1217 v.mustBeAssignable() 1218 switch k := v.kind(); k { 1219 default: 1220 panic(&ValueError{"reflect.Value.SetFloat", v.kind()}) 1221 case Float32: 1222 *(*float32)(v.ptr) = float32(x) 1223 case Float64: 1224 *(*float64)(v.ptr) = x 1225 } 1226 } 1227 1228 // SetInt sets v's underlying value to x. 1229 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false. 1230 func (v Value) SetInt(x int64) { 1231 v.mustBeAssignable() 1232 switch k := v.kind(); k { 1233 default: 1234 panic(&ValueError{"reflect.Value.SetInt", v.kind()}) 1235 case Int: 1236 *(*int)(v.ptr) = int(x) 1237 case Int8: 1238 *(*int8)(v.ptr) = int8(x) 1239 case Int16: 1240 *(*int16)(v.ptr) = int16(x) 1241 case Int32: 1242 *(*int32)(v.ptr) = int32(x) 1243 case Int64: 1244 *(*int64)(v.ptr) = x 1245 } 1246 } 1247 1248 // SetLen sets v's length to n. 1249 // It panics if v's Kind is not Slice or if n is negative or 1250 // greater than the capacity of the slice. 1251 func (v Value) SetLen(n int) { 1252 v.mustBeAssignable() 1253 v.mustBe(Slice) 1254 s := (*unsafeheader.Slice)(v.ptr) 1255 if uint(n) > uint(s.Cap) { 1256 panic("reflect: slice length out of range in SetLen") 1257 } 1258 s.Len = n 1259 } 1260 1261 // SetCap sets v's capacity to n. 1262 // It panics if v's Kind is not Slice or if n is smaller than the length or 1263 // greater than the capacity of the slice. 1264 func (v Value) SetCap(n int) { 1265 v.mustBeAssignable() 1266 v.mustBe(Slice) 1267 s := (*unsafeheader.Slice)(v.ptr) 1268 if n < s.Len || n > s.Cap { 1269 panic("reflect: slice capacity out of range in SetCap") 1270 } 1271 s.Cap = n 1272 } 1273 1274 // SetMapIndex sets the element associated with key in the map v to elem. 1275 // It panics if v's Kind is not Map. 1276 // If elem is the zero Value, SetMapIndex deletes the key from the map. 1277 // Otherwise if v holds a nil map, SetMapIndex will panic. 1278 // As in Go, key's elem must be assignable to the map's key type, 1279 // and elem's value must be assignable to the map's elem type. 1280 func (v Value) SetMapIndex(key, elem Value) { 1281 v.mustBe(Map) 1282 tt := (*mapType)(unsafe.Pointer(v.typ)) 1283 1284 if (tt.key == stringType || key.kind() == String) && tt.key == key.typ && tt.elem.size <= maxValSize { 1285 k := *(*string)(key.ptr) 1286 if elem.typ == nil { 1287 mapdelete_faststr(v.typ, v.pointer(), k) 1288 return 1289 } 1290 elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil) 1291 var e unsafe.Pointer 1292 if elem.flag&flagIndir != 0 { 1293 e = elem.ptr 1294 } else { 1295 e = unsafe.Pointer(&elem.ptr) 1296 } 1297 mapassign_faststr(v.typ, v.pointer(), k, e) 1298 return 1299 } 1300 1301 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil) 1302 var k unsafe.Pointer 1303 if key.flag&flagIndir != 0 { 1304 k = key.ptr 1305 } else { 1306 k = unsafe.Pointer(&key.ptr) 1307 } 1308 if elem.typ == nil { 1309 mapdelete(v.typ, v.pointer(), k) 1310 return 1311 } 1312 elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil) 1313 var e unsafe.Pointer 1314 if elem.flag&flagIndir != 0 { 1315 e = elem.ptr 1316 } else { 1317 e = unsafe.Pointer(&elem.ptr) 1318 } 1319 mapassign(v.typ, v.pointer(), k, e) 1320 } 1321 1322 // SetUint sets v's underlying value to x. 1323 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false. 1324 func (v Value) SetUint(x uint64) { 1325 v.mustBeAssignable() 1326 switch k := v.kind(); k { 1327 default: 1328 panic(&ValueError{"reflect.Value.SetUint", v.kind()}) 1329 case Uint: 1330 *(*uint)(v.ptr) = uint(x) 1331 case Uint8: 1332 *(*uint8)(v.ptr) = uint8(x) 1333 case Uint16: 1334 *(*uint16)(v.ptr) = uint16(x) 1335 case Uint32: 1336 *(*uint32)(v.ptr) = uint32(x) 1337 case Uint64: 1338 *(*uint64)(v.ptr) = x 1339 case Uintptr: 1340 *(*uintptr)(v.ptr) = uintptr(x) 1341 } 1342 } 1343 1344 // SetPointer sets the unsafe.Pointer value v to x. 1345 // It panics if v's Kind is not UnsafePointer. 1346 func (v Value) SetPointer(x unsafe.Pointer) { 1347 v.mustBeAssignable() 1348 v.mustBe(UnsafePointer) 1349 *(*unsafe.Pointer)(v.ptr) = x 1350 } 1351 1352 // SetString sets v's underlying value to x. 1353 // It panics if v's Kind is not String or if CanSet() is false. 1354 func (v Value) SetString(x string) { 1355 v.mustBeAssignable() 1356 v.mustBe(String) 1357 *(*string)(v.ptr) = x 1358 } 1359 1360 // Slice returns v[i:j]. 1361 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, 1362 // or if the indexes are out of bounds. 1363 func (v Value) Slice(i, j int) Value { 1364 var ( 1365 cap int 1366 typ *sliceType 1367 base unsafe.Pointer 1368 ) 1369 switch kind := v.kind(); kind { 1370 default: 1371 panic(&ValueError{"reflect.Value.Slice", v.kind()}) 1372 1373 case Array: 1374 if v.flag&flagAddr == 0 { 1375 panic("reflect.Value.Slice: slice of unaddressable array") 1376 } 1377 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1378 cap = int(tt.len) 1379 typ = (*sliceType)(unsafe.Pointer(tt.slice)) 1380 base = v.ptr 1381 1382 case Slice: 1383 typ = (*sliceType)(unsafe.Pointer(v.typ)) 1384 s := (*unsafeheader.Slice)(v.ptr) 1385 base = s.Data 1386 cap = s.Cap 1387 1388 case String: 1389 s := (*unsafeheader.String)(v.ptr) 1390 if i < 0 || j < i || j > s.Len { 1391 panic("reflect.Value.Slice: string slice index out of bounds") 1392 } 1393 var t unsafeheader.String 1394 if i < s.Len { 1395 t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i} 1396 } 1397 return Value{v.typ, unsafe.Pointer(&t), v.flag} 1398 } 1399 1400 if i < 0 || j < i || j > cap { 1401 panic("reflect.Value.Slice: slice index out of bounds") 1402 } 1403 1404 // Declare slice so that gc can see the base pointer in it. 1405 var x []unsafe.Pointer 1406 1407 // Reinterpret as *unsafeheader.Slice to edit. 1408 s := (*unsafeheader.Slice)(unsafe.Pointer(&x)) 1409 s.Len = j - i 1410 s.Cap = cap - i 1411 if cap-i > 0 { 1412 s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap") 1413 } else { 1414 // do not advance pointer, to avoid pointing beyond end of slice 1415 s.Data = base 1416 } 1417 1418 fl := v.flag.ro() | flagIndir | flag(Slice) 1419 return Value{typ.common(), unsafe.Pointer(&x), fl} 1420 } 1421 1422 // String returns the string v's underlying value, as a string. 1423 // String is a special case because of Go's String method convention. 1424 // Unlike the other getters, it does not panic if v's Kind is not String. 1425 // Instead, it returns a string of the form "<T value>" where T is v's type. 1426 // The fmt package treats Values specially. It does not call their String 1427 // method implicitly but instead prints the concrete values they hold. 1428 func (v Value) String() string { 1429 switch k := v.kind(); k { 1430 case Invalid: 1431 return "<invalid Value>" 1432 case String: 1433 return *(*string)(v.ptr) 1434 } 1435 // If you call String on a reflect.Value of other type, it's better to 1436 // print something than to panic. Useful in debugging. 1437 return "<" + v.Type().String() + " Value>" 1438 } 1439 1440 // Type returns v's type. 1441 func (v Value) Type() Type { 1442 f := v.flag 1443 if f == 0 { 1444 panic(&ValueError{"reflect.Value.Type", Invalid}) 1445 } 1446 if f&flagMethod == 0 { 1447 // Easy case 1448 return v.typ 1449 } 1450 1451 // Method value. 1452 // v.typ describes the receiver, not the method type. 1453 i := int(v.flag) >> flagMethodShift 1454 if v.typ.Kind() == Interface { 1455 // Method on interface. 1456 tt := (*interfaceType)(unsafe.Pointer(v.typ)) 1457 if uint(i) >= uint(len(tt.methods)) { 1458 panic("reflect: internal error: invalid method index") 1459 } 1460 m := &tt.methods[i] 1461 return v.typ.typeOff(m.typ) 1462 } 1463 // Method on concrete type. 1464 ms := v.typ.exportedMethods() 1465 if uint(i) >= uint(len(ms)) { 1466 panic("reflect: internal error: invalid method index") 1467 } 1468 m := ms[i] 1469 return v.typ.typeOff(m.mtyp) 1470 } 1471 1472 // CanUint reports whether Uint can be used without panicking. 1473 func (v Value) CanUint() bool { 1474 switch v.kind() { 1475 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 1476 return true 1477 default: 1478 return false 1479 } 1480 } 1481 1482 // Uint returns v's underlying value, as a uint64. 1483 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1484 func (v Value) Uint() uint64 { 1485 k := v.kind() 1486 p := v.ptr 1487 switch k { 1488 case Uint: 1489 return uint64(*(*uint)(p)) 1490 case Uint8: 1491 return uint64(*(*uint8)(p)) 1492 case Uint16: 1493 return uint64(*(*uint16)(p)) 1494 case Uint32: 1495 return uint64(*(*uint32)(p)) 1496 case Uint64: 1497 return *(*uint64)(p) 1498 case Uintptr: 1499 return uint64(*(*uintptr)(p)) 1500 } 1501 panic(&ValueError{"reflect.Value.Uint", v.kind()}) 1502 } 1503 1504 //go:nocheckptr 1505 // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled, 1506 // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr()) 1507 // and make an exception. 1508 1509 // UnsafeAddr returns a pointer to v's data, as a uintptr. 1510 // It is for advanced clients that also import the "unsafe" package. 1511 // It panics if v is not addressable. 1512 // 1513 // It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result. 1514 func (v Value) UnsafeAddr() uintptr { 1515 if v.typ == nil { 1516 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid}) 1517 } 1518 if v.flag&flagAddr == 0 { 1519 panic("reflect.Value.UnsafeAddr of unaddressable value") 1520 } 1521 return uintptr(v.ptr) 1522 } 1523 1524 // UnsafePointer returns v's value as a unsafe.Pointer. 1525 // It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer. 1526 // 1527 // If v's Kind is Func, the returned pointer is an underlying 1528 // code pointer, but not necessarily enough to identify a 1529 // single function uniquely. The only guarantee is that the 1530 // result is zero if and only if v is a nil func Value. 1531 // 1532 // If v's Kind is Slice, the returned pointer is to the first 1533 // element of the slice. If the slice is nil the returned value 1534 // is nil. If the slice is empty but non-nil the return value is non-nil. 1535 func (v Value) UnsafePointer() unsafe.Pointer { 1536 k := v.kind() 1537 switch k { 1538 case Pointer: 1539 if v.typ.ptrdata == 0 { 1540 // Since it is a not-in-heap pointer, all pointers to the heap are 1541 // forbidden! See comment in Value.Elem and issue #48399. 1542 if !verifyNotInHeapPtr(*(*uintptr)(v.ptr)) { 1543 panic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer") 1544 } 1545 return *(*unsafe.Pointer)(v.ptr) 1546 } 1547 fallthrough 1548 case Chan, Map, UnsafePointer: 1549 return v.pointer() 1550 case Func: 1551 if v.flag&flagMethod != 0 { 1552 panic("method values not supported in reflectlite") 1553 } 1554 p := v.pointer() 1555 // Non-nil func value points at data block. 1556 // First word of data block is actual code. 1557 if p != nil { 1558 p = *(*unsafe.Pointer)(p) 1559 } 1560 return p 1561 1562 case Slice: 1563 return (*unsafeheader.Slice)(v.ptr).Data 1564 } 1565 panic(&ValueError{"reflect.Value.UnsafePointer", v.kind()}) 1566 } 1567 1568 // StringHeader is the runtime representation of a string. 1569 // It cannot be used safely or portably and its representation may 1570 // change in a later release. 1571 // Moreover, the Data field is not sufficient to guarantee the data 1572 // it references will not be garbage collected, so programs must keep 1573 // a separate, correctly typed pointer to the underlying data. 1574 type StringHeader struct { 1575 Data uintptr 1576 Len int 1577 } 1578 1579 // SliceHeader is the runtime representation of a slice. 1580 // It cannot be used safely or portably and its representation may 1581 // change in a later release. 1582 // Moreover, the Data field is not sufficient to guarantee the data 1583 // it references will not be garbage collected, so programs must keep 1584 // a separate, correctly typed pointer to the underlying data. 1585 type SliceHeader struct { 1586 Data uintptr 1587 Len int 1588 Cap int 1589 } 1590 1591 // arrayAt returns the i-th element of p, 1592 // an array whose elements are eltSize bytes wide. 1593 // The array pointed at by p must have at least i+1 elements: 1594 // it is invalid (but impossible to check here) to pass i >= len, 1595 // because then the result will point outside the array. 1596 // whySafe must explain why i < len. (Passing "i < len" is fine; 1597 // the benefit is to surface this assumption at the call site.) 1598 func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer { 1599 return add(p, uintptr(i)*eltSize, "i < len") 1600 } 1601 1602 /* 1603 * constructors 1604 */ 1605 1606 //go:linkname ifaceE2I reflect.ifaceE2I 1607 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer) 1608 1609 // typedmemmove copies a value of type t to dst from src. 1610 // 1611 //go:noescape 1612 //go:linkname typedmemmove runtime.typedmemmove 1613 func typedmemmove(t *rtype, dst, src unsafe.Pointer) 1614 1615 // typedmemclr zeros the value at ptr of type t. 1616 // 1617 //go:noescape 1618 //go:linkname typedmemclr reflect.typedmemclr 1619 func typedmemclr(t *rtype, ptr unsafe.Pointer) 1620 1621 //go:linkname unsafe_New reflect.unsafe_New 1622 func unsafe_New(*rtype) unsafe.Pointer 1623 1624 // MakeMapWithSize creates a new map with the specified type 1625 // and initial space for approximately n elements. 1626 func MakeMapWithSize(typ Type, n int) Value { 1627 if typ.Kind() != Map { 1628 panic("reflect.MakeMapWithSize of non-map type") 1629 } 1630 t := typ.(*rtype) 1631 m := makemap(t, n) 1632 return Value{t, m, flag(Map)} 1633 } 1634 1635 // Indirect returns the value that v points to. 1636 // If v is a nil pointer, Indirect returns a zero Value. 1637 // If v is not a pointer, Indirect returns v. 1638 func Indirect(v Value) Value { 1639 if v.Kind() != Pointer { 1640 return v 1641 } 1642 return v.Elem() 1643 } 1644 1645 // ValueOf returns a new Value initialized to the concrete value 1646 // stored in the interface i. ValueOf(nil) returns the zero Value. 1647 func ValueOf(i interface{}) Value { 1648 if i == nil { 1649 return Value{} 1650 } 1651 1652 // TODO: Maybe allow contents of a Value to live on the stack. 1653 // For now we make the contents always escape to the heap. It 1654 // makes life easier in a few places (see chanrecv/mapassign 1655 // comment below). 1656 escapes(i) 1657 1658 return unpackEface(i) 1659 } 1660 1661 // Zero returns a Value representing the zero value for the specified type. 1662 // The result is different from the zero value of the Value struct, 1663 // which represents no value at all. 1664 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. 1665 // The returned value is neither addressable nor settable. 1666 func Zero(typ Type) Value { 1667 if typ == nil { 1668 panic("reflect: Zero(nil)") 1669 } 1670 t := typ.(*rtype) 1671 fl := flag(t.Kind()) 1672 if ifaceIndir(t) { 1673 var p unsafe.Pointer 1674 if t.size <= maxZero { 1675 p = unsafe.Pointer(&zeroVal[0]) 1676 } else { 1677 p = unsafe_New(t) 1678 } 1679 return Value{t, p, fl | flagIndir} 1680 } 1681 return Value{t, nil, fl} 1682 } 1683 1684 // must match declarations in runtime/map.go. 1685 const maxZero = 1024 1686 1687 //go:linkname zeroVal runtime.zeroVal 1688 var zeroVal [maxZero]byte 1689 1690 // New returns a Value representing a pointer to a new zero value 1691 // for the specified type. That is, the returned Value's Type is PointerTo(typ). 1692 func New(typ Type) Value { 1693 if typ == nil { 1694 panic("reflect: New(nil)") 1695 } 1696 t := typ.(*rtype) 1697 pt := t.ptrTo() 1698 if ifaceIndir(pt) { 1699 // This is a pointer to a go:notinheap type. 1700 panic("reflect: New of type that may not be allocated in heap (possibly undefined cgo C type)") 1701 } 1702 ptr := unsafe_New(t) 1703 fl := flag(Pointer) 1704 return Value{pt, ptr, fl} 1705 } 1706 1707 // NewAt returns a Value representing a pointer to a value of the 1708 // specified type, using p as that pointer. 1709 func NewAt(typ Type, p unsafe.Pointer) Value { 1710 fl := flag(Pointer) 1711 t := typ.(*rtype) 1712 return Value{t.ptrTo(), p, fl} 1713 } 1714 1715 // assignTo returns a value v that can be assigned directly to typ. 1716 // It panics if v is not assignable to typ. 1717 // For a conversion to an interface type, target is a suggested scratch space to use. 1718 // target must be initialized memory (or nil). 1719 func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value { 1720 if v.flag&flagMethod != 0 { 1721 panic("method values not supported in reflectlite") 1722 } 1723 1724 seen := map[_typePair]struct{}{} 1725 switch { 1726 case directlyAssignable(dst, v.typ, seen): 1727 // Overwrite type so that they match. 1728 // Same memory layout, so no harm done. 1729 fl := v.flag&(flagAddr|flagIndir) | v.flag.ro() 1730 fl |= flag(dst.Kind()) 1731 return Value{dst, v.ptr, fl} 1732 1733 case implements(dst, v.typ, seen): 1734 if target == nil { 1735 target = unsafe_New(dst) 1736 } 1737 if v.Kind() == Interface && v.IsNil() { 1738 // A nil ReadWriter passed to nil Reader is OK, 1739 // but using ifaceE2I below will panic. 1740 // Avoid the panic by returning a nil dst (e.g., Reader) explicitly. 1741 return Value{dst, nil, flag(Interface)} 1742 } 1743 x := valueInterface(v, false) 1744 if dst.NumMethod() == 0 { 1745 *(*interface{})(target) = x 1746 } else { 1747 ifaceE2I(dst, x, target) 1748 } 1749 return Value{dst, target, flagIndir | flag(Interface)} 1750 } 1751 1752 // Failed. 1753 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String()) 1754 } 1755 1756 // Convert returns the value v converted to type t. 1757 // If the usual Go conversion rules do not allow conversion 1758 // of the value v to type t, or if converting v to type t panics, Convert panics. 1759 func (v Value) Convert(t Type) Value { 1760 if v.flag&flagMethod != 0 { 1761 panic("method values not supported in reflectlite") 1762 } 1763 seen := map[_typePair]struct{}{} 1764 op := convertOp(t.common(), v.typ, false, seen) 1765 if op == nil { 1766 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String()) 1767 } 1768 return op(v, t) 1769 } 1770 1771 func (v Value) ConvertWithInterface(t Type) Value { 1772 if v.flag&flagMethod != 0 { 1773 panic("method values not supported in reflectlite") 1774 } 1775 seen := map[_typePair]struct{}{} 1776 op := convertOp(t.common(), v.typ, true, seen) 1777 if op == nil { 1778 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String()) 1779 } 1780 return op(v, t) 1781 } 1782 1783 // CanConvert reports whether the value v can be converted to type t. 1784 // If v.CanConvert(t) returns true then v.Convert(t) will not panic. 1785 func (v Value) CanConvert(t Type) bool { 1786 vt := v.Type() 1787 if !vt.ConvertibleTo(t) { 1788 return false 1789 } 1790 // Currently the only conversion that is OK in terms of type 1791 // but that can panic depending on the value is converting 1792 // from slice to pointer-to-array. 1793 if vt.Kind() == Slice && t.Kind() == Pointer && t.Elem().Kind() == Array { 1794 n := t.Elem().Len() 1795 if n > v.Len() { 1796 return false 1797 } 1798 } 1799 return true 1800 } 1801 1802 func convertOp(dst, src *rtype, allowInterface bool, seen map[_typePair]struct{}) func(Value, Type) Value { 1803 switch src.Kind() { 1804 case Int, Int8, Int16, Int32, Int64: 1805 switch dst.Kind() { 1806 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 1807 return cvtInt 1808 case Float32, Float64: 1809 return cvtIntFloat 1810 case String: 1811 return cvtIntString 1812 } 1813 1814 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 1815 switch dst.Kind() { 1816 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 1817 return cvtUint 1818 case Float32, Float64: 1819 return cvtUintFloat 1820 case String: 1821 return cvtUintString 1822 } 1823 1824 case Float32, Float64: 1825 switch dst.Kind() { 1826 case Int, Int8, Int16, Int32, Int64: 1827 return cvtFloatInt 1828 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 1829 return cvtFloatUint 1830 case Float32, Float64: 1831 return cvtFloat 1832 } 1833 1834 case Complex64, Complex128: 1835 switch dst.Kind() { 1836 case Complex64, Complex128: 1837 return cvtComplex 1838 } 1839 1840 case String: 1841 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" { 1842 switch dst.Elem().Kind() { 1843 case Uint8: 1844 return cvtStringBytes 1845 case Int32: 1846 return cvtStringRunes 1847 } 1848 } 1849 1850 case Slice: 1851 if dst.Kind() == String && src.Elem().PkgPath() == "" { 1852 switch src.Elem().Kind() { 1853 case Uint8: 1854 return cvtBytesString 1855 case Int32: 1856 return cvtRunesString 1857 } 1858 } 1859 // "x is a slice, T is a pointer-to-array type, 1860 // and the slice and array types have identical element types." 1861 if dst.Kind() == Pointer && dst.Elem().Kind() == Array && src.Elem() == dst.Elem().Elem() { 1862 return cvtSliceArrayPtr 1863 } 1864 1865 case Chan: 1866 if dst.Kind() == Chan && specialChannelAssignability(dst, src, seen) { 1867 return cvtDirect 1868 } 1869 } 1870 1871 // dst and src have same underlying type. 1872 if haveIdenticalUnderlyingType(dst, src, false, allowInterface, seen) { 1873 return cvtDirect 1874 } 1875 1876 // dst and src are non-defined pointer types with same underlying base type. 1877 if dst.Kind() == Pointer && dst.Name() == "" && 1878 src.Kind() == Pointer && src.Name() == "" && 1879 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false, allowInterface, seen) { 1880 return cvtDirect 1881 } 1882 1883 if implements(dst, src, seen) { 1884 if src.Kind() == Interface { 1885 return cvtI2I 1886 } 1887 return cvtT2I 1888 } 1889 1890 return nil 1891 } 1892 1893 func haveIdenticalType(T, V Type, cmpTags, allowInterface bool, seen map[_typePair]struct{}) bool { 1894 if cmpTags { 1895 return T == V 1896 } 1897 1898 if T.Name() != V.Name() || T.Kind() != V.Kind() || T.PkgPath() != V.PkgPath() { 1899 return false 1900 } 1901 1902 return haveIdenticalUnderlyingType(T.common(), V.common(), false, allowInterface, seen) 1903 } 1904 1905 func haveIdenticalUnderlyingType(T, V *rtype, cmpTags, allowInterface bool, seen map[_typePair]struct{}) bool { 1906 if T == V { 1907 return true 1908 } 1909 tp := _typePair{T, V} 1910 if _, ok := seen[tp]; ok { 1911 return true 1912 } 1913 1914 seen[tp] = struct{}{} 1915 1916 kind := T.Kind() 1917 if kind != V.Kind() { 1918 return false 1919 } 1920 1921 // Non-composite types of equal kind have same underlying type 1922 // (the predefined instance of the type). 1923 if Bool <= kind && kind <= Complex128 || kind == String || kind == UnsafePointer { 1924 return true 1925 } 1926 1927 // Composite types. 1928 switch kind { 1929 case Array: 1930 return T.Len() == V.Len() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags, allowInterface, seen) 1931 1932 case Chan: 1933 return V.ChanDir() == T.ChanDir() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags, allowInterface, seen) 1934 1935 case Func: 1936 t := (*funcType)(unsafe.Pointer(T)) 1937 v := (*funcType)(unsafe.Pointer(V)) 1938 if t.outCount != v.outCount || t.inCount != v.inCount { 1939 return false 1940 } 1941 for i := 0; i < t.NumIn(); i++ { 1942 if !haveIdenticalType(t.In(i), v.In(i), cmpTags, allowInterface, seen) { 1943 return false 1944 } 1945 } 1946 for i := 0; i < t.NumOut(); i++ { 1947 if !haveIdenticalType(t.Out(i), v.Out(i), cmpTags, allowInterface, seen) { 1948 return false 1949 } 1950 } 1951 return true 1952 1953 case Interface: 1954 t := (*interfaceType)(unsafe.Pointer(T)) 1955 v := (*interfaceType)(unsafe.Pointer(V)) 1956 if len(t.methods) == 0 && len(v.methods) == 0 { 1957 return true 1958 } 1959 if allowInterface && implements(V, T, seen) { 1960 return true 1961 } 1962 return false 1963 case Map: 1964 return haveIdenticalType(T.Key(), V.Key(), cmpTags, allowInterface, seen) && haveIdenticalType(T.Elem(), V.Elem(), cmpTags, allowInterface, seen) 1965 1966 case Pointer, Slice: 1967 return haveIdenticalType(T.Elem(), V.Elem(), cmpTags, allowInterface, seen) 1968 1969 case Struct: 1970 t := (*structType)(unsafe.Pointer(T)) 1971 v := (*structType)(unsafe.Pointer(V)) 1972 if len(t.fields) != len(v.fields) { 1973 return false 1974 } 1975 if t.pkgPath.name() != v.pkgPath.name() { 1976 return false 1977 } 1978 for i := range t.fields { 1979 tf := &t.fields[i] 1980 vf := &v.fields[i] 1981 if tf.name.name() != vf.name.name() { 1982 return false 1983 } 1984 if !haveIdenticalType(tf.typ, vf.typ, cmpTags, allowInterface, seen) { 1985 return false 1986 } 1987 if cmpTags && tf.name.tag() != vf.name.tag() { 1988 return false 1989 } 1990 if tf.offsetEmbed != vf.offsetEmbed { 1991 return false 1992 } 1993 if tf.embedded() != vf.embedded() { 1994 return false 1995 } 1996 } 1997 return true 1998 } 1999 2000 return false 2001 } 2002 2003 // makeInt returns a Value of type t equal to bits (possibly truncated), 2004 // where t is a signed or unsigned int type. 2005 func makeInt(f flag, bits uint64, t Type) Value { 2006 typ := t.common() 2007 ptr := unsafe_New(typ) 2008 switch typ.size { 2009 case 1: 2010 *(*uint8)(ptr) = uint8(bits) 2011 case 2: 2012 *(*uint16)(ptr) = uint16(bits) 2013 case 4: 2014 *(*uint32)(ptr) = uint32(bits) 2015 case 8: 2016 *(*uint64)(ptr) = bits 2017 } 2018 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2019 } 2020 2021 // makeFloat returns a Value of type t equal to v (possibly truncated to float32), 2022 // where t is a float32 or float64 type. 2023 func makeFloat(f flag, v float64, t Type) Value { 2024 typ := t.common() 2025 ptr := unsafe_New(typ) 2026 switch typ.size { 2027 case 4: 2028 *(*float32)(ptr) = float32(v) 2029 case 8: 2030 *(*float64)(ptr) = v 2031 } 2032 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2033 } 2034 2035 // makeFloat returns a Value of type t equal to v, where t is a float32 type. 2036 func makeFloat32(f flag, v float32, t Type) Value { 2037 typ := t.common() 2038 ptr := unsafe_New(typ) 2039 *(*float32)(ptr) = v 2040 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2041 } 2042 2043 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64), 2044 // where t is a complex64 or complex128 type. 2045 func makeComplex(f flag, v complex128, t Type) Value { 2046 typ := t.common() 2047 ptr := unsafe_New(typ) 2048 switch typ.size { 2049 case 8: 2050 *(*complex64)(ptr) = complex64(v) 2051 case 16: 2052 *(*complex128)(ptr) = v 2053 } 2054 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2055 } 2056 2057 func makeString(f flag, v string, t Type) Value { 2058 ret := New(t).Elem() 2059 ret.SetString(v) 2060 ret.flag = ret.flag&^flagAddr | f 2061 return ret 2062 } 2063 2064 func makeBytes(f flag, v []byte, t Type) Value { 2065 ret := New(t).Elem() 2066 ret.SetBytes(v) 2067 ret.flag = ret.flag&^flagAddr | f 2068 return ret 2069 } 2070 2071 func makeRunes(f flag, v []rune, t Type) Value { 2072 ret := New(t).Elem() 2073 ret.setRunes(v) 2074 ret.flag = ret.flag&^flagAddr | f 2075 return ret 2076 } 2077 2078 // These conversion functions are returned by convertOp 2079 // for classes of conversions. For example, the first function, cvtInt, 2080 // takes interface{} value v of signed int type and returns the value converted 2081 // to type t, where t is interface{} signed or unsigned int type. 2082 2083 // convertOp: intXX -> [u]intXX 2084 func cvtInt(v Value, t Type) Value { 2085 return makeInt(v.flag.ro(), uint64(v.Int()), t) 2086 } 2087 2088 // convertOp: uintXX -> [u]intXX 2089 func cvtUint(v Value, t Type) Value { 2090 return makeInt(v.flag.ro(), v.Uint(), t) 2091 } 2092 2093 // convertOp: floatXX -> intXX 2094 func cvtFloatInt(v Value, t Type) Value { 2095 return makeInt(v.flag.ro(), uint64(int64(v.Float())), t) 2096 } 2097 2098 // convertOp: floatXX -> uintXX 2099 func cvtFloatUint(v Value, t Type) Value { 2100 return makeInt(v.flag.ro(), uint64(v.Float()), t) 2101 } 2102 2103 // convertOp: intXX -> floatXX 2104 func cvtIntFloat(v Value, t Type) Value { 2105 return makeFloat(v.flag.ro(), float64(v.Int()), t) 2106 } 2107 2108 // convertOp: uintXX -> floatXX 2109 func cvtUintFloat(v Value, t Type) Value { 2110 return makeFloat(v.flag.ro(), float64(v.Uint()), t) 2111 } 2112 2113 // convertOp: floatXX -> floatXX 2114 func cvtFloat(v Value, t Type) Value { 2115 if v.Type().Kind() == Float32 && t.Kind() == Float32 { 2116 // Don't do interface{} conversion if both types have underlying type float32. 2117 // This avoids converting to float64 and back, which will 2118 // convert a signaling NaN to a quiet NaN. See issue 36400. 2119 return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t) 2120 } 2121 return makeFloat(v.flag.ro(), v.Float(), t) 2122 } 2123 2124 // convertOp: complexXX -> complexXX 2125 func cvtComplex(v Value, t Type) Value { 2126 return makeComplex(v.flag.ro(), v.Complex(), t) 2127 } 2128 2129 // convertOp: intXX -> string 2130 func cvtIntString(v Value, t Type) Value { 2131 s := "\uFFFD" 2132 if x := v.Int(); int64(rune(x)) == x { 2133 s = string(rune(x)) 2134 } 2135 return makeString(v.flag.ro(), s, t) 2136 } 2137 2138 // convertOp: uintXX -> string 2139 func cvtUintString(v Value, t Type) Value { 2140 s := "\uFFFD" 2141 if x := v.Uint(); uint64(rune(x)) == x { 2142 s = string(rune(x)) 2143 } 2144 return makeString(v.flag.ro(), s, t) 2145 } 2146 2147 // convertOp: []byte -> string 2148 func cvtBytesString(v Value, t Type) Value { 2149 return makeString(v.flag.ro(), string(v.Bytes()), t) 2150 } 2151 2152 // convertOp: string -> []byte 2153 func cvtStringBytes(v Value, t Type) Value { 2154 return makeBytes(v.flag.ro(), []byte(v.String()), t) 2155 } 2156 2157 // convertOp: []rune -> string 2158 func cvtRunesString(v Value, t Type) Value { 2159 return makeString(v.flag.ro(), string(v.runes()), t) 2160 } 2161 2162 // convertOp: string -> []rune 2163 func cvtStringRunes(v Value, t Type) Value { 2164 return makeRunes(v.flag.ro(), []rune(v.String()), t) 2165 } 2166 2167 // convertOp: []T -> *[N]T 2168 func cvtSliceArrayPtr(v Value, t Type) Value { 2169 n := t.Elem().Len() 2170 if n > v.Len() { 2171 panic("reflect: cannot convert slice with length " + itoa.Itoa(v.Len()) + " to pointer to array with length " + itoa.Itoa(n)) 2172 } 2173 h := (*unsafeheader.Slice)(v.ptr) 2174 return Value{t.common(), h.Data, v.flag&^(flagIndir|flagAddr|flagKindMask) | flag(Pointer)} 2175 } 2176 2177 // convertOp: direct copy 2178 func cvtDirect(v Value, typ Type) Value { 2179 f := v.flag 2180 t := typ.common() 2181 ptr := v.ptr 2182 if f&flagAddr != 0 { 2183 // indirect, mutable word - make a copy 2184 c := unsafe_New(t) 2185 typedmemmove(t, c, ptr) 2186 ptr = c 2187 f &^= flagAddr 2188 } 2189 return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f? 2190 } 2191 2192 // convertOp: concrete -> interface 2193 func cvtT2I(v Value, typ Type) Value { 2194 target := unsafe_New(typ.common()) 2195 x := valueInterface(v, false) 2196 if typ.NumMethod() == 0 { 2197 *(*interface{})(target) = x 2198 } else { 2199 ifaceE2I(typ.(*rtype), x, target) 2200 } 2201 return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)} 2202 } 2203 2204 // convertOp: interface -> interface 2205 func cvtI2I(v Value, typ Type) Value { 2206 if v.IsNil() { 2207 ret := Zero(typ) 2208 ret.flag |= v.flag.ro() 2209 return ret 2210 } 2211 return cvtT2I(v.Elem(), typ) 2212 } 2213 2214 //go:linkname chanlen reflect.chanlen 2215 func chanlen(ch unsafe.Pointer) int 2216 2217 //go:noescape 2218 //go:linkname maplen reflect.maplen 2219 func maplen(m unsafe.Pointer) int 2220 2221 //go:linkname makemap reflect.makemap 2222 func makemap(t *rtype, cap int) (m unsafe.Pointer) 2223 2224 //go:noescape 2225 //go:linkname mapaccess reflect.mapaccess 2226 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) 2227 2228 //go:noescape 2229 //go:linkname mapaccess_faststr reflect.mapaccess_faststr 2230 func mapaccess_faststr(t *rtype, m unsafe.Pointer, key string) (val unsafe.Pointer) 2231 2232 //go:noescape 2233 //go:linkname mapassign reflect.mapassign 2234 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer) 2235 2236 //go:noescape 2237 //go:linkname mapassign_faststr reflect.mapassign_faststr 2238 func mapassign_faststr(t *rtype, m unsafe.Pointer, key string, val unsafe.Pointer) 2239 2240 //go:noescape 2241 //go:linkname mapdelete reflect.mapdelete 2242 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer) 2243 2244 //go:noescape 2245 //go:linkname mapdelete_faststr reflect.mapdelete_faststr 2246 func mapdelete_faststr(t *rtype, m unsafe.Pointer, key string) 2247 2248 //go:noescape 2249 //go:linkname mapiterinit reflect.mapiterinit 2250 func mapiterinit(t *rtype, m unsafe.Pointer, it *hiter) 2251 2252 //go:noescape 2253 //go:linkname mapiterkey reflect.mapiterkey 2254 func mapiterkey(it *hiter) (key unsafe.Pointer) 2255 2256 //go:noescape 2257 //go:linkname mapiterelem reflect.mapiterelem 2258 func mapiterelem(it *hiter) (elem unsafe.Pointer) 2259 2260 //go:noescape 2261 //go:linkname mapiternext reflect.mapiternext 2262 func mapiternext(it *hiter) 2263 2264 //go:linkname verifyNotInHeapPtr reflect.verifyNotInHeapPtr 2265 func verifyNotInHeapPtr(p uintptr) bool 2266 2267 // Dummy annotation marking that the value x escapes, 2268 // for use in cases where the reflect code is so clever that 2269 // the compiler cannot follow. 2270 func escapes(x interface{}) { 2271 if dummy.b { 2272 dummy.x = x 2273 } 2274 } 2275 2276 var dummy struct { 2277 b bool 2278 x interface{} 2279 }