marshal.go 40 KB

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