marshal.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. // Copyright (c) 2012 The gocql 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 gocql
  5. import (
  6. "bytes"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "math"
  11. "math/big"
  12. "net"
  13. "reflect"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "speter.net/go/exp/math/dec/inf"
  18. )
  19. var (
  20. bigOne = big.NewInt(1)
  21. )
  22. var (
  23. ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config")
  24. )
  25. // Marshaler is the interface implemented by objects that can marshal
  26. // themselves into values understood by Cassandra.
  27. type Marshaler interface {
  28. MarshalCQL(info TypeInfo) ([]byte, error)
  29. }
  30. // Unmarshaler is the interface implemented by objects that can unmarshal
  31. // a Cassandra specific description of themselves.
  32. type Unmarshaler interface {
  33. UnmarshalCQL(info TypeInfo, data []byte) error
  34. }
  35. // Marshal returns the CQL encoding of the value for the Cassandra
  36. // internal type described by the info parameter.
  37. func Marshal(info TypeInfo, value interface{}) ([]byte, error) {
  38. if value == nil {
  39. return nil, nil
  40. }
  41. if info.Version() < protoVersion1 {
  42. panic("protocol version not set")
  43. }
  44. if valueRef := reflect.ValueOf(value); valueRef.Kind() == reflect.Ptr {
  45. if valueRef.IsNil() {
  46. return nil, nil
  47. } else {
  48. return Marshal(info, valueRef.Elem().Interface())
  49. }
  50. }
  51. if v, ok := value.(Marshaler); ok {
  52. return v.MarshalCQL(info)
  53. }
  54. switch info.Type() {
  55. case TypeVarchar, TypeAscii, TypeBlob:
  56. return marshalVarchar(info, value)
  57. case TypeBoolean:
  58. return marshalBool(info, value)
  59. case TypeInt:
  60. return marshalInt(info, value)
  61. case TypeBigInt, TypeCounter:
  62. return marshalBigInt(info, value)
  63. case TypeFloat:
  64. return marshalFloat(info, value)
  65. case TypeDouble:
  66. return marshalDouble(info, value)
  67. case TypeDecimal:
  68. return marshalDecimal(info, value)
  69. case TypeTimestamp:
  70. return marshalTimestamp(info, value)
  71. case TypeList, TypeSet:
  72. return marshalList(info, value)
  73. case TypeMap:
  74. return marshalMap(info, value)
  75. case TypeUUID, TypeTimeUUID:
  76. return marshalUUID(info, value)
  77. case TypeVarint:
  78. return marshalVarint(info, value)
  79. case TypeInet:
  80. return marshalInet(info, value)
  81. case TypeUDT:
  82. return marshalUDT(info, value)
  83. }
  84. // detect protocol 2 UDT
  85. if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
  86. return nil, ErrorUDTUnavailable
  87. }
  88. // TODO(tux21b): add the remaining types
  89. return nil, fmt.Errorf("can not marshal %T into %s", value, info)
  90. }
  91. // Unmarshal parses the CQL encoded data based on the info parameter that
  92. // describes the Cassandra internal data type and stores the result in the
  93. // value pointed by value.
  94. func Unmarshal(info TypeInfo, data []byte, value interface{}) error {
  95. if v, ok := value.(Unmarshaler); ok {
  96. return v.UnmarshalCQL(info, data)
  97. }
  98. if isNullableValue(value) {
  99. return unmarshalNullable(info, data, value)
  100. }
  101. switch info.Type() {
  102. case TypeVarchar, TypeAscii, TypeBlob:
  103. return unmarshalVarchar(info, data, value)
  104. case TypeBoolean:
  105. return unmarshalBool(info, data, value)
  106. case TypeInt:
  107. return unmarshalInt(info, data, value)
  108. case TypeBigInt, TypeCounter:
  109. return unmarshalBigInt(info, data, value)
  110. case TypeVarint:
  111. return unmarshalVarint(info, data, value)
  112. case TypeFloat:
  113. return unmarshalFloat(info, data, value)
  114. case TypeDouble:
  115. return unmarshalDouble(info, data, value)
  116. case TypeDecimal:
  117. return unmarshalDecimal(info, data, value)
  118. case TypeTimestamp:
  119. return unmarshalTimestamp(info, data, value)
  120. case TypeList, TypeSet:
  121. return unmarshalList(info, data, value)
  122. case TypeMap:
  123. return unmarshalMap(info, data, value)
  124. case TypeTimeUUID:
  125. return unmarshalTimeUUID(info, data, value)
  126. case TypeUUID:
  127. return unmarshalUUID(info, data, value)
  128. case TypeInet:
  129. return unmarshalInet(info, data, value)
  130. case TypeTuple:
  131. return unmarshalTuple(info, data, value)
  132. case TypeUDT:
  133. return unmarshalUDT(info, data, value)
  134. }
  135. // detect protocol 2 UDT
  136. if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
  137. return ErrorUDTUnavailable
  138. }
  139. // TODO(tux21b): add the remaining types
  140. return fmt.Errorf("can not unmarshal %s into %T", info, value)
  141. }
  142. func isNullableValue(value interface{}) bool {
  143. v := reflect.ValueOf(value)
  144. return v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Ptr
  145. }
  146. func isNullData(info TypeInfo, data []byte) bool {
  147. return len(data) == 0
  148. }
  149. func unmarshalNullable(info TypeInfo, data []byte, value interface{}) error {
  150. valueRef := reflect.ValueOf(value)
  151. if isNullData(info, data) {
  152. nilValue := reflect.Zero(valueRef.Type().Elem())
  153. valueRef.Elem().Set(nilValue)
  154. return nil
  155. }
  156. newValue := reflect.New(valueRef.Type().Elem().Elem())
  157. valueRef.Elem().Set(newValue)
  158. return Unmarshal(info, data, newValue.Interface())
  159. }
  160. func marshalVarchar(info TypeInfo, value interface{}) ([]byte, error) {
  161. switch v := value.(type) {
  162. case Marshaler:
  163. return v.MarshalCQL(info)
  164. case string:
  165. return []byte(v), nil
  166. case []byte:
  167. return v, nil
  168. }
  169. rv := reflect.ValueOf(value)
  170. t := rv.Type()
  171. k := t.Kind()
  172. switch {
  173. case k == reflect.String:
  174. return []byte(rv.String()), nil
  175. case k == reflect.Slice && t.Elem().Kind() == reflect.Uint8:
  176. return rv.Bytes(), nil
  177. }
  178. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  179. }
  180. func unmarshalVarchar(info TypeInfo, data []byte, value interface{}) error {
  181. switch v := value.(type) {
  182. case Unmarshaler:
  183. return v.UnmarshalCQL(info, data)
  184. case *string:
  185. *v = string(data)
  186. return nil
  187. case *[]byte:
  188. var dataCopy []byte
  189. if data != nil {
  190. dataCopy = make([]byte, len(data))
  191. copy(dataCopy, data)
  192. }
  193. *v = dataCopy
  194. return nil
  195. }
  196. rv := reflect.ValueOf(value)
  197. if rv.Kind() != reflect.Ptr {
  198. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  199. }
  200. rv = rv.Elem()
  201. t := rv.Type()
  202. k := t.Kind()
  203. switch {
  204. case k == reflect.String:
  205. rv.SetString(string(data))
  206. return nil
  207. case k == reflect.Slice && t.Elem().Kind() == reflect.Uint8:
  208. var dataCopy []byte
  209. if data != nil {
  210. dataCopy = make([]byte, len(data))
  211. copy(dataCopy, data)
  212. }
  213. rv.SetBytes(dataCopy)
  214. return nil
  215. }
  216. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  217. }
  218. func marshalInt(info TypeInfo, value interface{}) ([]byte, error) {
  219. switch v := value.(type) {
  220. case Marshaler:
  221. return v.MarshalCQL(info)
  222. case int:
  223. if v > math.MaxInt32 || v < math.MinInt32 {
  224. return nil, marshalErrorf("marshal int: value %d out of range", v)
  225. }
  226. return encInt(int32(v)), nil
  227. case uint:
  228. if v > math.MaxInt32 {
  229. return nil, marshalErrorf("marshal int: value %d out of range", v)
  230. }
  231. return encInt(int32(v)), nil
  232. case int64:
  233. if v > math.MaxInt32 || v < math.MinInt32 {
  234. return nil, marshalErrorf("marshal int: value %d out of range", v)
  235. }
  236. return encInt(int32(v)), nil
  237. case uint64:
  238. if v > math.MaxInt32 {
  239. return nil, marshalErrorf("marshal int: value %d out of range", v)
  240. }
  241. return encInt(int32(v)), nil
  242. case int32:
  243. return encInt(v), nil
  244. case uint32:
  245. if v > math.MaxInt32 {
  246. return nil, marshalErrorf("marshal int: value %d out of range", v)
  247. }
  248. return encInt(int32(v)), nil
  249. case int16:
  250. return encInt(int32(v)), nil
  251. case uint16:
  252. return encInt(int32(v)), nil
  253. case int8:
  254. return encInt(int32(v)), nil
  255. case uint8:
  256. return encInt(int32(v)), nil
  257. case string:
  258. i, err := strconv.ParseInt(value.(string), 10, 32)
  259. if err != nil {
  260. return nil, marshalErrorf("can not marshal string to int: %s", err)
  261. }
  262. return encInt(int32(i)), nil
  263. }
  264. rv := reflect.ValueOf(value)
  265. switch rv.Type().Kind() {
  266. case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
  267. v := rv.Int()
  268. if v > math.MaxInt32 || v < math.MinInt32 {
  269. return nil, marshalErrorf("marshal int: value %d out of range", v)
  270. }
  271. return encInt(int32(v)), nil
  272. case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
  273. v := rv.Uint()
  274. if v > math.MaxInt32 {
  275. return nil, marshalErrorf("marshal int: value %d out of range", v)
  276. }
  277. return encInt(int32(v)), nil
  278. }
  279. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  280. }
  281. func encInt(x int32) []byte {
  282. return []byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
  283. }
  284. func decInt(x []byte) int32 {
  285. if len(x) != 4 {
  286. return 0
  287. }
  288. return int32(x[0])<<24 | int32(x[1])<<16 | int32(x[2])<<8 | int32(x[3])
  289. }
  290. func marshalBigInt(info TypeInfo, value interface{}) ([]byte, error) {
  291. switch v := value.(type) {
  292. case Marshaler:
  293. return v.MarshalCQL(info)
  294. case int:
  295. return encBigInt(int64(v)), nil
  296. case uint:
  297. if uint64(v) > math.MaxInt64 {
  298. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  299. }
  300. return encBigInt(int64(v)), nil
  301. case int64:
  302. return encBigInt(v), nil
  303. case uint64:
  304. if v > math.MaxInt64 {
  305. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  306. }
  307. return encBigInt(int64(v)), nil
  308. case int32:
  309. return encBigInt(int64(v)), nil
  310. case uint32:
  311. return encBigInt(int64(v)), nil
  312. case int16:
  313. return encBigInt(int64(v)), nil
  314. case uint16:
  315. return encBigInt(int64(v)), nil
  316. case int8:
  317. return encBigInt(int64(v)), nil
  318. case uint8:
  319. return encBigInt(int64(v)), nil
  320. case big.Int:
  321. return encBigInt2C(&v), nil
  322. case string:
  323. i, err := strconv.ParseInt(value.(string), 10, 64)
  324. if err != nil {
  325. return nil, marshalErrorf("can not marshal string to bigint: %s", err)
  326. }
  327. return encBigInt(i), nil
  328. }
  329. rv := reflect.ValueOf(value)
  330. switch rv.Type().Kind() {
  331. case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
  332. v := rv.Int()
  333. return encBigInt(v), nil
  334. case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
  335. v := rv.Uint()
  336. if v > math.MaxInt64 {
  337. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  338. }
  339. return encBigInt(int64(v)), nil
  340. }
  341. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  342. }
  343. func encBigInt(x int64) []byte {
  344. return []byte{byte(x >> 56), byte(x >> 48), byte(x >> 40), byte(x >> 32),
  345. byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
  346. }
  347. func bytesToInt64(data []byte) (ret int64) {
  348. for i := range data {
  349. ret |= int64(data[i]) << (8 * uint(len(data)-i-1))
  350. }
  351. return ret
  352. }
  353. func unmarshalBigInt(info TypeInfo, data []byte, value interface{}) error {
  354. return unmarshalIntlike(info, decBigInt(data), data, value)
  355. }
  356. func unmarshalInt(info TypeInfo, data []byte, value interface{}) error {
  357. return unmarshalIntlike(info, int64(decInt(data)), data, value)
  358. }
  359. func unmarshalVarint(info TypeInfo, data []byte, value interface{}) error {
  360. switch value.(type) {
  361. case *big.Int:
  362. return unmarshalIntlike(info, 0, data, value)
  363. }
  364. if len(data) > 8 {
  365. return unmarshalErrorf("unmarshal int: varint value %v out of range for %T (use big.Int)", data, value)
  366. }
  367. int64Val := bytesToInt64(data)
  368. if len(data) < 8 && data[0]&0x80 > 0 {
  369. int64Val -= (1 << uint(len(data)*8))
  370. }
  371. return unmarshalIntlike(info, int64Val, data, value)
  372. }
  373. func marshalVarint(info TypeInfo, value interface{}) ([]byte, error) {
  374. var (
  375. retBytes []byte
  376. err error
  377. )
  378. switch v := value.(type) {
  379. case uint64:
  380. if v > uint64(math.MaxInt64) {
  381. retBytes = make([]byte, 9)
  382. binary.BigEndian.PutUint64(retBytes[1:], v)
  383. } else {
  384. retBytes = make([]byte, 8)
  385. binary.BigEndian.PutUint64(retBytes, v)
  386. }
  387. default:
  388. retBytes, err = marshalBigInt(info, value)
  389. }
  390. if err == nil {
  391. // trim down to most significant byte
  392. i := 0
  393. for ; i < len(retBytes)-1; i++ {
  394. b0 := retBytes[i]
  395. if b0 != 0 && b0 != 0xFF {
  396. break
  397. }
  398. b1 := retBytes[i+1]
  399. if b0 == 0 && b1 != 0 {
  400. if b1&0x80 == 0 {
  401. i++
  402. }
  403. break
  404. }
  405. if b0 == 0xFF && b1 != 0xFF {
  406. if b1&0x80 > 0 {
  407. i++
  408. }
  409. break
  410. }
  411. }
  412. retBytes = retBytes[i:]
  413. }
  414. return retBytes, err
  415. }
  416. func unmarshalIntlike(info TypeInfo, int64Val int64, data []byte, value interface{}) error {
  417. switch v := value.(type) {
  418. case *int:
  419. if ^uint(0) == math.MaxUint32 && (int64Val < math.MinInt32 || int64Val > math.MaxInt32) {
  420. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  421. }
  422. *v = int(int64Val)
  423. return nil
  424. case *uint:
  425. if int64Val < 0 || (^uint(0) == math.MaxUint32 && int64Val > math.MaxUint32) {
  426. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  427. }
  428. *v = uint(int64Val)
  429. return nil
  430. case *int64:
  431. *v = int64Val
  432. return nil
  433. case *uint64:
  434. if int64Val < 0 {
  435. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  436. }
  437. *v = uint64(int64Val)
  438. return nil
  439. case *int32:
  440. if int64Val < math.MinInt32 || int64Val > math.MaxInt32 {
  441. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  442. }
  443. *v = int32(int64Val)
  444. return nil
  445. case *uint32:
  446. if int64Val < 0 || int64Val > math.MaxUint32 {
  447. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  448. }
  449. *v = uint32(int64Val)
  450. return nil
  451. case *int16:
  452. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  453. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  454. }
  455. *v = int16(int64Val)
  456. return nil
  457. case *uint16:
  458. if int64Val < 0 || int64Val > math.MaxUint16 {
  459. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  460. }
  461. *v = uint16(int64Val)
  462. return nil
  463. case *int8:
  464. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  465. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  466. }
  467. *v = int8(int64Val)
  468. return nil
  469. case *uint8:
  470. if int64Val < 0 || int64Val > math.MaxUint8 {
  471. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  472. }
  473. *v = uint8(int64Val)
  474. return nil
  475. case *big.Int:
  476. decBigInt2C(data, v)
  477. return nil
  478. case *string:
  479. *v = strconv.FormatInt(int64Val, 10)
  480. return nil
  481. }
  482. rv := reflect.ValueOf(value)
  483. if rv.Kind() != reflect.Ptr {
  484. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  485. }
  486. rv = rv.Elem()
  487. switch rv.Type().Kind() {
  488. case reflect.Int:
  489. if ^uint(0) == math.MaxUint32 && (int64Val < math.MinInt32 || int64Val > math.MaxInt32) {
  490. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  491. }
  492. rv.SetInt(int64Val)
  493. return nil
  494. case reflect.Int64:
  495. rv.SetInt(int64Val)
  496. return nil
  497. case reflect.Int32:
  498. if int64Val < math.MinInt32 || int64Val > math.MaxInt32 {
  499. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  500. }
  501. rv.SetInt(int64Val)
  502. return nil
  503. case reflect.Int16:
  504. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  505. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  506. }
  507. rv.SetInt(int64Val)
  508. return nil
  509. case reflect.Int8:
  510. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  511. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  512. }
  513. rv.SetInt(int64Val)
  514. return nil
  515. case reflect.Uint:
  516. if int64Val < 0 || (^uint(0) == math.MaxUint32 && int64Val > math.MaxUint32) {
  517. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  518. }
  519. rv.SetUint(uint64(int64Val))
  520. return nil
  521. case reflect.Uint64:
  522. if int64Val < 0 {
  523. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  524. }
  525. rv.SetUint(uint64(int64Val))
  526. return nil
  527. case reflect.Uint32:
  528. if int64Val < 0 || int64Val > math.MaxUint32 {
  529. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  530. }
  531. rv.SetUint(uint64(int64Val))
  532. return nil
  533. case reflect.Uint16:
  534. if int64Val < 0 || int64Val > math.MaxUint16 {
  535. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  536. }
  537. rv.SetUint(uint64(int64Val))
  538. return nil
  539. case reflect.Uint8:
  540. if int64Val < 0 || int64Val > math.MaxUint8 {
  541. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  542. }
  543. rv.SetUint(uint64(int64Val))
  544. return nil
  545. }
  546. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  547. }
  548. func decBigInt(data []byte) int64 {
  549. if len(data) != 8 {
  550. return 0
  551. }
  552. return int64(data[0])<<56 | int64(data[1])<<48 |
  553. int64(data[2])<<40 | int64(data[3])<<32 |
  554. int64(data[4])<<24 | int64(data[5])<<16 |
  555. int64(data[6])<<8 | int64(data[7])
  556. }
  557. func marshalBool(info TypeInfo, value interface{}) ([]byte, error) {
  558. switch v := value.(type) {
  559. case Marshaler:
  560. return v.MarshalCQL(info)
  561. case bool:
  562. return encBool(v), nil
  563. }
  564. rv := reflect.ValueOf(value)
  565. switch rv.Type().Kind() {
  566. case reflect.Bool:
  567. return encBool(rv.Bool()), nil
  568. }
  569. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  570. }
  571. func encBool(v bool) []byte {
  572. if v {
  573. return []byte{1}
  574. }
  575. return []byte{0}
  576. }
  577. func unmarshalBool(info TypeInfo, data []byte, value interface{}) error {
  578. switch v := value.(type) {
  579. case Unmarshaler:
  580. return v.UnmarshalCQL(info, data)
  581. case *bool:
  582. *v = decBool(data)
  583. return nil
  584. }
  585. rv := reflect.ValueOf(value)
  586. if rv.Kind() != reflect.Ptr {
  587. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  588. }
  589. rv = rv.Elem()
  590. switch rv.Type().Kind() {
  591. case reflect.Bool:
  592. rv.SetBool(decBool(data))
  593. return nil
  594. }
  595. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  596. }
  597. func decBool(v []byte) bool {
  598. if len(v) == 0 {
  599. return false
  600. }
  601. return v[0] != 0
  602. }
  603. func marshalFloat(info TypeInfo, value interface{}) ([]byte, error) {
  604. switch v := value.(type) {
  605. case Marshaler:
  606. return v.MarshalCQL(info)
  607. case float32:
  608. return encInt(int32(math.Float32bits(v))), nil
  609. }
  610. rv := reflect.ValueOf(value)
  611. switch rv.Type().Kind() {
  612. case reflect.Float32:
  613. return encInt(int32(math.Float32bits(float32(rv.Float())))), nil
  614. }
  615. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  616. }
  617. func unmarshalFloat(info TypeInfo, data []byte, value interface{}) error {
  618. switch v := value.(type) {
  619. case Unmarshaler:
  620. return v.UnmarshalCQL(info, data)
  621. case *float32:
  622. *v = math.Float32frombits(uint32(decInt(data)))
  623. return nil
  624. }
  625. rv := reflect.ValueOf(value)
  626. if rv.Kind() != reflect.Ptr {
  627. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  628. }
  629. rv = rv.Elem()
  630. switch rv.Type().Kind() {
  631. case reflect.Float32:
  632. rv.SetFloat(float64(math.Float32frombits(uint32(decInt(data)))))
  633. return nil
  634. }
  635. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  636. }
  637. func marshalDouble(info TypeInfo, value interface{}) ([]byte, error) {
  638. switch v := value.(type) {
  639. case Marshaler:
  640. return v.MarshalCQL(info)
  641. case float64:
  642. return encBigInt(int64(math.Float64bits(v))), nil
  643. }
  644. rv := reflect.ValueOf(value)
  645. switch rv.Type().Kind() {
  646. case reflect.Float64:
  647. return encBigInt(int64(math.Float64bits(rv.Float()))), nil
  648. }
  649. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  650. }
  651. func unmarshalDouble(info TypeInfo, data []byte, value interface{}) error {
  652. switch v := value.(type) {
  653. case Unmarshaler:
  654. return v.UnmarshalCQL(info, data)
  655. case *float64:
  656. *v = math.Float64frombits(uint64(decBigInt(data)))
  657. return nil
  658. }
  659. rv := reflect.ValueOf(value)
  660. if rv.Kind() != reflect.Ptr {
  661. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  662. }
  663. rv = rv.Elem()
  664. switch rv.Type().Kind() {
  665. case reflect.Float64:
  666. rv.SetFloat(math.Float64frombits(uint64(decBigInt(data))))
  667. return nil
  668. }
  669. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  670. }
  671. func marshalDecimal(info TypeInfo, value interface{}) ([]byte, error) {
  672. switch v := value.(type) {
  673. case Marshaler:
  674. return v.MarshalCQL(info)
  675. case inf.Dec:
  676. unscaled := encBigInt2C(v.UnscaledBig())
  677. if unscaled == nil {
  678. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  679. }
  680. buf := make([]byte, 4+len(unscaled))
  681. copy(buf[0:4], encInt(int32(v.Scale())))
  682. copy(buf[4:], unscaled)
  683. return buf, nil
  684. }
  685. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  686. }
  687. func unmarshalDecimal(info TypeInfo, data []byte, value interface{}) error {
  688. switch v := value.(type) {
  689. case Unmarshaler:
  690. return v.UnmarshalCQL(info, data)
  691. case *inf.Dec:
  692. scale := decInt(data[0:4])
  693. unscaled := decBigInt2C(data[4:], nil)
  694. *v = *inf.NewDecBig(unscaled, inf.Scale(scale))
  695. return nil
  696. }
  697. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  698. }
  699. // decBigInt2C sets the value of n to the big-endian two's complement
  700. // value stored in the given data. If data[0]&80 != 0, the number
  701. // is negative. If data is empty, the result will be 0.
  702. func decBigInt2C(data []byte, n *big.Int) *big.Int {
  703. if n == nil {
  704. n = new(big.Int)
  705. }
  706. n.SetBytes(data)
  707. if len(data) > 0 && data[0]&0x80 > 0 {
  708. n.Sub(n, new(big.Int).Lsh(bigOne, uint(len(data))*8))
  709. }
  710. return n
  711. }
  712. // encBigInt2C returns the big-endian two's complement
  713. // form of n.
  714. func encBigInt2C(n *big.Int) []byte {
  715. switch n.Sign() {
  716. case 0:
  717. return []byte{0}
  718. case 1:
  719. b := n.Bytes()
  720. if b[0]&0x80 > 0 {
  721. b = append([]byte{0}, b...)
  722. }
  723. return b
  724. case -1:
  725. length := uint(n.BitLen()/8+1) * 8
  726. b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
  727. // When the most significant bit is on a byte
  728. // boundary, we can get some extra significant
  729. // bits, so strip them off when that happens.
  730. if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
  731. b = b[1:]
  732. }
  733. return b
  734. }
  735. return nil
  736. }
  737. func marshalTimestamp(info TypeInfo, value interface{}) ([]byte, error) {
  738. switch v := value.(type) {
  739. case Marshaler:
  740. return v.MarshalCQL(info)
  741. case int64:
  742. return encBigInt(v), nil
  743. case time.Time:
  744. x := v.UnixNano() / int64(1000000)
  745. return encBigInt(x), nil
  746. }
  747. rv := reflect.ValueOf(value)
  748. switch rv.Type().Kind() {
  749. case reflect.Int64:
  750. return encBigInt(rv.Int()), nil
  751. }
  752. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  753. }
  754. func unmarshalTimestamp(info TypeInfo, data []byte, value interface{}) error {
  755. switch v := value.(type) {
  756. case Unmarshaler:
  757. return v.UnmarshalCQL(info, data)
  758. case *int64:
  759. *v = decBigInt(data)
  760. return nil
  761. case *time.Time:
  762. if len(data) == 0 {
  763. return nil
  764. }
  765. x := decBigInt(data)
  766. sec := x / 1000
  767. nsec := (x - sec*1000) * 1000000
  768. *v = time.Unix(sec, nsec).In(time.UTC)
  769. return nil
  770. }
  771. rv := reflect.ValueOf(value)
  772. if rv.Kind() != reflect.Ptr {
  773. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  774. }
  775. rv = rv.Elem()
  776. switch rv.Type().Kind() {
  777. case reflect.Int64:
  778. rv.SetInt(decBigInt(data))
  779. return nil
  780. }
  781. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  782. }
  783. func writeCollectionSize(info CollectionType, n int, buf *bytes.Buffer) error {
  784. if info.proto > protoVersion2 {
  785. if n > math.MaxInt32 {
  786. return marshalErrorf("marshal: collection too large")
  787. }
  788. buf.WriteByte(byte(n >> 24))
  789. buf.WriteByte(byte(n >> 16))
  790. buf.WriteByte(byte(n >> 8))
  791. buf.WriteByte(byte(n))
  792. } else {
  793. if n > math.MaxUint16 {
  794. return marshalErrorf("marshal: collection too large")
  795. }
  796. buf.WriteByte(byte(n >> 8))
  797. buf.WriteByte(byte(n))
  798. }
  799. return nil
  800. }
  801. func marshalList(info TypeInfo, value interface{}) ([]byte, error) {
  802. listInfo, ok := info.(CollectionType)
  803. if !ok {
  804. return nil, marshalErrorf("marshal: can not marshal non collection type into list")
  805. }
  806. rv := reflect.ValueOf(value)
  807. t := rv.Type()
  808. k := t.Kind()
  809. switch k {
  810. case reflect.Slice, reflect.Array:
  811. if k == reflect.Slice && rv.IsNil() {
  812. return nil, nil
  813. }
  814. buf := &bytes.Buffer{}
  815. n := rv.Len()
  816. if err := writeCollectionSize(listInfo, n, buf); err != nil {
  817. return nil, err
  818. }
  819. for i := 0; i < n; i++ {
  820. item, err := Marshal(listInfo.Elem, rv.Index(i).Interface())
  821. if err != nil {
  822. return nil, err
  823. }
  824. if err := writeCollectionSize(listInfo, len(item), buf); err != nil {
  825. return nil, err
  826. }
  827. buf.Write(item)
  828. }
  829. return buf.Bytes(), nil
  830. case reflect.Map:
  831. elem := t.Elem()
  832. if elem.Kind() == reflect.Struct && elem.NumField() == 0 {
  833. rkeys := rv.MapKeys()
  834. keys := make([]interface{}, len(rkeys))
  835. for i := 0; i < len(keys); i++ {
  836. keys[i] = rkeys[i].Interface()
  837. }
  838. return marshalList(listInfo, keys)
  839. }
  840. }
  841. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  842. }
  843. func readCollectionSize(info CollectionType, data []byte) (size, read int) {
  844. if info.proto > protoVersion2 {
  845. size = int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  846. read = 4
  847. } else {
  848. size = int(data[0])<<8 | int(data[1])
  849. read = 2
  850. }
  851. return
  852. }
  853. func unmarshalList(info TypeInfo, data []byte, value interface{}) error {
  854. listInfo, ok := info.(CollectionType)
  855. if !ok {
  856. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into list")
  857. }
  858. rv := reflect.ValueOf(value)
  859. if rv.Kind() != reflect.Ptr {
  860. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  861. }
  862. rv = rv.Elem()
  863. t := rv.Type()
  864. k := t.Kind()
  865. switch k {
  866. case reflect.Slice, reflect.Array:
  867. if data == nil {
  868. if k == reflect.Array {
  869. return unmarshalErrorf("unmarshal list: can not store nil in array value")
  870. }
  871. rv.Set(reflect.Zero(t))
  872. return nil
  873. }
  874. if len(data) < 2 {
  875. return unmarshalErrorf("unmarshal list: unexpected eof")
  876. }
  877. n, p := readCollectionSize(listInfo, data)
  878. data = data[p:]
  879. if k == reflect.Array {
  880. if rv.Len() != n {
  881. return unmarshalErrorf("unmarshal list: array with wrong size")
  882. }
  883. } else {
  884. rv.Set(reflect.MakeSlice(t, n, n))
  885. }
  886. for i := 0; i < n; i++ {
  887. if len(data) < 2 {
  888. return unmarshalErrorf("unmarshal list: unexpected eof")
  889. }
  890. m, p := readCollectionSize(listInfo, data)
  891. data = data[p:]
  892. if err := Unmarshal(listInfo.Elem, data[:m], rv.Index(i).Addr().Interface()); err != nil {
  893. return err
  894. }
  895. data = data[m:]
  896. }
  897. return nil
  898. }
  899. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  900. }
  901. func marshalMap(info TypeInfo, value interface{}) ([]byte, error) {
  902. mapInfo, ok := info.(CollectionType)
  903. if !ok {
  904. return nil, marshalErrorf("marshal: can not marshal none collection type into map")
  905. }
  906. rv := reflect.ValueOf(value)
  907. t := rv.Type()
  908. if t.Kind() != reflect.Map {
  909. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  910. }
  911. if rv.IsNil() {
  912. return nil, nil
  913. }
  914. buf := &bytes.Buffer{}
  915. n := rv.Len()
  916. if err := writeCollectionSize(mapInfo, n, buf); err != nil {
  917. return nil, err
  918. }
  919. keys := rv.MapKeys()
  920. for _, key := range keys {
  921. item, err := Marshal(mapInfo.Key, key.Interface())
  922. if err != nil {
  923. return nil, err
  924. }
  925. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  926. return nil, err
  927. }
  928. buf.Write(item)
  929. item, err = Marshal(mapInfo.Elem, rv.MapIndex(key).Interface())
  930. if err != nil {
  931. return nil, err
  932. }
  933. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  934. return nil, err
  935. }
  936. buf.Write(item)
  937. }
  938. return buf.Bytes(), nil
  939. }
  940. func unmarshalMap(info TypeInfo, data []byte, value interface{}) error {
  941. mapInfo, ok := info.(CollectionType)
  942. if !ok {
  943. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into map")
  944. }
  945. rv := reflect.ValueOf(value)
  946. if rv.Kind() != reflect.Ptr {
  947. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  948. }
  949. rv = rv.Elem()
  950. t := rv.Type()
  951. if t.Kind() != reflect.Map {
  952. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  953. }
  954. if data == nil {
  955. rv.Set(reflect.Zero(t))
  956. return nil
  957. }
  958. rv.Set(reflect.MakeMap(t))
  959. if len(data) < 2 {
  960. return unmarshalErrorf("unmarshal map: unexpected eof")
  961. }
  962. n, p := readCollectionSize(mapInfo, data)
  963. data = data[p:]
  964. for i := 0; i < n; i++ {
  965. if len(data) < 2 {
  966. return unmarshalErrorf("unmarshal list: unexpected eof")
  967. }
  968. m, p := readCollectionSize(mapInfo, data)
  969. data = data[p:]
  970. key := reflect.New(t.Key())
  971. if err := Unmarshal(mapInfo.Key, data[:m], key.Interface()); err != nil {
  972. return err
  973. }
  974. data = data[m:]
  975. m, p = readCollectionSize(mapInfo, data)
  976. data = data[p:]
  977. val := reflect.New(t.Elem())
  978. if err := Unmarshal(mapInfo.Elem, data[:m], val.Interface()); err != nil {
  979. return err
  980. }
  981. data = data[m:]
  982. rv.SetMapIndex(key.Elem(), val.Elem())
  983. }
  984. return nil
  985. }
  986. func marshalUUID(info TypeInfo, value interface{}) ([]byte, error) {
  987. switch val := value.(type) {
  988. case UUID:
  989. return val.Bytes(), nil
  990. case []byte:
  991. if len(val) == 16 {
  992. return val, nil
  993. }
  994. case string:
  995. b, err := ParseUUID(val)
  996. if err != nil {
  997. return nil, err
  998. }
  999. return b[:], nil
  1000. }
  1001. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1002. }
  1003. func unmarshalUUID(info TypeInfo, data []byte, value interface{}) error {
  1004. if data == nil || len(data) == 0 {
  1005. switch v := value.(type) {
  1006. case *string:
  1007. *v = ""
  1008. case *[]byte:
  1009. *v = nil
  1010. case *UUID:
  1011. *v = UUID{}
  1012. default:
  1013. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1014. }
  1015. return nil
  1016. }
  1017. u, err := UUIDFromBytes(data)
  1018. if err != nil {
  1019. return unmarshalErrorf("Unable to parse UUID: %s", err)
  1020. }
  1021. switch v := value.(type) {
  1022. case *string:
  1023. *v = u.String()
  1024. return nil
  1025. case *[]byte:
  1026. *v = u[:]
  1027. return nil
  1028. case *UUID:
  1029. *v = u
  1030. return nil
  1031. }
  1032. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1033. }
  1034. func unmarshalTimeUUID(info TypeInfo, data []byte, value interface{}) error {
  1035. switch v := value.(type) {
  1036. case Unmarshaler:
  1037. return v.UnmarshalCQL(info, data)
  1038. case *time.Time:
  1039. id, err := UUIDFromBytes(data)
  1040. if err != nil {
  1041. return err
  1042. } else if id.Version() != 1 {
  1043. return unmarshalErrorf("invalid timeuuid")
  1044. }
  1045. *v = id.Time()
  1046. return nil
  1047. default:
  1048. return unmarshalUUID(info, data, value)
  1049. }
  1050. }
  1051. func marshalInet(info TypeInfo, value interface{}) ([]byte, error) {
  1052. // we return either the 4 or 16 byte representation of an
  1053. // ip address here otherwise the db value will be prefixed
  1054. // with the remaining byte values e.g. ::ffff:127.0.0.1 and not 127.0.0.1
  1055. switch val := value.(type) {
  1056. case net.IP:
  1057. t := val.To4()
  1058. if t == nil {
  1059. return val.To16(), nil
  1060. }
  1061. return t, nil
  1062. case string:
  1063. b := net.ParseIP(val)
  1064. if b != nil {
  1065. t := b.To4()
  1066. if t == nil {
  1067. return b.To16(), nil
  1068. }
  1069. return t, nil
  1070. }
  1071. return nil, marshalErrorf("cannot marshal. invalid ip string %s", val)
  1072. }
  1073. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1074. }
  1075. func unmarshalInet(info TypeInfo, data []byte, value interface{}) error {
  1076. switch v := value.(type) {
  1077. case Unmarshaler:
  1078. return v.UnmarshalCQL(info, data)
  1079. case *net.IP:
  1080. ip := net.IP(data)
  1081. if v4 := ip.To4(); v4 != nil {
  1082. *v = v4
  1083. return nil
  1084. }
  1085. *v = ip
  1086. return nil
  1087. case *string:
  1088. if len(data) == 0 {
  1089. *v = ""
  1090. return nil
  1091. }
  1092. ip := net.IP(data)
  1093. if v4 := ip.To4(); v4 != nil {
  1094. *v = v4.String()
  1095. return nil
  1096. }
  1097. *v = ip.String()
  1098. return nil
  1099. }
  1100. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1101. }
  1102. // currently only support unmarshal into a list of values, this makes it possible
  1103. // to support tuples without changing the query API. In the future this can be extend
  1104. // to allow unmarshalling into custom tuple types.
  1105. func unmarshalTuple(info TypeInfo, data []byte, value interface{}) error {
  1106. if v, ok := value.(Unmarshaler); ok {
  1107. return v.UnmarshalCQL(info, data)
  1108. }
  1109. tuple := info.(TupleTypeInfo)
  1110. switch v := value.(type) {
  1111. case []interface{}:
  1112. for i, elem := range tuple.Elems {
  1113. // each element inside data is a [bytes]
  1114. size := readInt(data)
  1115. data = data[4:]
  1116. err := Unmarshal(elem, data[:size], v[i])
  1117. if err != nil {
  1118. return err
  1119. }
  1120. data = data[size:]
  1121. }
  1122. return nil
  1123. }
  1124. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1125. }
  1126. // UDTMarshaler is an interface which should be implemented by users wishing to
  1127. // handle encoding UDT types to sent to Cassandra. Note: due to current implentations
  1128. // methods defined for this interface must be value receivers not pointer receivers.
  1129. type UDTMarshaler interface {
  1130. // MarshalUDT will be called for each field in the the UDT returned by Cassandra,
  1131. // the implementor should marshal the type to return by for example calling
  1132. // Marshal.
  1133. MarshalUDT(name string, info TypeInfo) ([]byte, error)
  1134. }
  1135. // UDTUnmarshaler should be implemented by users wanting to implement custom
  1136. // UDT unmarshaling.
  1137. type UDTUnmarshaler interface {
  1138. // UnmarshalUDT will be called for each field in the UDT return by Cassandra,
  1139. // the implementor should unmarshal the data into the value of their chosing,
  1140. // for example by calling Unmarshal.
  1141. UnmarshalUDT(name string, info TypeInfo, data []byte) error
  1142. }
  1143. func marshalUDT(info TypeInfo, value interface{}) ([]byte, error) {
  1144. udt := info.(UDTTypeInfo)
  1145. switch v := value.(type) {
  1146. case Marshaler:
  1147. return v.MarshalCQL(info)
  1148. case UDTMarshaler:
  1149. var buf []byte
  1150. for _, e := range udt.Elements {
  1151. data, err := v.MarshalUDT(e.Name, e.Type)
  1152. if err != nil {
  1153. return nil, err
  1154. }
  1155. n := len(data)
  1156. buf = append(buf, byte(n>>24),
  1157. byte(n>>16),
  1158. byte(n>>8),
  1159. byte(n))
  1160. buf = append(buf, data...)
  1161. }
  1162. return buf, nil
  1163. case map[string]interface{}:
  1164. var buf []byte
  1165. for _, e := range udt.Elements {
  1166. val, ok := v[e.Name]
  1167. if !ok {
  1168. return nil, marshalErrorf("missing UDT field in map: %s", e.Name)
  1169. }
  1170. data, err := Marshal(e.Type, val)
  1171. if err != nil {
  1172. return nil, err
  1173. }
  1174. n := len(data)
  1175. buf = append(buf, byte(n>>24),
  1176. byte(n>>16),
  1177. byte(n>>8),
  1178. byte(n))
  1179. buf = append(buf, data...)
  1180. }
  1181. return buf, nil
  1182. }
  1183. k := reflect.ValueOf(value)
  1184. if k.Kind() == reflect.Ptr {
  1185. if k.IsNil() {
  1186. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1187. }
  1188. k = k.Elem()
  1189. }
  1190. if k.Kind() != reflect.Struct || !k.IsValid() {
  1191. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1192. }
  1193. fields := make(map[string]reflect.Value)
  1194. t := reflect.TypeOf(value)
  1195. for i := 0; i < t.NumField(); i++ {
  1196. sf := t.Field(i)
  1197. if tag := sf.Tag.Get("cql"); tag != "" {
  1198. fields[tag] = k.Field(i)
  1199. }
  1200. }
  1201. var buf []byte
  1202. for _, e := range udt.Elements {
  1203. f, ok := fields[e.Name]
  1204. if !ok {
  1205. f = k.FieldByName(e.Name)
  1206. }
  1207. if !f.IsValid() {
  1208. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1209. } else if f.Kind() == reflect.Ptr {
  1210. f = f.Elem()
  1211. }
  1212. data, err := Marshal(e.Type, f.Interface())
  1213. if err != nil {
  1214. return nil, err
  1215. }
  1216. n := len(data)
  1217. buf = append(buf, byte(n>>24),
  1218. byte(n>>16),
  1219. byte(n>>8),
  1220. byte(n))
  1221. buf = append(buf, data...)
  1222. }
  1223. return buf, nil
  1224. }
  1225. func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
  1226. switch v := value.(type) {
  1227. case Unmarshaler:
  1228. return v.UnmarshalCQL(info, data)
  1229. case UDTUnmarshaler:
  1230. udt := info.(UDTTypeInfo)
  1231. for _, e := range udt.Elements {
  1232. size := readInt(data[:4])
  1233. data = data[4:]
  1234. var err error
  1235. if size < 0 {
  1236. err = v.UnmarshalUDT(e.Name, e.Type, nil)
  1237. } else {
  1238. err = v.UnmarshalUDT(e.Name, e.Type, data[:size])
  1239. data = data[size:]
  1240. }
  1241. if err != nil {
  1242. return err
  1243. }
  1244. }
  1245. return nil
  1246. }
  1247. k := reflect.ValueOf(value).Elem()
  1248. if k.Kind() != reflect.Struct || !k.IsValid() {
  1249. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1250. }
  1251. fields := make(map[string]reflect.Value)
  1252. t := k.Type()
  1253. for i := 0; i < t.NumField(); i++ {
  1254. sf := t.Field(i)
  1255. if tag := sf.Tag.Get("cql"); tag != "" {
  1256. fields[tag] = k.Field(i)
  1257. }
  1258. }
  1259. udt := info.(UDTTypeInfo)
  1260. for _, e := range udt.Elements {
  1261. size := readInt(data[:4])
  1262. data = data[4:]
  1263. var err error
  1264. if size >= 0 {
  1265. f, ok := fields[e.Name]
  1266. if !ok {
  1267. f = k.FieldByName(e.Name)
  1268. }
  1269. if !f.IsValid() || !f.CanAddr() {
  1270. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1271. }
  1272. fk := f.Addr().Interface()
  1273. if err := Unmarshal(e.Type, data[:size], fk); err != nil {
  1274. return err
  1275. }
  1276. data = data[size:]
  1277. }
  1278. if err != nil {
  1279. return err
  1280. }
  1281. }
  1282. return nil
  1283. }
  1284. // TypeInfo describes a Cassandra specific data type.
  1285. type TypeInfo interface {
  1286. Type() Type
  1287. Version() byte
  1288. Custom() string
  1289. // New creates a pointer to an empty version of whatever type
  1290. // is referenced by the TypeInfo receiver
  1291. New() interface{}
  1292. }
  1293. type NativeType struct {
  1294. proto byte
  1295. typ Type
  1296. custom string // only used for TypeCustom
  1297. }
  1298. func (t NativeType) New() interface{} {
  1299. return reflect.New(goType(t)).Interface()
  1300. }
  1301. func (s NativeType) Type() Type {
  1302. return s.typ
  1303. }
  1304. func (s NativeType) Version() byte {
  1305. return s.proto
  1306. }
  1307. func (s NativeType) Custom() string {
  1308. return s.custom
  1309. }
  1310. func (s NativeType) String() string {
  1311. switch s.typ {
  1312. case TypeCustom:
  1313. return fmt.Sprintf("%s(%s)", s.typ, s.custom)
  1314. default:
  1315. return s.typ.String()
  1316. }
  1317. }
  1318. type CollectionType struct {
  1319. NativeType
  1320. Key TypeInfo // only used for TypeMap
  1321. Elem TypeInfo // only used for TypeMap, TypeList and TypeSet
  1322. }
  1323. func (t CollectionType) New() interface{} {
  1324. return reflect.New(goType(t)).Interface()
  1325. }
  1326. func (c CollectionType) String() string {
  1327. switch c.typ {
  1328. case TypeMap:
  1329. return fmt.Sprintf("%s(%s, %s)", c.typ, c.Key, c.Elem)
  1330. case TypeList, TypeSet:
  1331. return fmt.Sprintf("%s(%s)", c.typ, c.Elem)
  1332. case TypeCustom:
  1333. return fmt.Sprintf("%s(%s)", c.typ, c.custom)
  1334. default:
  1335. return c.typ.String()
  1336. }
  1337. }
  1338. type TupleTypeInfo struct {
  1339. NativeType
  1340. Elems []TypeInfo
  1341. }
  1342. type UDTField struct {
  1343. Name string
  1344. Type TypeInfo
  1345. }
  1346. type UDTTypeInfo struct {
  1347. NativeType
  1348. KeySpace string
  1349. Name string
  1350. Elements []UDTField
  1351. }
  1352. func (u UDTTypeInfo) String() string {
  1353. buf := &bytes.Buffer{}
  1354. fmt.Fprintf(buf, "%s.%s{", u.KeySpace, u.Name)
  1355. first := true
  1356. for _, e := range u.Elements {
  1357. if !first {
  1358. fmt.Fprint(buf, ",")
  1359. } else {
  1360. first = false
  1361. }
  1362. fmt.Fprintf(buf, "%s=%v", e.Name, e.Type)
  1363. }
  1364. fmt.Fprint(buf, "}")
  1365. return buf.String()
  1366. }
  1367. // String returns a human readable name for the Cassandra datatype
  1368. // described by t.
  1369. // Type is the identifier of a Cassandra internal datatype.
  1370. type Type int
  1371. const (
  1372. TypeCustom Type = 0x0000
  1373. TypeAscii = 0x0001
  1374. TypeBigInt = 0x0002
  1375. TypeBlob = 0x0003
  1376. TypeBoolean = 0x0004
  1377. TypeCounter = 0x0005
  1378. TypeDecimal = 0x0006
  1379. TypeDouble = 0x0007
  1380. TypeFloat = 0x0008
  1381. TypeInt = 0x0009
  1382. TypeTimestamp = 0x000B
  1383. TypeUUID = 0x000C
  1384. TypeVarchar = 0x000D
  1385. TypeVarint = 0x000E
  1386. TypeTimeUUID = 0x000F
  1387. TypeInet = 0x0010
  1388. TypeList = 0x0020
  1389. TypeMap = 0x0021
  1390. TypeSet = 0x0022
  1391. TypeUDT = 0x0030
  1392. TypeTuple = 0x0031
  1393. )
  1394. // String returns the name of the identifier.
  1395. func (t Type) String() string {
  1396. switch t {
  1397. case TypeCustom:
  1398. return "custom"
  1399. case TypeAscii:
  1400. return "ascii"
  1401. case TypeBigInt:
  1402. return "bigint"
  1403. case TypeBlob:
  1404. return "blob"
  1405. case TypeBoolean:
  1406. return "boolean"
  1407. case TypeCounter:
  1408. return "counter"
  1409. case TypeDecimal:
  1410. return "decimal"
  1411. case TypeDouble:
  1412. return "double"
  1413. case TypeFloat:
  1414. return "float"
  1415. case TypeInt:
  1416. return "int"
  1417. case TypeTimestamp:
  1418. return "timestamp"
  1419. case TypeUUID:
  1420. return "uuid"
  1421. case TypeVarchar:
  1422. return "varchar"
  1423. case TypeTimeUUID:
  1424. return "timeuuid"
  1425. case TypeInet:
  1426. return "inet"
  1427. case TypeList:
  1428. return "list"
  1429. case TypeMap:
  1430. return "map"
  1431. case TypeSet:
  1432. return "set"
  1433. case TypeVarint:
  1434. return "varint"
  1435. case TypeTuple:
  1436. return "tuple"
  1437. default:
  1438. return fmt.Sprintf("unknown_type_%d", t)
  1439. }
  1440. }
  1441. type MarshalError string
  1442. func (m MarshalError) Error() string {
  1443. return string(m)
  1444. }
  1445. func marshalErrorf(format string, args ...interface{}) MarshalError {
  1446. return MarshalError(fmt.Sprintf(format, args...))
  1447. }
  1448. type UnmarshalError string
  1449. func (m UnmarshalError) Error() string {
  1450. return string(m)
  1451. }
  1452. func unmarshalErrorf(format string, args ...interface{}) UnmarshalError {
  1453. return UnmarshalError(fmt.Sprintf(format, args...))
  1454. }