value_union.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Copyright 2018 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. package protoreflect
  5. import (
  6. "fmt"
  7. "math"
  8. )
  9. // Value is a union where only one Go type may be set at a time.
  10. // The Value is used to represent all possible values a field may take.
  11. // The following shows which Go type is used to represent each proto Kind:
  12. //
  13. // ╔════════════╤═════════════════════════════════════╗
  14. // ║ Go type │ Protobuf kind ║
  15. // ╠════════════╪═════════════════════════════════════╣
  16. // ║ bool │ BoolKind ║
  17. // ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║
  18. // ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║
  19. // ║ uint32 │ Uint32Kind, Fixed32Kind ║
  20. // ║ uint64 │ Uint64Kind, Fixed64Kind ║
  21. // ║ float32 │ FloatKind ║
  22. // ║ float64 │ DoubleKind ║
  23. // ║ string │ StringKind ║
  24. // ║ []byte │ BytesKind ║
  25. // ║ EnumNumber │ EnumKind ║
  26. // ║ Message │ MessageKind, GroupKind ║
  27. // ╚════════════╧═════════════════════════════════════╝
  28. //
  29. // Multiple protobuf Kinds may be represented by a single Go type if the type
  30. // can losslessly represent the information for the proto kind. For example,
  31. // Int64Kind, Sint64Kind, and Sfixed64Kind are all represented by int64,
  32. // but use different integer encoding methods.
  33. //
  34. // The List or Map types are used if the field cardinality is repeated.
  35. // A field is a List if FieldDescriptor.IsList reports true.
  36. // A field is a Map if FieldDescriptor.IsMap reports true.
  37. //
  38. // Converting to/from a Value and a concrete Go value panics on type mismatch.
  39. // For example, ValueOf("hello").Int() panics because this attempts to
  40. // retrieve an int64 from a string.
  41. //
  42. // List, Map, and Message Values are called "composite" values.
  43. //
  44. // A composite Value may alias (reference) memory at some location,
  45. // such that changes to the Value updates the that location.
  46. // A composite value acquired with a Mutable method, such as Message.Mutable,
  47. // always references the source object.
  48. //
  49. // For example:
  50. // // Append a 0 to a "repeated int32" field.
  51. // // Since the Value returned by Mutable is guaranteed to alias
  52. // // the source message, modifying the Value modifies the message.
  53. // message.Mutable(fieldDesc).(List).Append(protoreflect.ValueOfInt32(0))
  54. //
  55. // // Assign [0] to a "repeated int32" field by creating a new Value,
  56. // // modifying it, and assigning it.
  57. // list := message.NewField(fieldDesc).(List)
  58. // list.Append(protoreflect.ValueOfInt32(0))
  59. // message.Set(fieldDesc, list)
  60. // // ERROR: Since it is not defined whether Set aliases the source,
  61. // // appending to the List here may or may not modify the message.
  62. // list.Append(protoreflect.ValueOfInt32(0))
  63. //
  64. // Some operations, such as Message.Get, may return an "empty, read-only"
  65. // composite Value. Modifying an empty, read-only value panics.
  66. type Value value
  67. // The protoreflect API uses a custom Value union type instead of interface{}
  68. // to keep the future open for performance optimizations. Using an interface{}
  69. // always incurs an allocation for primitives (e.g., int64) since it needs to
  70. // be boxed on the heap (as interfaces can only contain pointers natively).
  71. // Instead, we represent the Value union as a flat struct that internally keeps
  72. // track of which type is set. Using unsafe, the Value union can be reduced
  73. // down to 24B, which is identical in size to a slice.
  74. //
  75. // The latest compiler (Go1.11) currently suffers from some limitations:
  76. // • With inlining, the compiler should be able to statically prove that
  77. // only one of these switch cases are taken and inline one specific case.
  78. // See https://golang.org/issue/22310.
  79. // ValueOf returns a Value initialized with the concrete value stored in v.
  80. // This panics if the type does not match one of the allowed types in the
  81. // Value union.
  82. func ValueOf(v interface{}) Value {
  83. switch v := v.(type) {
  84. case nil:
  85. return Value{}
  86. case bool:
  87. return ValueOfBool(v)
  88. case int32:
  89. return ValueOfInt32(v)
  90. case int64:
  91. return ValueOfInt64(v)
  92. case uint32:
  93. return ValueOfUint32(v)
  94. case uint64:
  95. return ValueOfUint64(v)
  96. case float32:
  97. return ValueOfFloat32(v)
  98. case float64:
  99. return ValueOfFloat64(v)
  100. case string:
  101. return ValueOfString(v)
  102. case []byte:
  103. return ValueOfBytes(v)
  104. case EnumNumber:
  105. return ValueOfEnum(v)
  106. case Message, List, Map:
  107. return valueOfIface(v)
  108. case ProtoMessage:
  109. panic(fmt.Sprintf("invalid proto.Message(%T) type, expected a protoreflect.Message type", v))
  110. default:
  111. panic(fmt.Sprintf("invalid type: %T", v))
  112. }
  113. }
  114. // ValueOfBool returns a new boolean value.
  115. func ValueOfBool(v bool) Value {
  116. if v {
  117. return Value{typ: boolType, num: 1}
  118. } else {
  119. return Value{typ: boolType, num: 0}
  120. }
  121. }
  122. // ValueOfInt32 returns a new int32 value.
  123. func ValueOfInt32(v int32) Value {
  124. return Value{typ: int32Type, num: uint64(v)}
  125. }
  126. // ValueOfInt64 returns a new int64 value.
  127. func ValueOfInt64(v int64) Value {
  128. return Value{typ: int64Type, num: uint64(v)}
  129. }
  130. // ValueOfUint32 returns a new uint32 value.
  131. func ValueOfUint32(v uint32) Value {
  132. return Value{typ: uint32Type, num: uint64(v)}
  133. }
  134. // ValueOfUint64 returns a new uint64 value.
  135. func ValueOfUint64(v uint64) Value {
  136. return Value{typ: uint64Type, num: v}
  137. }
  138. // ValueOfFloat32 returns a new float32 value.
  139. func ValueOfFloat32(v float32) Value {
  140. return Value{typ: float32Type, num: uint64(math.Float64bits(float64(v)))}
  141. }
  142. // ValueOfFloat64 returns a new float64 value.
  143. func ValueOfFloat64(v float64) Value {
  144. return Value{typ: float64Type, num: uint64(math.Float64bits(float64(v)))}
  145. }
  146. // ValueOfString returns a new string value.
  147. func ValueOfString(v string) Value {
  148. return valueOfString(v)
  149. }
  150. // ValueOfBytes returns a new bytes value.
  151. func ValueOfBytes(v []byte) Value {
  152. return valueOfBytes(v[:len(v):len(v)])
  153. }
  154. // ValueOfEnum returns a new enum value.
  155. func ValueOfEnum(v EnumNumber) Value {
  156. return Value{typ: enumType, num: uint64(v)}
  157. }
  158. // ValueOfMessage returns a new Message value.
  159. func ValueOfMessage(v Message) Value {
  160. return valueOfIface(v)
  161. }
  162. // ValueOfList returns a new List value.
  163. func ValueOfList(v List) Value {
  164. return valueOfIface(v)
  165. }
  166. // ValueOfMap returns a new Map value.
  167. func ValueOfMap(v Map) Value {
  168. return valueOfIface(v)
  169. }
  170. // IsValid reports whether v is populated with a value.
  171. func (v Value) IsValid() bool {
  172. return v.typ != nilType
  173. }
  174. // Interface returns v as an interface{}.
  175. //
  176. // Invariant: v == ValueOf(v).Interface()
  177. func (v Value) Interface() interface{} {
  178. switch v.typ {
  179. case nilType:
  180. return nil
  181. case boolType:
  182. return v.Bool()
  183. case int32Type:
  184. return int32(v.Int())
  185. case int64Type:
  186. return int64(v.Int())
  187. case uint32Type:
  188. return uint32(v.Uint())
  189. case uint64Type:
  190. return uint64(v.Uint())
  191. case float32Type:
  192. return float32(v.Float())
  193. case float64Type:
  194. return float64(v.Float())
  195. case stringType:
  196. return v.String()
  197. case bytesType:
  198. return v.Bytes()
  199. case enumType:
  200. return v.Enum()
  201. default:
  202. return v.getIface()
  203. }
  204. }
  205. func (v Value) typeName() string {
  206. switch v.typ {
  207. case nilType:
  208. return "nil"
  209. case boolType:
  210. return "bool"
  211. case int32Type:
  212. return "int32"
  213. case int64Type:
  214. return "int64"
  215. case uint32Type:
  216. return "uint32"
  217. case uint64Type:
  218. return "uint64"
  219. case float32Type:
  220. return "float32"
  221. case float64Type:
  222. return "float64"
  223. case stringType:
  224. return "string"
  225. case bytesType:
  226. return "bytes"
  227. case enumType:
  228. return "enum"
  229. default:
  230. switch v := v.getIface().(type) {
  231. case Message:
  232. return "message"
  233. case List:
  234. return "list"
  235. case Map:
  236. return "map"
  237. default:
  238. return fmt.Sprintf("<unknown: %T>", v)
  239. }
  240. }
  241. }
  242. func (v Value) panicMessage(what string) string {
  243. return fmt.Sprintf("type mismatch: cannot convert %v to %s", v.typeName(), what)
  244. }
  245. // Bool returns v as a bool and panics if the type is not a bool.
  246. func (v Value) Bool() bool {
  247. switch v.typ {
  248. case boolType:
  249. return v.num > 0
  250. default:
  251. panic(v.panicMessage("bool"))
  252. }
  253. }
  254. // Int returns v as a int64 and panics if the type is not a int32 or int64.
  255. func (v Value) Int() int64 {
  256. switch v.typ {
  257. case int32Type, int64Type:
  258. return int64(v.num)
  259. default:
  260. panic(v.panicMessage("int"))
  261. }
  262. }
  263. // Uint returns v as a uint64 and panics if the type is not a uint32 or uint64.
  264. func (v Value) Uint() uint64 {
  265. switch v.typ {
  266. case uint32Type, uint64Type:
  267. return uint64(v.num)
  268. default:
  269. panic(v.panicMessage("uint"))
  270. }
  271. }
  272. // Float returns v as a float64 and panics if the type is not a float32 or float64.
  273. func (v Value) Float() float64 {
  274. switch v.typ {
  275. case float32Type, float64Type:
  276. return math.Float64frombits(uint64(v.num))
  277. default:
  278. panic(v.panicMessage("float"))
  279. }
  280. }
  281. // String returns v as a string. Since this method implements fmt.Stringer,
  282. // this returns the formatted string value for any non-string type.
  283. func (v Value) String() string {
  284. switch v.typ {
  285. case stringType:
  286. return v.getString()
  287. default:
  288. return fmt.Sprint(v.Interface())
  289. }
  290. }
  291. // Bytes returns v as a []byte and panics if the type is not a []byte.
  292. func (v Value) Bytes() []byte {
  293. switch v.typ {
  294. case bytesType:
  295. return v.getBytes()
  296. default:
  297. panic(v.panicMessage("bytes"))
  298. }
  299. }
  300. // Enum returns v as a EnumNumber and panics if the type is not a EnumNumber.
  301. func (v Value) Enum() EnumNumber {
  302. switch v.typ {
  303. case enumType:
  304. return EnumNumber(v.num)
  305. default:
  306. panic(v.panicMessage("enum"))
  307. }
  308. }
  309. // Message returns v as a Message and panics if the type is not a Message.
  310. func (v Value) Message() Message {
  311. switch vi := v.getIface().(type) {
  312. case Message:
  313. return vi
  314. default:
  315. panic(v.panicMessage("message"))
  316. }
  317. }
  318. // List returns v as a List and panics if the type is not a List.
  319. func (v Value) List() List {
  320. switch vi := v.getIface().(type) {
  321. case List:
  322. return vi
  323. default:
  324. panic(v.panicMessage("list"))
  325. }
  326. }
  327. // Map returns v as a Map and panics if the type is not a Map.
  328. func (v Value) Map() Map {
  329. switch vi := v.getIface().(type) {
  330. case Map:
  331. return vi
  332. default:
  333. panic(v.panicMessage("map"))
  334. }
  335. }
  336. // MapKey returns v as a MapKey and panics for invalid MapKey types.
  337. func (v Value) MapKey() MapKey {
  338. switch v.typ {
  339. case boolType, int32Type, int64Type, uint32Type, uint64Type, stringType:
  340. return MapKey(v)
  341. default:
  342. panic(v.panicMessage("map key"))
  343. }
  344. }
  345. // MapKey is used to index maps, where the Go type of the MapKey must match
  346. // the specified key Kind (see MessageDescriptor.IsMapEntry).
  347. // The following shows what Go type is used to represent each proto Kind:
  348. //
  349. // ╔═════════╤═════════════════════════════════════╗
  350. // ║ Go type │ Protobuf kind ║
  351. // ╠═════════╪═════════════════════════════════════╣
  352. // ║ bool │ BoolKind ║
  353. // ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║
  354. // ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║
  355. // ║ uint32 │ Uint32Kind, Fixed32Kind ║
  356. // ║ uint64 │ Uint64Kind, Fixed64Kind ║
  357. // ║ string │ StringKind ║
  358. // ╚═════════╧═════════════════════════════════════╝
  359. //
  360. // A MapKey is constructed and accessed through a Value:
  361. // k := ValueOf("hash").MapKey() // convert string to MapKey
  362. // s := k.String() // convert MapKey to string
  363. //
  364. // The MapKey is a strict subset of valid types used in Value;
  365. // converting a Value to a MapKey with an invalid type panics.
  366. type MapKey value
  367. // IsValid reports whether k is populated with a value.
  368. func (k MapKey) IsValid() bool {
  369. return Value(k).IsValid()
  370. }
  371. // Interface returns k as an interface{}.
  372. func (k MapKey) Interface() interface{} {
  373. return Value(k).Interface()
  374. }
  375. // Bool returns k as a bool and panics if the type is not a bool.
  376. func (k MapKey) Bool() bool {
  377. return Value(k).Bool()
  378. }
  379. // Int returns k as a int64 and panics if the type is not a int32 or int64.
  380. func (k MapKey) Int() int64 {
  381. return Value(k).Int()
  382. }
  383. // Uint returns k as a uint64 and panics if the type is not a uint32 or uint64.
  384. func (k MapKey) Uint() uint64 {
  385. return Value(k).Uint()
  386. }
  387. // String returns k as a string. Since this method implements fmt.Stringer,
  388. // this returns the formatted string value for any non-string type.
  389. func (k MapKey) String() string {
  390. return Value(k).String()
  391. }
  392. // Value returns k as a Value.
  393. func (k MapKey) Value() Value {
  394. return Value(k)
  395. }