marshal.go 39 KB

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