marshal.go 38 KB

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