marshal.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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. "fmt"
  9. "math"
  10. "math/big"
  11. "net"
  12. "reflect"
  13. "time"
  14. "speter.net/go/exp/math/dec/inf"
  15. )
  16. var (
  17. bigOne = big.NewInt(1)
  18. )
  19. // Marshaler is the interface implemented by objects that can marshal
  20. // themselves into values understood by Cassandra.
  21. type Marshaler interface {
  22. MarshalCQL(info *TypeInfo) ([]byte, error)
  23. }
  24. // Unmarshaler is the interface implemented by objects that can unmarshal
  25. // a Cassandra specific description of themselves.
  26. type Unmarshaler interface {
  27. UnmarshalCQL(info *TypeInfo, data []byte) error
  28. }
  29. // Marshal returns the CQL encoding of the value for the Cassandra
  30. // internal type described by the info parameter.
  31. func Marshal(info *TypeInfo, value interface{}) ([]byte, error) {
  32. if value == nil {
  33. return nil, nil
  34. }
  35. if valueRef := reflect.ValueOf(value); valueRef.Kind() == reflect.Ptr {
  36. if valueRef.IsNil() {
  37. return nil, nil
  38. } else {
  39. return Marshal(info, valueRef.Elem().Interface())
  40. }
  41. }
  42. if v, ok := value.(Marshaler); ok {
  43. return v.MarshalCQL(info)
  44. }
  45. switch info.Type {
  46. case TypeVarchar, TypeAscii, TypeBlob:
  47. return marshalVarchar(info, value)
  48. case TypeBoolean:
  49. return marshalBool(info, value)
  50. case TypeInt:
  51. return marshalInt(info, value)
  52. case TypeBigInt, TypeCounter:
  53. return marshalBigInt(info, value)
  54. case TypeFloat:
  55. return marshalFloat(info, value)
  56. case TypeDouble:
  57. return marshalDouble(info, value)
  58. case TypeDecimal:
  59. return marshalDecimal(info, value)
  60. case TypeTimestamp:
  61. return marshalTimestamp(info, value)
  62. case TypeList, TypeSet:
  63. return marshalList(info, value)
  64. case TypeMap:
  65. return marshalMap(info, value)
  66. case TypeUUID, TypeTimeUUID:
  67. return marshalUUID(info, value)
  68. case TypeVarint:
  69. return marshalVarint(info, value)
  70. case TypeInet:
  71. return marshalInet(info, value)
  72. }
  73. // TODO(tux21b): add the remaining types
  74. return nil, fmt.Errorf("can not marshal %T into %s", value, info)
  75. }
  76. // Unmarshal parses the CQL encoded data based on the info parameter that
  77. // describes the Cassandra internal data type and stores the result in the
  78. // value pointed by value.
  79. func Unmarshal(info *TypeInfo, data []byte, value interface{}) error {
  80. if v, ok := value.(Unmarshaler); ok {
  81. return v.UnmarshalCQL(info, data)
  82. }
  83. if isNullableValue(value) {
  84. return unmarshalNullable(info, data, value)
  85. }
  86. switch info.Type {
  87. case TypeVarchar, TypeAscii, TypeBlob:
  88. return unmarshalVarchar(info, data, value)
  89. case TypeBoolean:
  90. return unmarshalBool(info, data, value)
  91. case TypeInt:
  92. return unmarshalInt(info, data, value)
  93. case TypeBigInt, TypeCounter:
  94. return unmarshalBigInt(info, data, value)
  95. case TypeVarint:
  96. return unmarshalVarint(info, data, value)
  97. case TypeFloat:
  98. return unmarshalFloat(info, data, value)
  99. case TypeDouble:
  100. return unmarshalDouble(info, data, value)
  101. case TypeDecimal:
  102. return unmarshalDecimal(info, data, value)
  103. case TypeTimestamp:
  104. return unmarshalTimestamp(info, data, value)
  105. case TypeList, TypeSet:
  106. return unmarshalList(info, data, value)
  107. case TypeMap:
  108. return unmarshalMap(info, data, value)
  109. case TypeTimeUUID:
  110. return unmarshalTimeUUID(info, data, value)
  111. case TypeUUID:
  112. return unmarshalUUID(info, data, value)
  113. case TypeInet:
  114. return unmarshalInet(info, data, value)
  115. }
  116. // TODO(tux21b): add the remaining types
  117. return fmt.Errorf("can not unmarshal %s into %T", info, value)
  118. }
  119. func isNullableValue(value interface{}) bool {
  120. v := reflect.ValueOf(value)
  121. return v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Ptr
  122. }
  123. func isNullData(info *TypeInfo, data []byte) bool {
  124. return len(data) == 0
  125. }
  126. func unmarshalNullable(info *TypeInfo, data []byte, value interface{}) error {
  127. valueRef := reflect.ValueOf(value)
  128. if isNullData(info, data) {
  129. nilValue := reflect.Zero(valueRef.Type().Elem())
  130. valueRef.Elem().Set(nilValue)
  131. return nil
  132. } else {
  133. newValue := reflect.New(valueRef.Type().Elem().Elem())
  134. valueRef.Elem().Set(newValue)
  135. return Unmarshal(info, data, newValue.Interface())
  136. }
  137. }
  138. func marshalVarchar(info *TypeInfo, value interface{}) ([]byte, error) {
  139. switch v := value.(type) {
  140. case Marshaler:
  141. return v.MarshalCQL(info)
  142. case string:
  143. return []byte(v), nil
  144. case []byte:
  145. return v, nil
  146. }
  147. rv := reflect.ValueOf(value)
  148. t := rv.Type()
  149. k := t.Kind()
  150. switch {
  151. case k == reflect.String:
  152. return []byte(rv.String()), nil
  153. case k == reflect.Slice && t.Elem().Kind() == reflect.Uint8:
  154. return rv.Bytes(), nil
  155. }
  156. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  157. }
  158. func unmarshalVarchar(info *TypeInfo, data []byte, value interface{}) error {
  159. switch v := value.(type) {
  160. case Unmarshaler:
  161. return v.UnmarshalCQL(info, data)
  162. case *string:
  163. *v = string(data)
  164. return nil
  165. case *[]byte:
  166. var dataCopy []byte
  167. if data != nil {
  168. dataCopy = make([]byte, len(data))
  169. copy(dataCopy, data)
  170. }
  171. *v = dataCopy
  172. return nil
  173. }
  174. rv := reflect.ValueOf(value)
  175. if rv.Kind() != reflect.Ptr {
  176. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  177. }
  178. rv = rv.Elem()
  179. t := rv.Type()
  180. k := t.Kind()
  181. switch {
  182. case k == reflect.String:
  183. rv.SetString(string(data))
  184. return nil
  185. case k == reflect.Slice && t.Elem().Kind() == reflect.Uint8:
  186. var dataCopy []byte
  187. if data != nil {
  188. dataCopy = make([]byte, len(data))
  189. copy(dataCopy, data)
  190. }
  191. rv.SetBytes(dataCopy)
  192. return nil
  193. }
  194. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  195. }
  196. func marshalInt(info *TypeInfo, value interface{}) ([]byte, error) {
  197. switch v := value.(type) {
  198. case Marshaler:
  199. return v.MarshalCQL(info)
  200. case int:
  201. if v > math.MaxInt32 || v < math.MinInt32 {
  202. return nil, marshalErrorf("marshal int: value %d out of range", v)
  203. }
  204. return encInt(int32(v)), nil
  205. case uint:
  206. if v > math.MaxInt32 {
  207. return nil, marshalErrorf("marshal int: value %d out of range", v)
  208. }
  209. return encInt(int32(v)), nil
  210. case int64:
  211. if v > math.MaxInt32 || v < math.MinInt32 {
  212. return nil, marshalErrorf("marshal int: value %d out of range", v)
  213. }
  214. return encInt(int32(v)), nil
  215. case uint64:
  216. if v > math.MaxInt32 {
  217. return nil, marshalErrorf("marshal int: value %d out of range", v)
  218. }
  219. return encInt(int32(v)), nil
  220. case int32:
  221. return encInt(v), nil
  222. case uint32:
  223. if v > math.MaxInt32 {
  224. return nil, marshalErrorf("marshal int: value %d out of range", v)
  225. }
  226. return encInt(int32(v)), nil
  227. case int16:
  228. return encInt(int32(v)), nil
  229. case uint16:
  230. return encInt(int32(v)), nil
  231. case int8:
  232. return encInt(int32(v)), nil
  233. case uint8:
  234. return encInt(int32(v)), nil
  235. }
  236. rv := reflect.ValueOf(value)
  237. switch rv.Type().Kind() {
  238. case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
  239. v := rv.Int()
  240. if v > math.MaxInt32 || v < math.MinInt32 {
  241. return nil, marshalErrorf("marshal int: value %d out of range", v)
  242. }
  243. return encInt(int32(v)), nil
  244. case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
  245. v := rv.Uint()
  246. if v > math.MaxInt32 {
  247. return nil, marshalErrorf("marshal int: value %d out of range", v)
  248. }
  249. return encInt(int32(v)), nil
  250. }
  251. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  252. }
  253. func encInt(x int32) []byte {
  254. return []byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
  255. }
  256. func decInt(x []byte) int32 {
  257. if len(x) != 4 {
  258. return 0
  259. }
  260. return int32(x[0])<<24 | int32(x[1])<<16 | int32(x[2])<<8 | int32(x[3])
  261. }
  262. func marshalBigInt(info *TypeInfo, value interface{}) ([]byte, error) {
  263. switch v := value.(type) {
  264. case Marshaler:
  265. return v.MarshalCQL(info)
  266. case int:
  267. return encBigInt(int64(v)), nil
  268. case uint:
  269. if uint64(v) > math.MaxInt64 {
  270. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  271. }
  272. return encBigInt(int64(v)), nil
  273. case int64:
  274. return encBigInt(v), nil
  275. case uint64:
  276. if v > math.MaxInt64 {
  277. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  278. }
  279. return encBigInt(int64(v)), nil
  280. case int32:
  281. return encBigInt(int64(v)), nil
  282. case uint32:
  283. return encBigInt(int64(v)), nil
  284. case int16:
  285. return encBigInt(int64(v)), nil
  286. case uint16:
  287. return encBigInt(int64(v)), nil
  288. case int8:
  289. return encBigInt(int64(v)), nil
  290. case uint8:
  291. return encBigInt(int64(v)), nil
  292. case big.Int:
  293. return encBigInt2C(&v), nil
  294. }
  295. rv := reflect.ValueOf(value)
  296. switch rv.Type().Kind() {
  297. case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
  298. v := rv.Int()
  299. return encBigInt(v), nil
  300. case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
  301. v := rv.Uint()
  302. if v > math.MaxInt64 {
  303. return nil, marshalErrorf("marshal bigint: value %d out of range", v)
  304. }
  305. return encBigInt(int64(v)), nil
  306. }
  307. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  308. }
  309. func encBigInt(x int64) []byte {
  310. return []byte{byte(x >> 56), byte(x >> 48), byte(x >> 40), byte(x >> 32),
  311. byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
  312. }
  313. func bytesToInt64(data []byte) (ret int64) {
  314. for i := range data {
  315. ret |= int64(data[i]) << (8 * uint(len(data)-i-1))
  316. }
  317. return ret
  318. }
  319. func unmarshalBigInt(info *TypeInfo, data []byte, value interface{}) error {
  320. return unmarshalIntlike(info, decBigInt(data), data, value)
  321. }
  322. func unmarshalInt(info *TypeInfo, data []byte, value interface{}) error {
  323. return unmarshalIntlike(info, int64(decInt(data)), data, value)
  324. }
  325. func unmarshalVarint(info *TypeInfo, data []byte, value interface{}) error {
  326. switch value.(type) {
  327. case *big.Int:
  328. return unmarshalIntlike(info, 0, data, value)
  329. }
  330. if len(data) > 8 {
  331. return unmarshalErrorf("unmarshal int: varint value %v out of range for %T (use big.Int)", data, value)
  332. }
  333. int64Val := bytesToInt64(data)
  334. if len(data) < 8 && data[0]&0x80 > 0 {
  335. int64Val -= (1 << uint(len(data)*8))
  336. }
  337. return unmarshalIntlike(info, int64Val, data, value)
  338. }
  339. func marshalVarint(info *TypeInfo, value interface{}) ([]byte, error) {
  340. var (
  341. retBytes []byte
  342. err error
  343. )
  344. switch v := value.(type) {
  345. case uint64:
  346. if v > uint64(math.MaxInt64) {
  347. retBytes = make([]byte, 9)
  348. binary.BigEndian.PutUint64(retBytes[1:], v)
  349. } else {
  350. retBytes = make([]byte, 8)
  351. binary.BigEndian.PutUint64(retBytes, v)
  352. }
  353. default:
  354. retBytes, err = marshalBigInt(info, value)
  355. }
  356. if err == nil {
  357. // trim down to most significant byte
  358. i := 0
  359. for ; i < len(retBytes)-1; i++ {
  360. b0 := retBytes[i]
  361. if b0 != 0 && b0 != 0xFF {
  362. break
  363. }
  364. b1 := retBytes[i+1]
  365. if b0 == 0 && b1 != 0 {
  366. if b1&0x80 == 0 {
  367. i++
  368. }
  369. break
  370. }
  371. if b0 == 0xFF && b1 != 0xFF {
  372. if b1&0x80 > 0 {
  373. i++
  374. }
  375. break
  376. }
  377. }
  378. retBytes = retBytes[i:]
  379. }
  380. return retBytes, err
  381. }
  382. func unmarshalIntlike(info *TypeInfo, int64Val int64, data []byte, value interface{}) error {
  383. switch v := value.(type) {
  384. case *int:
  385. if ^uint(0) == math.MaxUint32 && (int64Val < math.MinInt32 || int64Val > math.MaxInt32) {
  386. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  387. }
  388. *v = int(int64Val)
  389. return nil
  390. case *uint:
  391. if int64Val < 0 || (^uint(0) == math.MaxUint32 && int64Val > math.MaxUint32) {
  392. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  393. }
  394. *v = uint(int64Val)
  395. return nil
  396. case *int64:
  397. *v = int64Val
  398. return nil
  399. case *uint64:
  400. if int64Val < 0 {
  401. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  402. }
  403. *v = uint64(int64Val)
  404. return nil
  405. case *int32:
  406. if int64Val < math.MinInt32 || int64Val > math.MaxInt32 {
  407. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  408. }
  409. *v = int32(int64Val)
  410. return nil
  411. case *uint32:
  412. if int64Val < 0 || int64Val > math.MaxUint32 {
  413. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  414. }
  415. *v = uint32(int64Val)
  416. return nil
  417. case *int16:
  418. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  419. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  420. }
  421. *v = int16(int64Val)
  422. return nil
  423. case *uint16:
  424. if int64Val < 0 || int64Val > math.MaxUint16 {
  425. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  426. }
  427. *v = uint16(int64Val)
  428. return nil
  429. case *int8:
  430. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  431. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  432. }
  433. *v = int8(int64Val)
  434. return nil
  435. case *uint8:
  436. if int64Val < 0 || int64Val > math.MaxUint8 {
  437. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  438. }
  439. *v = uint8(int64Val)
  440. return nil
  441. case *big.Int:
  442. decBigInt2C(data, v)
  443. return nil
  444. }
  445. rv := reflect.ValueOf(value)
  446. if rv.Kind() != reflect.Ptr {
  447. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  448. }
  449. rv = rv.Elem()
  450. switch rv.Type().Kind() {
  451. case reflect.Int:
  452. if ^uint(0) == math.MaxUint32 && (int64Val < math.MinInt32 || int64Val > math.MaxInt32) {
  453. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  454. }
  455. rv.SetInt(int64Val)
  456. return nil
  457. case reflect.Int64:
  458. rv.SetInt(int64Val)
  459. return nil
  460. case reflect.Int32:
  461. if int64Val < math.MinInt32 || int64Val > math.MaxInt32 {
  462. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  463. }
  464. rv.SetInt(int64Val)
  465. return nil
  466. case reflect.Int16:
  467. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  468. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  469. }
  470. rv.SetInt(int64Val)
  471. return nil
  472. case reflect.Int8:
  473. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  474. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  475. }
  476. rv.SetInt(int64Val)
  477. return nil
  478. case reflect.Uint:
  479. if int64Val < 0 || (^uint(0) == math.MaxUint32 && int64Val > math.MaxUint32) {
  480. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  481. }
  482. rv.SetUint(uint64(int64Val))
  483. return nil
  484. case reflect.Uint64:
  485. if int64Val < 0 {
  486. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  487. }
  488. rv.SetUint(uint64(int64Val))
  489. return nil
  490. case reflect.Uint32:
  491. if int64Val < 0 || int64Val > math.MaxUint32 {
  492. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  493. }
  494. rv.SetUint(uint64(int64Val))
  495. return nil
  496. case reflect.Uint16:
  497. if int64Val < 0 || int64Val > math.MaxUint16 {
  498. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  499. }
  500. rv.SetUint(uint64(int64Val))
  501. return nil
  502. case reflect.Uint8:
  503. if int64Val < 0 || int64Val > math.MaxUint8 {
  504. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  505. }
  506. rv.SetUint(uint64(int64Val))
  507. return nil
  508. }
  509. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  510. }
  511. func decBigInt(data []byte) int64 {
  512. if len(data) != 8 {
  513. return 0
  514. }
  515. return int64(data[0])<<56 | int64(data[1])<<48 |
  516. int64(data[2])<<40 | int64(data[3])<<32 |
  517. int64(data[4])<<24 | int64(data[5])<<16 |
  518. int64(data[6])<<8 | int64(data[7])
  519. }
  520. func marshalBool(info *TypeInfo, value interface{}) ([]byte, error) {
  521. switch v := value.(type) {
  522. case Marshaler:
  523. return v.MarshalCQL(info)
  524. case bool:
  525. return encBool(v), nil
  526. }
  527. rv := reflect.ValueOf(value)
  528. switch rv.Type().Kind() {
  529. case reflect.Bool:
  530. return encBool(rv.Bool()), nil
  531. }
  532. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  533. }
  534. func encBool(v bool) []byte {
  535. if v {
  536. return []byte{1}
  537. }
  538. return []byte{0}
  539. }
  540. func unmarshalBool(info *TypeInfo, data []byte, value interface{}) error {
  541. switch v := value.(type) {
  542. case Unmarshaler:
  543. return v.UnmarshalCQL(info, data)
  544. case *bool:
  545. *v = decBool(data)
  546. return nil
  547. }
  548. rv := reflect.ValueOf(value)
  549. if rv.Kind() != reflect.Ptr {
  550. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  551. }
  552. rv = rv.Elem()
  553. switch rv.Type().Kind() {
  554. case reflect.Bool:
  555. rv.SetBool(decBool(data))
  556. return nil
  557. }
  558. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  559. }
  560. func decBool(v []byte) bool {
  561. if len(v) == 0 {
  562. return false
  563. }
  564. return v[0] != 0
  565. }
  566. func marshalFloat(info *TypeInfo, value interface{}) ([]byte, error) {
  567. switch v := value.(type) {
  568. case Marshaler:
  569. return v.MarshalCQL(info)
  570. case float32:
  571. return encInt(int32(math.Float32bits(v))), nil
  572. }
  573. rv := reflect.ValueOf(value)
  574. switch rv.Type().Kind() {
  575. case reflect.Float32:
  576. return encInt(int32(math.Float32bits(float32(rv.Float())))), nil
  577. }
  578. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  579. }
  580. func unmarshalFloat(info *TypeInfo, data []byte, value interface{}) error {
  581. switch v := value.(type) {
  582. case Unmarshaler:
  583. return v.UnmarshalCQL(info, data)
  584. case *float32:
  585. *v = math.Float32frombits(uint32(decInt(data)))
  586. return nil
  587. }
  588. rv := reflect.ValueOf(value)
  589. if rv.Kind() != reflect.Ptr {
  590. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  591. }
  592. rv = rv.Elem()
  593. switch rv.Type().Kind() {
  594. case reflect.Float32:
  595. rv.SetFloat(float64(math.Float32frombits(uint32(decInt(data)))))
  596. return nil
  597. }
  598. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  599. }
  600. func marshalDouble(info *TypeInfo, value interface{}) ([]byte, error) {
  601. switch v := value.(type) {
  602. case Marshaler:
  603. return v.MarshalCQL(info)
  604. case float64:
  605. return encBigInt(int64(math.Float64bits(v))), nil
  606. }
  607. rv := reflect.ValueOf(value)
  608. switch rv.Type().Kind() {
  609. case reflect.Float64:
  610. return encBigInt(int64(math.Float64bits(rv.Float()))), nil
  611. }
  612. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  613. }
  614. func unmarshalDouble(info *TypeInfo, data []byte, value interface{}) error {
  615. switch v := value.(type) {
  616. case Unmarshaler:
  617. return v.UnmarshalCQL(info, data)
  618. case *float64:
  619. *v = math.Float64frombits(uint64(decBigInt(data)))
  620. return nil
  621. }
  622. rv := reflect.ValueOf(value)
  623. if rv.Kind() != reflect.Ptr {
  624. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  625. }
  626. rv = rv.Elem()
  627. switch rv.Type().Kind() {
  628. case reflect.Float64:
  629. rv.SetFloat(math.Float64frombits(uint64(decBigInt(data))))
  630. return nil
  631. }
  632. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  633. }
  634. func marshalDecimal(info *TypeInfo, value interface{}) ([]byte, error) {
  635. switch v := value.(type) {
  636. case Marshaler:
  637. return v.MarshalCQL(info)
  638. case inf.Dec:
  639. unscaled := encBigInt2C(v.UnscaledBig())
  640. if unscaled == nil {
  641. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  642. }
  643. buf := make([]byte, 4+len(unscaled))
  644. copy(buf[0:4], encInt(int32(v.Scale())))
  645. copy(buf[4:], unscaled)
  646. return buf, nil
  647. }
  648. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  649. }
  650. func unmarshalDecimal(info *TypeInfo, data []byte, value interface{}) error {
  651. switch v := value.(type) {
  652. case Unmarshaler:
  653. return v.UnmarshalCQL(info, data)
  654. case *inf.Dec:
  655. scale := decInt(data[0:4])
  656. unscaled := decBigInt2C(data[4:], nil)
  657. newValue := reflect.ValueOf(inf.NewDecBig(unscaled, inf.Scale(scale)))
  658. reflect.ValueOf(value).Elem().Set(newValue.Elem())
  659. return nil
  660. }
  661. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  662. }
  663. // decBigInt2C sets the value of n to the big-endian two's complement
  664. // value stored in the given data. If data[0]&80 != 0, the number
  665. // is negative. If data is empty, the result will be 0.
  666. func decBigInt2C(data []byte, n *big.Int) *big.Int {
  667. if n == nil {
  668. n = new(big.Int)
  669. }
  670. n.SetBytes(data)
  671. if len(data) > 0 && data[0]&0x80 > 0 {
  672. n.Sub(n, new(big.Int).Lsh(bigOne, uint(len(data))*8))
  673. }
  674. return n
  675. }
  676. // encBigInt2C returns the big-endian two's complement
  677. // form of n.
  678. func encBigInt2C(n *big.Int) []byte {
  679. switch n.Sign() {
  680. case 0:
  681. return []byte{0}
  682. case 1:
  683. b := n.Bytes()
  684. if b[0]&0x80 > 0 {
  685. b = append([]byte{0}, b...)
  686. }
  687. return b
  688. case -1:
  689. length := uint(n.BitLen()/8+1) * 8
  690. b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
  691. // When the most significant bit is on a byte
  692. // boundary, we can get some extra significant
  693. // bits, so strip them off when that happens.
  694. if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
  695. b = b[1:]
  696. }
  697. return b
  698. }
  699. return nil
  700. }
  701. func marshalTimestamp(info *TypeInfo, value interface{}) ([]byte, error) {
  702. switch v := value.(type) {
  703. case Marshaler:
  704. return v.MarshalCQL(info)
  705. case int64:
  706. return encBigInt(v), nil
  707. case time.Time:
  708. x := v.UnixNano() / int64(1000000)
  709. return encBigInt(x), nil
  710. }
  711. rv := reflect.ValueOf(value)
  712. switch rv.Type().Kind() {
  713. case reflect.Int64:
  714. return encBigInt(rv.Int()), nil
  715. }
  716. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  717. }
  718. func unmarshalTimestamp(info *TypeInfo, data []byte, value interface{}) error {
  719. switch v := value.(type) {
  720. case Unmarshaler:
  721. return v.UnmarshalCQL(info, data)
  722. case *int64:
  723. *v = decBigInt(data)
  724. return nil
  725. case *time.Time:
  726. if len(data) == 0 {
  727. return nil
  728. }
  729. x := decBigInt(data)
  730. sec := x / 1000
  731. nsec := (x - sec*1000) * 1000000
  732. *v = time.Unix(sec, nsec).In(time.UTC)
  733. return nil
  734. }
  735. rv := reflect.ValueOf(value)
  736. if rv.Kind() != reflect.Ptr {
  737. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  738. }
  739. rv = rv.Elem()
  740. switch rv.Type().Kind() {
  741. case reflect.Int64:
  742. rv.SetInt(decBigInt(data))
  743. return nil
  744. }
  745. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  746. }
  747. func marshalList(info *TypeInfo, value interface{}) ([]byte, error) {
  748. rv := reflect.ValueOf(value)
  749. t := rv.Type()
  750. k := t.Kind()
  751. switch k {
  752. case reflect.Slice, reflect.Array:
  753. if k == reflect.Slice && rv.IsNil() {
  754. return nil, nil
  755. }
  756. buf := &bytes.Buffer{}
  757. n := rv.Len()
  758. if n > math.MaxUint16 {
  759. return nil, marshalErrorf("marshal: slice / array too large")
  760. }
  761. buf.WriteByte(byte(n >> 8))
  762. buf.WriteByte(byte(n))
  763. for i := 0; i < n; i++ {
  764. item, err := Marshal(info.Elem, rv.Index(i).Interface())
  765. if err != nil {
  766. return nil, err
  767. }
  768. if len(item) > math.MaxUint16 {
  769. return nil, marshalErrorf("marshal: slice / array item too large")
  770. }
  771. buf.WriteByte(byte(len(item) >> 8))
  772. buf.WriteByte(byte(len(item)))
  773. buf.Write(item)
  774. }
  775. return buf.Bytes(), nil
  776. }
  777. if k == reflect.Map {
  778. elem := t.Elem()
  779. if elem.Kind() == reflect.Struct && elem.NumField() == 0 {
  780. rkeys := rv.MapKeys()
  781. keys := make([]interface{}, len(rkeys))
  782. for i := 0; i < len(keys); i++ {
  783. keys[i] = rkeys[i].Interface()
  784. }
  785. return marshalList(info, keys)
  786. }
  787. }
  788. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  789. }
  790. func unmarshalList(info *TypeInfo, data []byte, value interface{}) error {
  791. rv := reflect.ValueOf(value)
  792. if rv.Kind() != reflect.Ptr {
  793. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  794. }
  795. rv = rv.Elem()
  796. t := rv.Type()
  797. k := t.Kind()
  798. switch k {
  799. case reflect.Slice, reflect.Array:
  800. if data == nil {
  801. if k == reflect.Array {
  802. return unmarshalErrorf("unmarshal list: can not store nil in array value")
  803. }
  804. rv.Set(reflect.Zero(t))
  805. return nil
  806. }
  807. if len(data) < 2 {
  808. return unmarshalErrorf("unmarshal list: unexpected eof")
  809. }
  810. n := int(data[0])<<8 | int(data[1])
  811. data = data[2:]
  812. if k == reflect.Array {
  813. if rv.Len() != n {
  814. return unmarshalErrorf("unmarshal list: array with wrong size")
  815. }
  816. } else if rv.Cap() < n {
  817. rv.Set(reflect.MakeSlice(t, n, n))
  818. } else {
  819. rv.SetLen(n)
  820. }
  821. for i := 0; i < n; i++ {
  822. if len(data) < 2 {
  823. return unmarshalErrorf("unmarshal list: unexpected eof")
  824. }
  825. m := int(data[0])<<8 | int(data[1])
  826. data = data[2:]
  827. if err := Unmarshal(info.Elem, data[:m], rv.Index(i).Addr().Interface()); err != nil {
  828. return err
  829. }
  830. data = data[m:]
  831. }
  832. return nil
  833. }
  834. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  835. }
  836. func marshalMap(info *TypeInfo, value interface{}) ([]byte, error) {
  837. rv := reflect.ValueOf(value)
  838. t := rv.Type()
  839. if t.Kind() != reflect.Map {
  840. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  841. }
  842. if rv.IsNil() {
  843. return nil, nil
  844. }
  845. buf := &bytes.Buffer{}
  846. n := rv.Len()
  847. if n > math.MaxUint16 {
  848. return nil, marshalErrorf("marshal: map too large")
  849. }
  850. buf.WriteByte(byte(n >> 8))
  851. buf.WriteByte(byte(n))
  852. keys := rv.MapKeys()
  853. for _, key := range keys {
  854. item, err := Marshal(info.Key, key.Interface())
  855. if err != nil {
  856. return nil, err
  857. }
  858. if len(item) > math.MaxUint16 {
  859. return nil, marshalErrorf("marshal: slice / array item too large")
  860. }
  861. buf.WriteByte(byte(len(item) >> 8))
  862. buf.WriteByte(byte(len(item)))
  863. buf.Write(item)
  864. item, err = Marshal(info.Elem, rv.MapIndex(key).Interface())
  865. if err != nil {
  866. return nil, err
  867. }
  868. if len(item) > math.MaxUint16 {
  869. return nil, marshalErrorf("marshal: slice / array item too large")
  870. }
  871. buf.WriteByte(byte(len(item) >> 8))
  872. buf.WriteByte(byte(len(item)))
  873. buf.Write(item)
  874. }
  875. return buf.Bytes(), nil
  876. }
  877. func unmarshalMap(info *TypeInfo, data []byte, value interface{}) error {
  878. rv := reflect.ValueOf(value)
  879. if rv.Kind() != reflect.Ptr {
  880. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  881. }
  882. rv = rv.Elem()
  883. t := rv.Type()
  884. if t.Kind() != reflect.Map {
  885. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  886. }
  887. if data == nil {
  888. rv.Set(reflect.Zero(t))
  889. return nil
  890. }
  891. rv.Set(reflect.MakeMap(t))
  892. if len(data) < 2 {
  893. return unmarshalErrorf("unmarshal map: unexpected eof")
  894. }
  895. n := int(data[1]) | int(data[0])<<8
  896. data = data[2:]
  897. for i := 0; i < n; i++ {
  898. if len(data) < 2 {
  899. return unmarshalErrorf("unmarshal list: unexpected eof")
  900. }
  901. m := int(data[1]) | int(data[0])<<8
  902. data = data[2:]
  903. key := reflect.New(t.Key())
  904. if err := Unmarshal(info.Key, data[:m], key.Interface()); err != nil {
  905. return err
  906. }
  907. data = data[m:]
  908. m = int(data[1]) | int(data[0])<<8
  909. data = data[2:]
  910. val := reflect.New(t.Elem())
  911. if err := Unmarshal(info.Elem, data[:m], val.Interface()); err != nil {
  912. return err
  913. }
  914. data = data[m:]
  915. rv.SetMapIndex(key.Elem(), val.Elem())
  916. }
  917. return nil
  918. }
  919. func marshalUUID(info *TypeInfo, value interface{}) ([]byte, error) {
  920. switch val := value.(type) {
  921. case UUID:
  922. return val.Bytes(), nil
  923. case []byte:
  924. if len(val) == 16 {
  925. return val, nil
  926. }
  927. case string:
  928. b, err := ParseUUID(val)
  929. if err != nil {
  930. return nil, err
  931. }
  932. return b[:], nil
  933. }
  934. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  935. }
  936. func unmarshalUUID(info *TypeInfo, data []byte, value interface{}) error {
  937. if data == nil || len(data) == 0 {
  938. switch v := value.(type) {
  939. case *string:
  940. *v = ""
  941. case *[]byte:
  942. *v = nil
  943. case *UUID:
  944. *v = UUID{}
  945. default:
  946. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  947. }
  948. return nil
  949. }
  950. u, err := UUIDFromBytes(data)
  951. if err != nil {
  952. return unmarshalErrorf("Unable to parse UUID: %s", err)
  953. }
  954. switch v := value.(type) {
  955. case *string:
  956. *v = u.String()
  957. return nil
  958. case *[]byte:
  959. *v = u[:]
  960. return nil
  961. case *UUID:
  962. *v = u
  963. return nil
  964. }
  965. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  966. }
  967. func unmarshalTimeUUID(info *TypeInfo, data []byte, value interface{}) error {
  968. switch v := value.(type) {
  969. case Unmarshaler:
  970. return v.UnmarshalCQL(info, data)
  971. case *time.Time:
  972. id, err := UUIDFromBytes(data)
  973. if err != nil {
  974. return err
  975. } else if id.Version() != 1 {
  976. return unmarshalErrorf("invalid timeuuid")
  977. }
  978. *v = id.Time()
  979. return nil
  980. default:
  981. return unmarshalUUID(info, data, value)
  982. }
  983. }
  984. func marshalInet(info *TypeInfo, value interface{}) ([]byte, error) {
  985. // we return either the 4 or 16 byte representation of an
  986. // ip address here otherwise the db value will be prefixed
  987. // with the remaining byte values e.g. ::ffff:127.0.0.1 and not 127.0.0.1
  988. switch val := value.(type) {
  989. case net.IP:
  990. t := val.To4()
  991. if t == nil {
  992. return val.To16(), nil
  993. }
  994. return t, nil
  995. case string:
  996. b := net.ParseIP(val)
  997. if b != nil {
  998. t := b.To4()
  999. if t == nil {
  1000. return b.To16(), nil
  1001. }
  1002. return t, nil
  1003. }
  1004. return nil, marshalErrorf("cannot marshal. invalid ip string %s", val)
  1005. }
  1006. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1007. }
  1008. func unmarshalInet(info *TypeInfo, data []byte, value interface{}) error {
  1009. switch v := value.(type) {
  1010. case Unmarshaler:
  1011. return v.UnmarshalCQL(info, data)
  1012. case *net.IP:
  1013. ip := net.IP(data)
  1014. if v4 := ip.To4(); v4 != nil {
  1015. *v = v4
  1016. return nil
  1017. }
  1018. *v = ip
  1019. return nil
  1020. case *string:
  1021. if len(data) == 0 {
  1022. *v = ""
  1023. return nil
  1024. }
  1025. ip := net.IP(data)
  1026. if v4 := ip.To4(); v4 != nil {
  1027. *v = v4.String()
  1028. return nil
  1029. }
  1030. *v = ip.String()
  1031. return nil
  1032. }
  1033. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1034. }
  1035. // TypeInfo describes a Cassandra specific data type.
  1036. type TypeInfo struct {
  1037. Type Type
  1038. Key *TypeInfo // only used for TypeMap
  1039. Elem *TypeInfo // only used for TypeMap, TypeList and TypeSet
  1040. Custom string // only used for TypeCostum
  1041. }
  1042. // String returns a human readable name for the Cassandra datatype
  1043. // described by t.
  1044. func (t TypeInfo) String() string {
  1045. switch t.Type {
  1046. case TypeMap:
  1047. return fmt.Sprintf("%s(%s, %s)", t.Type, t.Key, t.Elem)
  1048. case TypeList, TypeSet:
  1049. return fmt.Sprintf("%s(%s)", t.Type, t.Elem)
  1050. case TypeCustom:
  1051. return fmt.Sprintf("%s(%s)", t.Type, t.Custom)
  1052. }
  1053. return t.Type.String()
  1054. }
  1055. // Type is the identifier of a Cassandra internal datatype.
  1056. type Type int
  1057. const (
  1058. TypeCustom Type = 0x0000
  1059. TypeAscii Type = 0x0001
  1060. TypeBigInt Type = 0x0002
  1061. TypeBlob Type = 0x0003
  1062. TypeBoolean Type = 0x0004
  1063. TypeCounter Type = 0x0005
  1064. TypeDecimal Type = 0x0006
  1065. TypeDouble Type = 0x0007
  1066. TypeFloat Type = 0x0008
  1067. TypeInt Type = 0x0009
  1068. TypeTimestamp Type = 0x000B
  1069. TypeUUID Type = 0x000C
  1070. TypeVarchar Type = 0x000D
  1071. TypeVarint Type = 0x000E
  1072. TypeTimeUUID Type = 0x000F
  1073. TypeInet Type = 0x0010
  1074. TypeList Type = 0x0020
  1075. TypeMap Type = 0x0021
  1076. TypeSet Type = 0x0022
  1077. )
  1078. // String returns the name of the identifier.
  1079. func (t Type) String() string {
  1080. switch t {
  1081. case TypeCustom:
  1082. return "custom"
  1083. case TypeAscii:
  1084. return "ascii"
  1085. case TypeBigInt:
  1086. return "bigint"
  1087. case TypeBlob:
  1088. return "blob"
  1089. case TypeBoolean:
  1090. return "boolean"
  1091. case TypeCounter:
  1092. return "counter"
  1093. case TypeDecimal:
  1094. return "decimal"
  1095. case TypeDouble:
  1096. return "double"
  1097. case TypeFloat:
  1098. return "float"
  1099. case TypeInt:
  1100. return "int"
  1101. case TypeTimestamp:
  1102. return "timestamp"
  1103. case TypeUUID:
  1104. return "uuid"
  1105. case TypeVarchar:
  1106. return "varchar"
  1107. case TypeTimeUUID:
  1108. return "timeuuid"
  1109. case TypeInet:
  1110. return "inet"
  1111. case TypeList:
  1112. return "list"
  1113. case TypeMap:
  1114. return "map"
  1115. case TypeSet:
  1116. return "set"
  1117. case TypeVarint:
  1118. return "varint"
  1119. default:
  1120. return "unknown"
  1121. }
  1122. }
  1123. type MarshalError string
  1124. func (m MarshalError) Error() string {
  1125. return string(m)
  1126. }
  1127. func marshalErrorf(format string, args ...interface{}) MarshalError {
  1128. return MarshalError(fmt.Sprintf(format, args...))
  1129. }
  1130. type UnmarshalError string
  1131. func (m UnmarshalError) Error() string {
  1132. return string(m)
  1133. }
  1134. func unmarshalErrorf(format string, args ...interface{}) UnmarshalError {
  1135. return UnmarshalError(fmt.Sprintf(format, args...))
  1136. }