marshal.go 47 KB

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