marshal.go 40 KB

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