1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
|
package reflect
import (
"math"
"unsafe"
)
type valueFlags uint8
// Flags list some useful flags that contain some extra information not
// contained in an interface{} directly, like whether this value was exported at
// all (it is possible to read unexported fields using reflection, but it is not
// possible to modify them).
const (
valueFlagIndirect valueFlags = 1 << iota
valueFlagExported
valueFlagEmbedRO
valueFlagStickyRO
valueFlagRO = valueFlagEmbedRO | valueFlagStickyRO
)
func (v valueFlags) ro() valueFlags {
if v&valueFlagRO != 0 {
return valueFlagStickyRO
}
return 0
}
type Value struct {
typecode *rawType
value unsafe.Pointer
flags valueFlags
}
// isIndirect returns whether the value pointer in this Value is always a
// pointer to the value. If it is false, it is only a pointer to the value if
// the value is bigger than a pointer.
func (v Value) isIndirect() bool {
return v.flags&valueFlagIndirect != 0
}
// isExported returns whether the value represented by this Value could be
// accessed without violating type system constraints. For example, it is not
// set for unexported struct fields.
func (v Value) isExported() bool {
return v.flags&valueFlagExported != 0
}
func (v Value) isRO() bool {
return v.flags&(valueFlagRO) != 0
}
func (v Value) checkRO() {
if v.isRO() {
panic("reflect: value is not settable")
}
}
func Indirect(v Value) Value {
if v.Kind() != Ptr {
return v
}
return v.Elem()
}
//go:linkname composeInterface runtime.composeInterface
func composeInterface(unsafe.Pointer, unsafe.Pointer) interface{}
//go:linkname decomposeInterface runtime.decomposeInterface
func decomposeInterface(i interface{}) (unsafe.Pointer, unsafe.Pointer)
func ValueOf(i interface{}) Value {
typecode, value := decomposeInterface(i)
return Value{
typecode: (*rawType)(typecode),
value: value,
flags: valueFlagExported,
}
}
func (v Value) Interface() interface{} {
if !v.isExported() {
panic("(reflect.Value).Interface: unexported")
}
return valueInterfaceUnsafe(v)
}
// valueInterfaceUnsafe is used by the runtime to hash map keys. It should not
// be subject to the isExported check.
func valueInterfaceUnsafe(v Value) interface{} {
if v.typecode.Kind() == Interface {
// The value itself is an interface. This can happen when getting the
// value of a struct field of interface type, like this:
// type T struct {
// X interface{}
// }
return *(*interface{})(v.value)
}
if v.isIndirect() && v.typecode.Size() <= unsafe.Sizeof(uintptr(0)) {
// Value was indirect but must be put back directly in the interface
// value.
var value uintptr
for j := v.typecode.Size(); j != 0; j-- {
value = (value << 8) | uintptr(*(*uint8)(unsafe.Add(v.value, j-1)))
}
v.value = unsafe.Pointer(value)
}
return composeInterface(unsafe.Pointer(v.typecode), v.value)
}
func (v Value) Type() Type {
return v.typecode
}
// IsZero reports whether v is the zero value for its type.
// It panics if the argument is invalid.
func (v Value) IsZero() bool {
switch v.Kind() {
case Bool:
return !v.Bool()
case Int, Int8, Int16, Int32, Int64:
return v.Int() == 0
case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
return v.Uint() == 0
case Float32, Float64:
return v.Float() == 0
case Complex64, Complex128:
return v.Complex() == 0
case Array:
for i := 0; i < v.Len(); i++ {
if !v.Index(i).IsZero() {
return false
}
}
return true
case Chan, Func, Interface, Map, Pointer, Slice, UnsafePointer:
return v.IsNil()
case String:
return v.Len() == 0
case Struct:
for i := 0; i < v.NumField(); i++ {
if !v.Field(i).IsZero() && v.Type().Field(i).Name != "_" {
return false
}
}
return true
default:
// This should never happens, but will act as a safeguard for
// later, as a default value doesn't makes sense here.
panic(&ValueError{Method: "reflect.Value.IsZero", Kind: v.Kind()})
}
}
// Internal function only, do not use.
//
// RawType returns the raw, underlying type code. It is used in the runtime
// package and needs to be exported for the runtime package to access it.
func (v Value) RawType() *rawType {
return v.typecode
}
func (v Value) Kind() Kind {
return v.typecode.Kind()
}
// IsNil returns whether the value is the nil value. It panics if the value Kind
// is not a channel, map, pointer, function, slice, or interface.
func (v Value) IsNil() bool {
switch v.Kind() {
case Chan, Map, Ptr, UnsafePointer:
return v.pointer() == nil
case Func:
if v.value == nil {
return true
}
fn := (*funcHeader)(v.value)
return fn.Code == nil
case Slice:
if v.value == nil {
return true
}
slice := (*sliceHeader)(v.value)
return slice.data == nil
case Interface:
val := *(*interface{})(v.value)
return val == nil
default:
panic(&ValueError{Method: "IsNil", Kind: v.Kind()})
}
}
// Pointer returns the underlying pointer of the given value for the following
// types: chan, map, pointer, unsafe.Pointer, slice, func.
func (v Value) Pointer() uintptr {
return uintptr(v.UnsafePointer())
}
// UnsafePointer returns the underlying pointer of the given value for the
// following types: chan, map, pointer, unsafe.Pointer, slice, func.
func (v Value) UnsafePointer() unsafe.Pointer {
switch v.Kind() {
case Chan, Map, Ptr, UnsafePointer:
return v.pointer()
case Slice:
slice := (*sliceHeader)(v.value)
return slice.data
case Func:
fn := (*funcHeader)(v.value)
if fn.Context != nil {
return fn.Context
}
return fn.Code
default:
panic(&ValueError{Method: "UnsafePointer", Kind: v.Kind()})
}
}
// pointer returns the underlying pointer represented by v.
// v.Kind() must be Ptr, Map, Chan, or UnsafePointer
func (v Value) pointer() unsafe.Pointer {
if v.isIndirect() {
return *(*unsafe.Pointer)(v.value)
}
return v.value
}
func (v Value) IsValid() bool {
return v.typecode != nil
}
func (v Value) CanInterface() bool {
return v.isExported() && !v.isRO()
}
func (v Value) CanAddr() bool {
return v.flags&(valueFlagIndirect) == valueFlagIndirect
}
func (v Value) Comparable() bool {
k := v.Kind()
switch k {
case Invalid:
return false
case Array:
switch v.Type().Elem().Kind() {
case Interface, Array, Struct:
for i := 0; i < v.Type().Len(); i++ {
if !v.Index(i).Comparable() {
return false
}
}
return true
}
return v.Type().Comparable()
case Interface:
return v.Elem().Comparable()
case Struct:
for i := 0; i < v.NumField(); i++ {
if !v.Field(i).Comparable() {
return false
}
}
return true
default:
return v.Type().Comparable()
}
}
func (v Value) Addr() Value {
if !v.CanAddr() {
panic("reflect.Value.Addr of unaddressable value")
}
// Preserve flagRO instead of using v.flag.ro() so that
// v.Addr().Elem() is equivalent to v (#32772)
flags := v.flags & (valueFlagExported | valueFlagRO)
return Value{
typecode: pointerTo(v.typecode),
value: v.value,
flags: flags,
}
}
func (v Value) UnsafeAddr() uintptr {
return uintptr(v.Addr().UnsafePointer())
}
func (v Value) CanSet() bool {
return v.flags&(valueFlagExported|valueFlagIndirect|valueFlagRO) == valueFlagExported|valueFlagIndirect
}
func (v Value) Bool() bool {
switch v.Kind() {
case Bool:
if v.isIndirect() {
return *((*bool)(v.value))
} else {
return uintptr(v.value) != 0
}
default:
panic(&ValueError{Method: "Bool", Kind: v.Kind()})
}
}
// CanInt reports whether Uint can be used without panicking.
func (v Value) CanInt() bool {
switch v.Kind() {
case Int, Int8, Int16, Int32, Int64:
return true
default:
return false
}
}
func (v Value) Int() int64 {
switch v.Kind() {
case Int:
if v.isIndirect() || unsafe.Sizeof(int(0)) > unsafe.Sizeof(uintptr(0)) {
return int64(*(*int)(v.value))
} else {
return int64(int(uintptr(v.value)))
}
case Int8:
if v.isIndirect() {
return int64(*(*int8)(v.value))
} else {
return int64(int8(uintptr(v.value)))
}
case Int16:
if v.isIndirect() {
return int64(*(*int16)(v.value))
} else {
return int64(int16(uintptr(v.value)))
}
case Int32:
if v.isIndirect() || unsafe.Sizeof(int32(0)) > unsafe.Sizeof(uintptr(0)) {
return int64(*(*int32)(v.value))
} else {
return int64(int32(uintptr(v.value)))
}
case Int64:
if v.isIndirect() || unsafe.Sizeof(int64(0)) > unsafe.Sizeof(uintptr(0)) {
return int64(*(*int64)(v.value))
} else {
return int64(int64(uintptr(v.value)))
}
default:
panic(&ValueError{Method: "Int", Kind: v.Kind()})
}
}
// CanUint reports whether Uint can be used without panicking.
func (v Value) CanUint() bool {
switch v.Kind() {
case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
return true
default:
return false
}
}
func (v Value) Uint() uint64 {
switch v.Kind() {
case Uintptr:
if v.isIndirect() {
return uint64(*(*uintptr)(v.value))
} else {
return uint64(uintptr(v.value))
}
case Uint8:
if v.isIndirect() {
return uint64(*(*uint8)(v.value))
} else {
return uint64(uintptr(v.value))
}
case Uint16:
if v.isIndirect() {
return uint64(*(*uint16)(v.value))
} else {
return uint64(uintptr(v.value))
}
case Uint:
if v.isIndirect() || unsafe.Sizeof(uint(0)) > unsafe.Sizeof(uintptr(0)) {
return uint64(*(*uint)(v.value))
} else {
return uint64(uintptr(v.value))
}
case Uint32:
if v.isIndirect() || unsafe.Sizeof(uint32(0)) > unsafe.Sizeof(uintptr(0)) {
return uint64(*(*uint32)(v.value))
} else {
return uint64(uintptr(v.value))
}
case Uint64:
if v.isIndirect() || unsafe.Sizeof(uint64(0)) > unsafe.Sizeof(uintptr(0)) {
return uint64(*(*uint64)(v.value))
} else {
return uint64(uintptr(v.value))
}
default:
panic(&ValueError{Method: "Uint", Kind: v.Kind()})
}
}
// CanFloat reports whether Float can be used without panicking.
func (v Value) CanFloat() bool {
switch v.Kind() {
case Float32, Float64:
return true
default:
return false
}
}
func (v Value) Float32() float32 {
switch v.Kind() {
case Float32:
if v.isIndirect() || unsafe.Sizeof(float32(0)) > unsafe.Sizeof(uintptr(0)) {
// The float is stored as an external value on systems with 16-bit
// pointers.
return *(*float32)(v.value)
} else {
// The float is directly stored in the interface value on systems
// with 32-bit and 64-bit pointers.
return *(*float32)(unsafe.Pointer(&v.value))
}
case Float64:
return float32(v.Float())
}
panic(&ValueError{Method: "Float", Kind: v.Kind()})
}
func (v Value) Float() float64 {
switch v.Kind() {
case Float32:
if v.isIndirect() || unsafe.Sizeof(float32(0)) > unsafe.Sizeof(uintptr(0)) {
// The float is stored as an external value on systems with 16-bit
// pointers.
return float64(*(*float32)(v.value))
} else {
// The float is directly stored in the interface value on systems
// with 32-bit and 64-bit pointers.
return float64(*(*float32)(unsafe.Pointer(&v.value)))
}
case Float64:
if v.isIndirect() || unsafe.Sizeof(float64(0)) > unsafe.Sizeof(uintptr(0)) {
// For systems with 16-bit and 32-bit pointers.
return *(*float64)(v.value)
} else {
// The float is directly stored in the interface value on systems
// with 64-bit pointers.
return *(*float64)(unsafe.Pointer(&v.value))
}
default:
panic(&ValueError{Method: "Float", Kind: v.Kind()})
}
}
// CanComplex reports whether Complex can be used without panicking.
func (v Value) CanComplex() bool {
switch v.Kind() {
case Complex64, Complex128:
return true
default:
return false
}
}
func (v Value) Complex() complex128 {
switch v.Kind() {
case Complex64:
if v.isIndirect() || unsafe.Sizeof(complex64(0)) > unsafe.Sizeof(uintptr(0)) {
// The complex number is stored as an external value on systems with
// 16-bit and 32-bit pointers.
return complex128(*(*complex64)(v.value))
} else {
// The complex number is directly stored in the interface value on
// systems with 64-bit pointers.
return complex128(*(*complex64)(unsafe.Pointer(&v.value)))
}
case Complex128:
// This is a 128-bit value, which is always stored as an external value.
// It may be stored in the pointer directly on very uncommon
// architectures with 128-bit pointers, however.
return *(*complex128)(v.value)
default:
panic(&ValueError{Method: "Complex", Kind: v.Kind()})
}
}
func (v Value) String() string {
switch v.Kind() {
case String:
// A string value is always bigger than a pointer as it is made of a
// pointer and a length.
return *(*string)(v.value)
default:
// Special case because of the special treatment of .String() in Go.
return "<" + v.typecode.String() + " Value>"
}
}
func (v Value) Bytes() []byte {
switch v.Kind() {
case Slice:
if v.typecode.elem().Kind() != Uint8 {
panic(&ValueError{Method: "Bytes", Kind: v.Kind()})
}
return *(*[]byte)(v.value)
case Array:
v.checkAddressable()
if v.typecode.elem().Kind() != Uint8 {
panic(&ValueError{Method: "Bytes", Kind: v.Kind()})
}
// Small inline arrays are not addressable, so we only have to
// handle addressable arrays which will be stored as pointers
// in v.value
return unsafe.Slice((*byte)(v.value), v.Len())
}
panic(&ValueError{Method: "Bytes", Kind: v.Kind()})
}
func (v Value) Slice(i, j int) Value {
switch v.Kind() {
case Slice:
hdr := *(*sliceHeader)(v.value)
i, j := uintptr(i), uintptr(j)
if j < i || hdr.cap < j {
slicePanic()
}
elemSize := v.typecode.underlying().elem().Size()
hdr.len = j - i
hdr.cap = hdr.cap - i
hdr.data = unsafe.Add(hdr.data, i*elemSize)
return Value{
typecode: v.typecode,
value: unsafe.Pointer(&hdr),
flags: v.flags,
}
case Array:
v.checkAddressable()
buf, length := buflen(v)
i, j := uintptr(i), uintptr(j)
if j < i || length < j {
slicePanic()
}
elemSize := v.typecode.underlying().elem().Size()
var hdr sliceHeader
hdr.len = j - i
hdr.cap = length - i
hdr.data = unsafe.Add(buf, i*elemSize)
sliceType := (*arrayType)(unsafe.Pointer(v.typecode.underlying())).slicePtr
return Value{
typecode: sliceType,
value: unsafe.Pointer(&hdr),
flags: v.flags,
}
case String:
i, j := uintptr(i), uintptr(j)
str := *(*stringHeader)(v.value)
if j < i || str.len < j {
slicePanic()
}
hdr := stringHeader{
data: unsafe.Add(str.data, i),
len: j - i,
}
return Value{
typecode: v.typecode,
value: unsafe.Pointer(&hdr),
flags: v.flags,
}
}
panic(&ValueError{Method: "Slice", Kind: v.Kind()})
}
func (v Value) Slice3(i, j, k int) Value {
switch v.Kind() {
case Slice:
hdr := *(*sliceHeader)(v.value)
i, j, k := uintptr(i), uintptr(j), uintptr(k)
if j < i || k < j || hdr.len < k {
slicePanic()
}
elemSize := v.typecode.underlying().elem().Size()
hdr.len = j - i
hdr.cap = k - i
hdr.data = unsafe.Add(hdr.data, i*elemSize)
return Value{
typecode: v.typecode,
value: unsafe.Pointer(&hdr),
flags: v.flags,
}
case Array:
v.checkAddressable()
buf, length := buflen(v)
i, j, k := uintptr(i), uintptr(j), uintptr(k)
if j < i || k < j || length < k {
slicePanic()
}
elemSize := v.typecode.underlying().elem().Size()
var hdr sliceHeader
hdr.len = j - i
hdr.cap = k - i
hdr.data = unsafe.Add(buf, i*elemSize)
sliceType := (*arrayType)(unsafe.Pointer(v.typecode.underlying())).slicePtr
return Value{
typecode: sliceType,
value: unsafe.Pointer(&hdr),
flags: v.flags,
}
}
panic("unimplemented: (reflect.Value).Slice3()")
}
//go:linkname maplen runtime.hashmapLen
func maplen(p unsafe.Pointer) int
//go:linkname chanlen runtime.chanLen
func chanlen(p unsafe.Pointer) int
// Len returns the length of this value for slices, strings, arrays, channels,
// and maps. For other types, it panics.
func (v Value) Len() int {
switch v.typecode.Kind() {
case Array:
return v.typecode.Len()
case Chan:
return chanlen(v.pointer())
case Map:
return maplen(v.pointer())
case Slice:
return int((*sliceHeader)(v.value).len)
case String:
return int((*stringHeader)(v.value).len)
default:
panic(&ValueError{Method: "Len", Kind: v.Kind()})
}
}
//go:linkname chancap runtime.chanCap
func chancap(p unsafe.Pointer) int
// Cap returns the capacity of this value for arrays, channels and slices.
// For other types, it panics.
func (v Value) Cap() int {
switch v.typecode.Kind() {
case Array:
return v.typecode.Len()
case Chan:
return chancap(v.pointer())
case Slice:
return int((*sliceHeader)(v.value).cap)
default:
panic(&ValueError{Method: "Cap", Kind: v.Kind()})
}
}
//go:linkname mapclear runtime.hashmapClear
func mapclear(p unsafe.Pointer)
// Clear clears the contents of a map or zeros the contents of a slice
//
// It panics if v's Kind is not Map or Slice.
func (v Value) Clear() {
switch v.typecode.Kind() {
case Map:
mapclear(v.pointer())
case Slice:
hdr := (*sliceHeader)(v.value)
elemSize := v.typecode.underlying().elem().Size()
memzero(hdr.data, elemSize*hdr.len)
default:
panic(&ValueError{Method: "Clear", Kind: v.Kind()})
}
}
// NumField returns the number of fields of this struct. It panics for other
// value types.
func (v Value) NumField() int {
return v.typecode.NumField()
}
func (v Value) Elem() Value {
switch v.Kind() {
case Ptr:
ptr := v.pointer()
if ptr == nil {
return Value{}
}
// Don't copy RO flags
flags := (v.flags & (valueFlagIndirect | valueFlagExported)) | valueFlagIndirect
return Value{
typecode: v.typecode.elem(),
value: ptr,
flags: flags,
}
case Interface:
typecode, value := decomposeInterface(*(*interface{})(v.value))
return Value{
typecode: (*rawType)(typecode),
value: value,
flags: v.flags &^ valueFlagIndirect,
}
default:
panic(&ValueError{Method: "Elem", Kind: v.Kind()})
}
}
// Field returns the value of the i'th field of this struct.
func (v Value) Field(i int) Value {
if v.Kind() != Struct {
panic(&ValueError{Method: "Field", Kind: v.Kind()})
}
structField := v.typecode.rawField(i)
// Copy flags but clear EmbedRO; we're not an embedded field anymore
flags := v.flags & ^valueFlagEmbedRO
if structField.PkgPath != "" {
// No PkgPath => not exported.
// Clear exported flag even if the parent was exported.
flags &^= valueFlagExported
// Update the RO flag
if structField.Anonymous {
// Embedded field
flags |= valueFlagEmbedRO
} else {
flags |= valueFlagStickyRO
}
} else {
// Parent field may not have been exported but we are
flags |= valueFlagExported
}
size := v.typecode.Size()
fieldType := structField.Type
fieldSize := fieldType.Size()
if v.isIndirect() || fieldSize > unsafe.Sizeof(uintptr(0)) {
// v.value was already a pointer to the value and it should stay that
// way.
return Value{
flags: flags,
typecode: fieldType,
value: unsafe.Add(v.value, structField.Offset),
}
}
// The fieldSize is smaller than uintptr, which means that the value will
// have to be stored directly in the interface value.
if fieldSize == 0 {
// The struct field is zero sized.
// This is a rare situation, but because it's undefined behavior
// to shift the size of the value (zeroing the value), handle this
// situation explicitly.
return Value{
flags: flags,
typecode: fieldType,
value: unsafe.Pointer(nil),
}
}
if size > unsafe.Sizeof(uintptr(0)) {
// The value was not stored in the interface before but will be
// afterwards, so load the value (from the correct offset) and return
// it.
ptr := unsafe.Add(v.value, structField.Offset)
value := unsafe.Pointer(loadValue(ptr, fieldSize))
return Value{
flags: flags &^ valueFlagIndirect,
typecode: fieldType,
value: value,
}
}
// The value was already stored directly in the interface and it still
// is. Cut out the part of the value that we need.
value := maskAndShift(uintptr(v.value), structField.Offset, fieldSize)
return Value{
flags: flags,
typecode: fieldType,
value: unsafe.Pointer(value),
}
}
var uint8Type = TypeOf(uint8(0)).(*rawType)
func (v Value) Index(i int) Value {
switch v.Kind() {
case Slice:
// Extract an element from the slice.
slice := *(*sliceHeader)(v.value)
if uint(i) >= uint(slice.len) {
panic("reflect: slice index out of range")
}
flags := (v.flags & (valueFlagExported | valueFlagIndirect)) | valueFlagIndirect | v.flags.ro()
elem := Value{
typecode: v.typecode.elem(),
flags: flags,
}
elem.value = unsafe.Add(slice.data, elem.typecode.Size()*uintptr(i)) // pointer to new value
return elem
case String:
// Extract a character from a string.
// A string is never stored directly in the interface, but always as a
// pointer to the string value.
// Keeping valueFlagExported if set, but don't set valueFlagIndirect
// otherwise CanSet will return true for string elements (which is bad,
// strings are read-only).
s := *(*stringHeader)(v.value)
if uint(i) >= uint(s.len) {
panic("reflect: string index out of range")
}
return Value{
typecode: uint8Type,
value: unsafe.Pointer(uintptr(*(*uint8)(unsafe.Add(s.data, i)))),
flags: v.flags & valueFlagExported,
}
case Array:
// Extract an element from the array.
elemType := v.typecode.elem()
elemSize := elemType.Size()
size := v.typecode.Size()
if size == 0 {
// The element size is 0 and/or the length of the array is 0.
return Value{
typecode: v.typecode.elem(),
flags: v.flags,
}
}
if elemSize > unsafe.Sizeof(uintptr(0)) {
// The resulting value doesn't fit in a pointer so must be
// indirect. Also, because size != 0 this implies that the array
// length must be != 0, and thus that the total size is at least
// elemSize.
addr := unsafe.Add(v.value, elemSize*uintptr(i)) // pointer to new value
return Value{
typecode: v.typecode.elem(),
flags: v.flags,
value: addr,
}
}
if size > unsafe.Sizeof(uintptr(0)) || v.isIndirect() {
// The element fits in a pointer, but the array is not stored in the pointer directly.
// Load the value from the pointer.
addr := unsafe.Add(v.value, elemSize*uintptr(i)) // pointer to new value
value := addr
if !v.isIndirect() {
// Use a pointer to the value (don't load the value) if the
// 'indirect' flag is set.
value = unsafe.Pointer(loadValue(addr, elemSize))
}
return Value{
typecode: v.typecode.elem(),
flags: v.flags,
value: value,
}
}
// The value fits in a pointer, so extract it with some shifting and
// masking.
offset := elemSize * uintptr(i)
value := maskAndShift(uintptr(v.value), offset, elemSize)
return Value{
typecode: v.typecode.elem(),
flags: v.flags,
value: unsafe.Pointer(value),
}
default:
panic(&ValueError{Method: "Index", Kind: v.Kind()})
}
}
func (v Value) NumMethod() int {
if v.typecode == nil {
panic(&ValueError{Method: "reflect.Value.NumMethod", Kind: Invalid})
}
return v.typecode.NumMethod()
}
// OverflowFloat reports whether the float64 x cannot be represented by v's type.
// It panics if v's Kind is not Float32 or Float64.
func (v Value) OverflowFloat(x float64) bool {
k := v.Kind()
switch k {
case Float32:
return overflowFloat32(x)
case Float64:
return false
}
panic(&ValueError{Method: "reflect.Value.OverflowFloat", Kind: v.Kind()})
}
func overflowFloat32(x float64) bool {
if x < 0 {
x = -x
}
return math.MaxFloat32 < x && x <= math.MaxFloat64
}
func (v Value) MapKeys() []Value {
if v.Kind() != Map {
panic(&ValueError{Method: "MapKeys", Kind: v.Kind()})
}
// empty map
if v.Len() == 0 {
return nil
}
keys := make([]Value, 0, v.Len())
it := hashmapNewIterator()
k := New(v.typecode.Key())
e := New(v.typecode.Elem())
keyType := v.typecode.key()
keyTypeIsEmptyInterface := keyType.Kind() == Interface && keyType.NumMethod() == 0
shouldUnpackInterface := !keyTypeIsEmptyInterface && keyType.Kind() != String && !keyType.isBinary()
for hashmapNext(v.pointer(), it, k.value, e.value) {
if shouldUnpackInterface {
intf := *(*interface{})(k.value)
v := ValueOf(intf)
keys = append(keys, v)
} else {
keys = append(keys, k.Elem())
}
k = New(v.typecode.Key())
}
return keys
}
//go:linkname hashmapStringGet runtime.hashmapStringGet
func hashmapStringGet(m unsafe.Pointer, key string, value unsafe.Pointer, valueSize uintptr) bool
//go:linkname hashmapBinaryGet runtime.hashmapBinaryGet
func hashmapBinaryGet(m unsafe.Pointer, key, value unsafe.Pointer, valueSize uintptr) bool
//go:linkname hashmapInterfaceGet runtime.hashmapInterfaceGet
func hashmapInterfaceGet(m unsafe.Pointer, key interface{}, value unsafe.Pointer, valueSize uintptr) bool
func (v Value) MapIndex(key Value) Value {
if v.Kind() != Map {
panic(&ValueError{Method: "MapIndex", Kind: v.Kind()})
}
vkey := v.typecode.key()
// compare key type with actual key type of map
if !key.typecode.AssignableTo(vkey) {
// type error?
panic("reflect.Value.MapIndex: incompatible types for key")
}
elemType := v.typecode.Elem()
elem := New(elemType)
if vkey.Kind() == String {
if ok := hashmapStringGet(v.pointer(), *(*string)(key.value), elem.value, elemType.Size()); !ok {
return Value{}
}
return elem.Elem()
} else if vkey.isBinary() {
var keyptr unsafe.Pointer
if key.isIndirect() || key.typecode.Size() > unsafe.Sizeof(uintptr(0)) {
keyptr = key.value
} else {
keyptr = unsafe.Pointer(&key.value)
}
//TODO(dgryski): zero out padding bytes in key, if any
if ok := hashmapBinaryGet(v.pointer(), keyptr, elem.value, elemType.Size()); !ok {
return Value{}
}
return elem.Elem()
} else {
if ok := hashmapInterfaceGet(v.pointer(), key.Interface(), elem.value, elemType.Size()); !ok {
return Value{}
}
return elem.Elem()
}
}
//go:linkname hashmapNewIterator runtime.hashmapNewIterator
func hashmapNewIterator() unsafe.Pointer
//go:linkname hashmapNext runtime.hashmapNext
func hashmapNext(m unsafe.Pointer, it unsafe.Pointer, key, value unsafe.Pointer) bool
func (v Value) MapRange() *MapIter {
if v.Kind() != Map {
panic(&ValueError{Method: "MapRange", Kind: v.Kind()})
}
keyType := v.typecode.key()
keyTypeIsEmptyInterface := keyType.Kind() == Interface && keyType.NumMethod() == 0
shouldUnpackInterface := !keyTypeIsEmptyInterface && keyType.Kind() != String && !keyType.isBinary()
return &MapIter{
m: v,
it: hashmapNewIterator(),
unpackKeyInterface: shouldUnpackInterface,
}
}
type MapIter struct {
m Value
it unsafe.Pointer
key Value
val Value
valid bool
unpackKeyInterface bool
}
func (it *MapIter) Key() Value {
if !it.valid {
panic("reflect.MapIter.Key called on invalid iterator")
}
if it.unpackKeyInterface {
intf := *(*interface{})(it.key.value)
v := ValueOf(intf)
return v
}
return it.key.Elem()
}
func (it *MapIter) Value() Value {
if !it.valid {
panic("reflect.MapIter.Value called on invalid iterator")
}
return it.val.Elem()
}
func (it *MapIter) Next() bool {
it.key = New(it.m.typecode.Key())
it.val = New(it.m.typecode.Elem())
it.valid = hashmapNext(it.m.pointer(), it.it, it.key.value, it.val.value)
return it.valid
}
func (v Value) Set(x Value) {
v.checkAddressable()
v.checkRO()
if !x.typecode.AssignableTo(v.typecode) {
panic("reflect.Value.Set: value of type " + x.typecode.String() + " cannot be assigned to type " + v.typecode.String())
}
if v.typecode.Kind() == Interface && x.typecode.Kind() != Interface {
// move the value of x back into the interface, if possible
if x.isIndirect() && x.typecode.Size() <= unsafe.Sizeof(uintptr(0)) {
x.value = unsafe.Pointer(loadValue(x.value, x.typecode.Size()))
}
intf := composeInterface(unsafe.Pointer(x.typecode), x.value)
x = Value{
typecode: v.typecode,
value: unsafe.Pointer(&intf),
}
}
size := v.typecode.Size()
if size <= unsafe.Sizeof(uintptr(0)) && !x.isIndirect() {
storeValue(v.value, size, uintptr(x.value))
} else {
memcpy(v.value, x.value, size)
}
}
func (v Value) SetZero() {
v.checkAddressable()
v.checkRO()
size := v.typecode.Size()
memzero(v.value, size)
}
func (v Value) SetBool(x bool) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case Bool:
*(*bool)(v.value) = x
default:
panic(&ValueError{Method: "SetBool", Kind: v.Kind()})
}
}
func (v Value) SetInt(x int64) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case Int:
*(*int)(v.value) = int(x)
case Int8:
*(*int8)(v.value) = int8(x)
case Int16:
*(*int16)(v.value) = int16(x)
case Int32:
*(*int32)(v.value) = int32(x)
case Int64:
*(*int64)(v.value) = x
default:
panic(&ValueError{Method: "SetInt", Kind: v.Kind()})
}
}
func (v Value) SetUint(x uint64) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case Uint:
*(*uint)(v.value) = uint(x)
case Uint8:
*(*uint8)(v.value) = uint8(x)
case Uint16:
*(*uint16)(v.value) = uint16(x)
case Uint32:
*(*uint32)(v.value) = uint32(x)
case Uint64:
*(*uint64)(v.value) = x
case Uintptr:
*(*uintptr)(v.value) = uintptr(x)
default:
panic(&ValueError{Method: "SetUint", Kind: v.Kind()})
}
}
func (v Value) SetFloat(x float64) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case Float32:
*(*float32)(v.value) = float32(x)
case Float64:
*(*float64)(v.value) = x
default:
panic(&ValueError{Method: "SetFloat", Kind: v.Kind()})
}
}
func (v Value) SetComplex(x complex128) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case Complex64:
*(*complex64)(v.value) = complex64(x)
case Complex128:
*(*complex128)(v.value) = x
default:
panic(&ValueError{Method: "SetComplex", Kind: v.Kind()})
}
}
func (v Value) SetString(x string) {
v.checkAddressable()
v.checkRO()
switch v.Kind() {
case String:
*(*string)(v.value) = x
default:
panic(&ValueError{Method: "SetString", Kind: v.Kind()})
}
}
func (v Value) SetBytes(x []byte) {
v.checkAddressable()
v.checkRO()
if v.typecode.Kind() != Slice || v.typecode.elem().Kind() != Uint8 {
panic("reflect.Value.SetBytes called on not []byte")
}
// copy the header contents over
*(*[]byte)(v.value) = x
}
func (v Value) SetCap(n int) {
panic("unimplemented: (reflect.Value).SetCap()")
}
func (v Value) SetLen(n int) {
if v.typecode.Kind() != Slice {
panic(&ValueError{Method: "reflect.Value.SetLen", Kind: v.Kind()})
}
v.checkAddressable()
hdr := (*sliceHeader)(v.value)
if int(uintptr(n)) != n || uintptr(n) > hdr.cap {
panic("reflect.Value.SetLen: slice length out of range")
}
hdr.len = uintptr(n)
}
func (v Value) checkAddressable() {
if !v.isIndirect() {
panic("reflect: value is not addressable")
}
}
// OverflowInt reports whether the int64 x cannot be represented by v's type.
// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
func (v Value) OverflowInt(x int64) bool {
switch v.Kind() {
case Int, Int8, Int16, Int32, Int64:
bitSize := v.typecode.Size() * 8
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
return x != trunc
}
panic(&ValueError{Method: "reflect.Value.OverflowInt", Kind: v.Kind()})
}
// OverflowUint reports whether the uint64 x cannot be represented by v's type.
// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
func (v Value) OverflowUint(x uint64) bool {
k := v.Kind()
switch k {
case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
bitSize := v.typecode.Size() * 8
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
return x != trunc
}
panic(&ValueError{Method: "reflect.Value.OverflowUint", Kind: v.Kind()})
}
func (v Value) CanConvert(t Type) bool {
// TODO: Optimize this to not actually perform a conversion
_, ok := convertOp(v, t)
return ok
}
func (v Value) Convert(t Type) Value {
if v, ok := convertOp(v, t); ok {
return v
}
panic("reflect.Value.Convert: value of type " + v.typecode.String() + " cannot be converted to type " + t.String())
}
func convertOp(src Value, typ Type) (Value, bool) {
// Easy check first. Do we even need to do anything?
if src.typecode.underlying() == typ.(*rawType).underlying() {
return Value{
typecode: typ.(*rawType),
value: src.value,
flags: src.flags,
}, true
}
if rtype := typ.(*rawType); rtype.Kind() == Interface && rtype.NumMethod() == 0 {
iface := composeInterface(unsafe.Pointer(src.typecode), src.value)
return Value{
typecode: rtype,
value: unsafe.Pointer(&iface),
flags: valueFlagExported,
}, true
}
switch src.Kind() {
case Int, Int8, Int16, Int32, Int64:
switch rtype := typ.(*rawType); rtype.Kind() {
case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
return cvtInt(src, rtype), true
case Float32, Float64:
return cvtIntFloat(src, rtype), true
case String:
return cvtIntString(src, rtype), true
}
case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
switch rtype := typ.(*rawType); rtype.Kind() {
case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
return cvtUint(src, rtype), true
case Float32, Float64:
return cvtUintFloat(src, rtype), true
case String:
return cvtUintString(src, rtype), true
}
case Float32, Float64:
switch rtype := typ.(*rawType); rtype.Kind() {
case Int, Int8, Int16, Int32, Int64:
return cvtFloatInt(src, rtype), true
case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
return cvtFloatUint(src, rtype), true
case Float32, Float64:
return cvtFloat(src, rtype), true
}
/*
case Complex64, Complex128:
switch src.Kind() {
case Complex64, Complex128:
return cvtComplex
}
*/
case Slice:
switch rtype := typ.(*rawType); rtype.Kind() {
case Array:
if src.typecode.elem() == rtype.elem() && rtype.Len() <= src.Len() {
return Value{
typecode: rtype,
value: (*sliceHeader)(src.value).data,
flags: src.flags | valueFlagIndirect,
}, true
}
case Pointer:
if rtype.Elem().Kind() == Array {
if src.typecode.elem() == rtype.elem().elem() && rtype.elem().Len() <= src.Len() {
return Value{
typecode: rtype,
value: (*sliceHeader)(src.value).data,
flags: src.flags & (valueFlagExported | valueFlagRO),
}, true
}
}
case String:
if !src.typecode.elem().isNamed() {
switch src.Type().Elem().Kind() {
case Uint8:
return cvtBytesString(src, rtype), true
case Int32:
return cvtRunesString(src, rtype), true
}
}
}
case String:
rtype := typ.(*rawType)
if typ.Kind() == Slice && !rtype.elem().isNamed() {
switch typ.Elem().Kind() {
case Uint8:
return cvtStringBytes(src, rtype), true
case Int32:
return cvtStringRunes(src, rtype), true
}
}
}
// TODO(dgryski): Unimplemented:
// Chan
// Non-defined pointers types with same underlying base type
// Interface <-> Type conversions
return Value{}, false
}
func cvtInt(v Value, t *rawType) Value {
return makeInt(v.flags, uint64(v.Int()), t)
}
func cvtUint(v Value, t *rawType) Value {
return makeInt(v.flags, v.Uint(), t)
}
func cvtIntFloat(v Value, t *rawType) Value {
return makeFloat(v.flags, float64(v.Int()), t)
}
func cvtUintFloat(v Value, t *rawType) Value {
return makeFloat(v.flags, float64(v.Uint()), t)
}
func cvtFloatInt(v Value, t *rawType) Value {
return makeInt(v.flags, uint64(int64(v.Float())), t)
}
func cvtFloatUint(v Value, t *rawType) Value {
return makeInt(v.flags, uint64(v.Float()), t)
}
func cvtFloat(v Value, t *rawType) Value {
if v.Type().Kind() == Float32 && t.Kind() == Float32 {
// Don't do any conversion if both types have underlying type float32.
// This avoids converting to float64 and back, which will
// convert a signaling NaN to a quiet NaN. See issue 36400.
return makeFloat32(v.flags, v.Float32(), t)
}
return makeFloat(v.flags, v.Float(), t)
}
//go:linkname stringToBytes runtime.stringToBytes
func stringToBytes(x string) []byte
func cvtStringBytes(v Value, t *rawType) Value {
b := stringToBytes(*(*string)(v.value))
return Value{
typecode: t,
value: unsafe.Pointer(&b),
flags: v.flags,
}
}
//go:linkname stringFromBytes runtime.stringFromBytes
func stringFromBytes(x []byte) string
func cvtBytesString(v Value, t *rawType) Value {
s := stringFromBytes(*(*[]byte)(v.value))
return Value{
typecode: t,
value: unsafe.Pointer(&s),
flags: v.flags,
}
}
func makeInt(flags valueFlags, bits uint64, t *rawType) Value {
size := t.Size()
v := Value{
typecode: t,
flags: flags,
}
ptr := unsafe.Pointer(&v.value)
if size > unsafe.Sizeof(uintptr(0)) {
ptr = alloc(size, nil)
v.value = ptr
}
switch size {
case 1:
*(*uint8)(ptr) = uint8(bits)
case 2:
*(*uint16)(ptr) = uint16(bits)
case 4:
*(*uint32)(ptr) = uint32(bits)
case 8:
*(*uint64)(ptr) = bits
}
return v
}
func makeFloat(flags valueFlags, f float64, t *rawType) Value {
size := t.Size()
v := Value{
typecode: t,
flags: flags,
}
ptr := unsafe.Pointer(&v.value)
if size > unsafe.Sizeof(uintptr(0)) {
ptr = alloc(size, nil)
v.value = ptr
}
switch size {
case 4:
*(*float32)(ptr) = float32(f)
case 8:
*(*float64)(ptr) = f
}
return v
}
func makeFloat32(flags valueFlags, f float32, t *rawType) Value {
v := Value{
typecode: t,
flags: flags,
}
*(*float32)(unsafe.Pointer(&v.value)) = float32(f)
return v
}
func cvtIntString(src Value, t *rawType) Value {
panic("cvtUintString: unimplemented")
}
func cvtUintString(src Value, t *rawType) Value {
panic("cvtUintString: unimplemented")
}
func cvtStringRunes(src Value, t *rawType) Value {
panic("cvsStringRunes: unimplemented")
}
func cvtRunesString(src Value, t *rawType) Value {
panic("cvsRunesString: unimplemented")
}
//go:linkname slicePanic runtime.slicePanic
func slicePanic()
func MakeSlice(typ Type, len, cap int) Value {
if typ.Kind() != Slice {
panic("reflect.MakeSlice of non-slice type")
}
rtype := typ.(*rawType)
ulen := uint(len)
ucap := uint(cap)
maxSize := (^uintptr(0)) / 2
elem := rtype.elem()
elementSize := elem.Size()
if elementSize > 1 {
maxSize /= uintptr(elementSize)
}
if ulen > ucap || ucap > uint(maxSize) {
slicePanic()
}
// This can't overflow because of the above checks.
size := uintptr(ucap) * elementSize
var slice sliceHeader
slice.cap = uintptr(ucap)
slice.len = uintptr(ulen)
layout := elem.gcLayout()
slice.data = alloc(size, layout)
return Value{
typecode: rtype,
value: unsafe.Pointer(&slice),
flags: valueFlagExported,
}
}
var zerobuffer unsafe.Pointer
const zerobufferLen = 32
func init() {
// 32 characters of zero bytes
zerobufferStr := "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
s := (*stringHeader)(unsafe.Pointer(&zerobufferStr))
zerobuffer = s.data
}
func Zero(typ Type) Value {
size := typ.Size()
if size <= unsafe.Sizeof(uintptr(0)) {
return Value{
typecode: typ.(*rawType),
value: nil,
flags: valueFlagExported | valueFlagRO,
}
}
if size <= zerobufferLen {
return Value{
typecode: typ.(*rawType),
value: unsafe.Pointer(zerobuffer),
flags: valueFlagExported | valueFlagRO,
}
}
return Value{
typecode: typ.(*rawType),
value: alloc(size, nil),
flags: valueFlagExported | valueFlagRO,
}
}
// New is the reflect equivalent of the new(T) keyword, returning a pointer to a
// new value of the given type.
func New(typ Type) Value {
return Value{
typecode: pointerTo(typ.(*rawType)),
value: alloc(typ.Size(), nil),
flags: valueFlagExported,
}
}
type funcHeader struct {
Context unsafe.Pointer
Code unsafe.Pointer
}
type SliceHeader struct {
Data uintptr
Len intw
Cap intw
}
// Slice header that matches the underlying structure. Used for when we switch
// to a precise GC, which needs to know exactly where pointers live.
type sliceHeader struct {
data unsafe.Pointer
len uintptr
cap uintptr
}
type StringHeader struct {
Data uintptr
Len intw
}
// Like sliceHeader, this type is used internally to make sure pointer and
// non-pointer fields match those of actual strings.
type stringHeader struct {
data unsafe.Pointer
len uintptr
}
// Verify SliceHeader and StringHeader sizes.
// See https://github.com/tinygo-org/tinygo/pull/4156
// and https://github.com/tinygo-org/tinygo/issues/1284.
var (
_ [unsafe.Sizeof([]byte{})]byte = [unsafe.Sizeof(SliceHeader{})]byte{}
_ [unsafe.Sizeof([]byte{})]byte = [unsafe.Sizeof(sliceHeader{})]byte{}
_ [unsafe.Sizeof("")]byte = [unsafe.Sizeof(StringHeader{})]byte{}
_ [unsafe.Sizeof("")]byte = [unsafe.Sizeof(stringHeader{})]byte{}
)
type ValueError struct {
Method string
Kind Kind
}
func (e *ValueError) Error() string {
if e.Kind == 0 {
return "reflect: call of " + e.Method + " on zero Value"
}
return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
}
//go:linkname memcpy runtime.memcpy
func memcpy(dst, src unsafe.Pointer, size uintptr)
//go:linkname memzero runtime.memzero
func memzero(ptr unsafe.Pointer, size uintptr)
//go:linkname alloc runtime.alloc
func alloc(size uintptr, layout unsafe.Pointer) unsafe.Pointer
//go:linkname sliceAppend runtime.sliceAppend
func sliceAppend(srcBuf, elemsBuf unsafe.Pointer, srcLen, srcCap, elemsLen uintptr, elemSize uintptr) (unsafe.Pointer, uintptr, uintptr)
//go:linkname sliceCopy runtime.sliceCopy
func sliceCopy(dst, src unsafe.Pointer, dstLen, srcLen uintptr, elemSize uintptr) int
// Copy copies the contents of src into dst until either
// dst has been filled or src has been exhausted.
func Copy(dst, src Value) int {
compatibleTypes := false ||
// dst and src are both slices or arrays with equal types
((dst.typecode.Kind() == Slice || dst.typecode.Kind() == Array) &&
(src.typecode.Kind() == Slice || src.typecode.Kind() == Array) &&
(dst.typecode.elem() == src.typecode.elem())) ||
// dst is array or slice of uint8 and src is string
((dst.typecode.Kind() == Slice || dst.typecode.Kind() == Array) &&
dst.typecode.elem().Kind() == Uint8 &&
src.typecode.Kind() == String)
if !compatibleTypes {
panic("Copy: type mismatch: " + dst.typecode.String() + "/" + src.typecode.String())
}
// Can read from an unaddressable array but not write to one.
if dst.typecode.Kind() == Array && !dst.isIndirect() {
panic("reflect.Copy: unaddressable array value")
}
dstbuf, dstlen := buflen(dst)
srcbuf, srclen := buflen(src)
if srclen > 0 {
dst.checkRO()
}
return sliceCopy(dstbuf, srcbuf, dstlen, srclen, dst.typecode.elem().Size())
}
func buflen(v Value) (unsafe.Pointer, uintptr) {
var buf unsafe.Pointer
var len uintptr
switch v.typecode.Kind() {
case Slice:
hdr := (*sliceHeader)(v.value)
buf = hdr.data
len = hdr.len
case Array:
if v.isIndirect() {
buf = v.value
} else {
buf = unsafe.Pointer(&v.value)
}
len = uintptr(v.Len())
case String:
hdr := (*stringHeader)(v.value)
buf = hdr.data
len = hdr.len
default:
// This shouldn't happen
panic("reflect.Copy: not slice or array or string")
}
return buf, len
}
//go:linkname sliceGrow runtime.sliceGrow
func sliceGrow(buf unsafe.Pointer, oldLen, oldCap, newCap, elemSize uintptr) (unsafe.Pointer, uintptr, uintptr)
// extend slice to hold n new elements
func extendSlice(v Value, n int) sliceHeader {
if v.Kind() != Slice {
panic(&ValueError{Method: "extendSlice", Kind: v.Kind()})
}
var old sliceHeader
if v.value != nil {
old = *(*sliceHeader)(v.value)
}
nbuf, nlen, ncap := sliceGrow(old.data, old.len, old.cap, old.len+uintptr(n), v.typecode.elem().Size())
return sliceHeader{
data: nbuf,
len: nlen + uintptr(n),
cap: ncap,
}
}
// Append appends the values x to a slice s and returns the resulting slice.
// As in Go, each x's value must be assignable to the slice's element type.
func Append(v Value, x ...Value) Value {
if v.Kind() != Slice {
panic(&ValueError{Method: "Append", Kind: v.Kind()})
}
oldLen := v.Len()
newslice := extendSlice(v, len(x))
v.flags = valueFlagExported
v.value = (unsafe.Pointer)(&newslice)
for i, xx := range x {
v.Index(oldLen + i).Set(xx)
}
return v
}
// AppendSlice appends a slice t to a slice s and returns the resulting slice.
// The slices s and t must have the same element type.
func AppendSlice(s, t Value) Value {
if s.typecode.Kind() != Slice || t.typecode.Kind() != Slice || s.typecode != t.typecode {
// Not a very helpful error message, but shortened to just one error to
// keep code size down.
panic("reflect.AppendSlice: invalid types")
}
if !s.isExported() || !t.isExported() {
// One of the sides was not exported, so can't access the data.
panic("reflect.AppendSlice: unexported")
}
sSlice := (*sliceHeader)(s.value)
tSlice := (*sliceHeader)(t.value)
elemSize := s.typecode.elem().Size()
ptr, len, cap := sliceAppend(sSlice.data, tSlice.data, sSlice.len, sSlice.cap, tSlice.len, elemSize)
result := &sliceHeader{
data: ptr,
len: len,
cap: cap,
}
return Value{
typecode: s.typecode,
value: unsafe.Pointer(result),
flags: valueFlagExported,
}
}
// Grow increases the slice's capacity, if necessary, to guarantee space for
// another n elements. After Grow(n), at least n elements can be appended
// to the slice without another allocation.
//
// It panics if v's Kind is not a Slice or if n is negative or too large to
// allocate the memory.
func (v Value) Grow(n int) {
v.checkAddressable()
if n < 0 {
panic("reflect.Grow: negative length")
}
if v.Kind() != Slice {
panic(&ValueError{Method: "Grow", Kind: v.Kind()})
}
slice := (*sliceHeader)(v.value)
newslice := extendSlice(v, n)
// Only copy the new data and cap: the len remains unchanged.
slice.data = newslice.data
slice.cap = newslice.cap
}
//go:linkname hashmapStringSet runtime.hashmapStringSet
func hashmapStringSet(m unsafe.Pointer, key string, value unsafe.Pointer)
//go:linkname hashmapBinarySet runtime.hashmapBinarySet
func hashmapBinarySet(m unsafe.Pointer, key, value unsafe.Pointer)
//go:linkname hashmapInterfaceSet runtime.hashmapInterfaceSet
func hashmapInterfaceSet(m unsafe.Pointer, key interface{}, value unsafe.Pointer)
//go:linkname hashmapStringDelete runtime.hashmapStringDelete
func hashmapStringDelete(m unsafe.Pointer, key string)
//go:linkname hashmapBinaryDelete runtime.hashmapBinaryDelete
func hashmapBinaryDelete(m unsafe.Pointer, key unsafe.Pointer)
//go:linkname hashmapInterfaceDelete runtime.hashmapInterfaceDelete
func hashmapInterfaceDelete(m unsafe.Pointer, key interface{})
func (v Value) SetMapIndex(key, elem Value) {
v.checkRO()
if v.Kind() != Map {
panic(&ValueError{Method: "SetMapIndex", Kind: v.Kind()})
}
vkey := v.typecode.key()
// compare key type with actual key type of map
if !key.typecode.AssignableTo(vkey) {
panic("reflect.Value.SetMapIndex: incompatible types for key")
}
// if elem is the zero Value, it means delete
del := elem == Value{}
if !del && !elem.typecode.AssignableTo(v.typecode.elem()) {
panic("reflect.Value.SetMapIndex: incompatible types for value")
}
// make elem an interface if it needs to be converted
if v.typecode.elem().Kind() == Interface && elem.typecode.Kind() != Interface {
intf := composeInterface(unsafe.Pointer(elem.typecode), elem.value)
elem = Value{
typecode: v.typecode.elem(),
value: unsafe.Pointer(&intf),
}
}
if key.Kind() == String {
if del {
hashmapStringDelete(v.pointer(), *(*string)(key.value))
} else {
var elemptr unsafe.Pointer
if elem.isIndirect() || elem.typecode.Size() > unsafe.Sizeof(uintptr(0)) {
elemptr = elem.value
} else {
elemptr = unsafe.Pointer(&elem.value)
}
hashmapStringSet(v.pointer(), *(*string)(key.value), elemptr)
}
} else if key.typecode.isBinary() {
var keyptr unsafe.Pointer
if key.isIndirect() || key.typecode.Size() > unsafe.Sizeof(uintptr(0)) {
keyptr = key.value
} else {
keyptr = unsafe.Pointer(&key.value)
}
if del {
hashmapBinaryDelete(v.pointer(), keyptr)
} else {
var elemptr unsafe.Pointer
if elem.isIndirect() || elem.typecode.Size() > unsafe.Sizeof(uintptr(0)) {
elemptr = elem.value
} else {
elemptr = unsafe.Pointer(&elem.value)
}
hashmapBinarySet(v.pointer(), keyptr, elemptr)
}
} else {
if del {
hashmapInterfaceDelete(v.pointer(), key.Interface())
} else {
var elemptr unsafe.Pointer
if elem.isIndirect() || elem.typecode.Size() > unsafe.Sizeof(uintptr(0)) {
elemptr = elem.value
} else {
elemptr = unsafe.Pointer(&elem.value)
}
hashmapInterfaceSet(v.pointer(), key.Interface(), elemptr)
}
}
}
// FieldByIndex returns the nested field corresponding to index.
func (v Value) FieldByIndex(index []int) Value {
if len(index) == 1 {
return v.Field(index[0])
}
if v.Kind() != Struct {
panic(&ValueError{"FieldByIndex", v.Kind()})
}
for i, x := range index {
if i > 0 {
if v.Kind() == Pointer && v.typecode.elem().Kind() == Struct {
if v.IsNil() {
panic("reflect: indirection through nil pointer to embedded struct")
}
v = v.Elem()
}
}
v = v.Field(x)
}
return v
}
// FieldByIndexErr returns the nested field corresponding to index.
func (v Value) FieldByIndexErr(index []int) (Value, error) {
return Value{}, &ValueError{Method: "FieldByIndexErr"}
}
func (v Value) FieldByName(name string) Value {
if v.Kind() != Struct {
panic(&ValueError{"FieldByName", v.Kind()})
}
if field, ok := v.typecode.FieldByName(name); ok {
return v.FieldByIndex(field.Index)
}
return Value{}
}
func (v Value) FieldByNameFunc(match func(string) bool) Value {
if v.Kind() != Struct {
panic(&ValueError{"FieldByName", v.Kind()})
}
if field, ok := v.typecode.FieldByNameFunc(match); ok {
return v.FieldByIndex(field.Index)
}
return Value{}
}
//go:linkname hashmapMake runtime.hashmapMake
func hashmapMake(keySize, valueSize uintptr, sizeHint uintptr, alg uint8) unsafe.Pointer
// MakeMapWithSize creates a new map with the specified type and initial space
// for approximately n elements.
func MakeMapWithSize(typ Type, n int) Value {
// TODO(dgryski): deduplicate these? runtime and reflect both need them.
const (
hashmapAlgorithmBinary uint8 = iota
hashmapAlgorithmString
hashmapAlgorithmInterface
)
if typ.Kind() != Map {
panic(&ValueError{Method: "MakeMap", Kind: typ.Kind()})
}
if n < 0 {
panic("reflect.MakeMapWithSize: negative size hint")
}
key := typ.Key().(*rawType)
val := typ.Elem().(*rawType)
var alg uint8
if key.Kind() == String {
alg = hashmapAlgorithmString
} else if key.isBinary() {
alg = hashmapAlgorithmBinary
} else {
alg = hashmapAlgorithmInterface
}
m := hashmapMake(key.Size(), val.Size(), uintptr(n), alg)
return Value{
typecode: typ.(*rawType),
value: m,
flags: valueFlagExported,
}
}
type SelectDir int
const (
_ SelectDir = iota
SelectSend // case Chan <- Send
SelectRecv // case <-Chan:
SelectDefault // default
)
type SelectCase struct {
Dir SelectDir // direction of case
Chan Value // channel to use (for send or receive)
Send Value // value to send (for send)
}
func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
panic("unimplemented: reflect.Select")
}
func (v Value) Send(x Value) {
panic("unimplemented: reflect.Value.Send()")
}
func (v Value) Close() {
panic("unimplemented: reflect.Value.Close()")
}
// MakeMap creates a new map with the specified type.
func MakeMap(typ Type) Value {
return MakeMapWithSize(typ, 8)
}
func (v Value) Call(in []Value) []Value {
panic("unimplemented: (reflect.Value).Call()")
}
func (v Value) CallSlice(in []Value) []Value {
panic("unimplemented: (reflect.Value).CallSlice()")
}
func (v Value) Method(i int) Value {
panic("unimplemented: (reflect.Value).Method()")
}
func (v Value) MethodByName(name string) Value {
panic("unimplemented: (reflect.Value).MethodByName()")
}
func (v Value) Recv() (x Value, ok bool) {
panic("unimplemented: (reflect.Value).Recv()")
}
func NewAt(typ Type, p unsafe.Pointer) Value {
panic("unimplemented: reflect.New()")
}
|