marshal.go 39 KB

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