marshal.go 31 KB

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