marshal.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  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. *v = time.Time{}
  1010. return nil
  1011. }
  1012. x := decBigInt(data)
  1013. sec := x / 1000
  1014. nsec := (x - sec*1000) * 1000000
  1015. *v = time.Unix(sec, nsec).In(time.UTC)
  1016. return nil
  1017. }
  1018. rv := reflect.ValueOf(value)
  1019. if rv.Kind() != reflect.Ptr {
  1020. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1021. }
  1022. rv = rv.Elem()
  1023. switch rv.Type().Kind() {
  1024. case reflect.Int64:
  1025. rv.SetInt(decBigInt(data))
  1026. return nil
  1027. }
  1028. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1029. }
  1030. func writeCollectionSize(info CollectionType, n int, buf *bytes.Buffer) error {
  1031. if info.proto > protoVersion2 {
  1032. if n > math.MaxInt32 {
  1033. return marshalErrorf("marshal: collection too large")
  1034. }
  1035. buf.WriteByte(byte(n >> 24))
  1036. buf.WriteByte(byte(n >> 16))
  1037. buf.WriteByte(byte(n >> 8))
  1038. buf.WriteByte(byte(n))
  1039. } else {
  1040. if n > math.MaxUint16 {
  1041. return marshalErrorf("marshal: collection too large")
  1042. }
  1043. buf.WriteByte(byte(n >> 8))
  1044. buf.WriteByte(byte(n))
  1045. }
  1046. return nil
  1047. }
  1048. func marshalList(info TypeInfo, value interface{}) ([]byte, error) {
  1049. listInfo, ok := info.(CollectionType)
  1050. if !ok {
  1051. return nil, marshalErrorf("marshal: can not marshal non collection type into list")
  1052. }
  1053. if value == nil {
  1054. return nil, nil
  1055. }
  1056. rv := reflect.ValueOf(value)
  1057. t := rv.Type()
  1058. k := t.Kind()
  1059. if k == reflect.Slice && rv.IsNil() {
  1060. return nil, nil
  1061. }
  1062. switch k {
  1063. case reflect.Slice, reflect.Array:
  1064. buf := &bytes.Buffer{}
  1065. n := rv.Len()
  1066. if err := writeCollectionSize(listInfo, n, buf); err != nil {
  1067. return nil, err
  1068. }
  1069. for i := 0; i < n; i++ {
  1070. item, err := Marshal(listInfo.Elem, rv.Index(i).Interface())
  1071. if err != nil {
  1072. return nil, err
  1073. }
  1074. if err := writeCollectionSize(listInfo, len(item), buf); err != nil {
  1075. return nil, err
  1076. }
  1077. buf.Write(item)
  1078. }
  1079. return buf.Bytes(), nil
  1080. case reflect.Map:
  1081. elem := t.Elem()
  1082. if elem.Kind() == reflect.Struct && elem.NumField() == 0 {
  1083. rkeys := rv.MapKeys()
  1084. keys := make([]interface{}, len(rkeys))
  1085. for i := 0; i < len(keys); i++ {
  1086. keys[i] = rkeys[i].Interface()
  1087. }
  1088. return marshalList(listInfo, keys)
  1089. }
  1090. }
  1091. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1092. }
  1093. func readCollectionSize(info CollectionType, data []byte) (size, read int) {
  1094. if info.proto > protoVersion2 {
  1095. size = int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1096. read = 4
  1097. } else {
  1098. size = int(data[0])<<8 | int(data[1])
  1099. read = 2
  1100. }
  1101. return
  1102. }
  1103. func unmarshalList(info TypeInfo, data []byte, value interface{}) error {
  1104. listInfo, ok := info.(CollectionType)
  1105. if !ok {
  1106. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into list")
  1107. }
  1108. rv := reflect.ValueOf(value)
  1109. if rv.Kind() != reflect.Ptr {
  1110. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1111. }
  1112. rv = rv.Elem()
  1113. t := rv.Type()
  1114. k := t.Kind()
  1115. switch k {
  1116. case reflect.Slice, reflect.Array:
  1117. if data == nil {
  1118. if k == reflect.Array {
  1119. return unmarshalErrorf("unmarshal list: can not store nil in array value")
  1120. }
  1121. if rv.IsNil() {
  1122. return nil
  1123. }
  1124. rv.Set(reflect.Zero(t))
  1125. return nil
  1126. }
  1127. if len(data) < 2 {
  1128. return unmarshalErrorf("unmarshal list: unexpected eof")
  1129. }
  1130. n, p := readCollectionSize(listInfo, data)
  1131. data = data[p:]
  1132. if k == reflect.Array {
  1133. if rv.Len() != n {
  1134. return unmarshalErrorf("unmarshal list: array with wrong size")
  1135. }
  1136. } else {
  1137. rv.Set(reflect.MakeSlice(t, n, n))
  1138. }
  1139. for i := 0; i < n; i++ {
  1140. if len(data) < 2 {
  1141. return unmarshalErrorf("unmarshal list: unexpected eof")
  1142. }
  1143. m, p := readCollectionSize(listInfo, data)
  1144. data = data[p:]
  1145. if err := Unmarshal(listInfo.Elem, data[:m], rv.Index(i).Addr().Interface()); err != nil {
  1146. return err
  1147. }
  1148. data = data[m:]
  1149. }
  1150. return nil
  1151. }
  1152. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1153. }
  1154. func marshalMap(info TypeInfo, value interface{}) ([]byte, error) {
  1155. mapInfo, ok := info.(CollectionType)
  1156. if !ok {
  1157. return nil, marshalErrorf("marshal: can not marshal none collection type into map")
  1158. }
  1159. if value == nil {
  1160. return nil, nil
  1161. }
  1162. rv := reflect.ValueOf(value)
  1163. if rv.IsNil() {
  1164. return nil, nil
  1165. }
  1166. t := rv.Type()
  1167. if t.Kind() != reflect.Map {
  1168. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1169. }
  1170. buf := &bytes.Buffer{}
  1171. n := rv.Len()
  1172. if err := writeCollectionSize(mapInfo, n, buf); err != nil {
  1173. return nil, err
  1174. }
  1175. keys := rv.MapKeys()
  1176. for _, key := range keys {
  1177. item, err := Marshal(mapInfo.Key, key.Interface())
  1178. if err != nil {
  1179. return nil, err
  1180. }
  1181. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  1182. return nil, err
  1183. }
  1184. buf.Write(item)
  1185. item, err = Marshal(mapInfo.Elem, rv.MapIndex(key).Interface())
  1186. if err != nil {
  1187. return nil, err
  1188. }
  1189. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  1190. return nil, err
  1191. }
  1192. buf.Write(item)
  1193. }
  1194. return buf.Bytes(), nil
  1195. }
  1196. func unmarshalMap(info TypeInfo, data []byte, value interface{}) error {
  1197. mapInfo, ok := info.(CollectionType)
  1198. if !ok {
  1199. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into map")
  1200. }
  1201. rv := reflect.ValueOf(value)
  1202. if rv.Kind() != reflect.Ptr {
  1203. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1204. }
  1205. rv = rv.Elem()
  1206. t := rv.Type()
  1207. if t.Kind() != reflect.Map {
  1208. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1209. }
  1210. if data == nil {
  1211. rv.Set(reflect.Zero(t))
  1212. return nil
  1213. }
  1214. rv.Set(reflect.MakeMap(t))
  1215. if len(data) < 2 {
  1216. return unmarshalErrorf("unmarshal map: unexpected eof")
  1217. }
  1218. n, p := readCollectionSize(mapInfo, data)
  1219. data = data[p:]
  1220. for i := 0; i < n; i++ {
  1221. if len(data) < 2 {
  1222. return unmarshalErrorf("unmarshal list: unexpected eof")
  1223. }
  1224. m, p := readCollectionSize(mapInfo, data)
  1225. data = data[p:]
  1226. key := reflect.New(t.Key())
  1227. if err := Unmarshal(mapInfo.Key, data[:m], key.Interface()); err != nil {
  1228. return err
  1229. }
  1230. data = data[m:]
  1231. m, p = readCollectionSize(mapInfo, data)
  1232. data = data[p:]
  1233. val := reflect.New(t.Elem())
  1234. if err := Unmarshal(mapInfo.Elem, data[:m], val.Interface()); err != nil {
  1235. return err
  1236. }
  1237. data = data[m:]
  1238. rv.SetMapIndex(key.Elem(), val.Elem())
  1239. }
  1240. return nil
  1241. }
  1242. func marshalUUID(info TypeInfo, value interface{}) ([]byte, error) {
  1243. switch val := value.(type) {
  1244. case UUID:
  1245. return val.Bytes(), nil
  1246. case []byte:
  1247. if len(val) == 16 {
  1248. return val, nil
  1249. }
  1250. case string:
  1251. b, err := ParseUUID(val)
  1252. if err != nil {
  1253. return nil, err
  1254. }
  1255. return b[:], nil
  1256. }
  1257. if value == nil {
  1258. return nil, nil
  1259. }
  1260. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1261. }
  1262. func unmarshalUUID(info TypeInfo, data []byte, value interface{}) error {
  1263. if data == nil || len(data) == 0 {
  1264. switch v := value.(type) {
  1265. case *string:
  1266. *v = ""
  1267. case *[]byte:
  1268. *v = nil
  1269. case *UUID:
  1270. *v = UUID{}
  1271. default:
  1272. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1273. }
  1274. return nil
  1275. }
  1276. u, err := UUIDFromBytes(data)
  1277. if err != nil {
  1278. return unmarshalErrorf("Unable to parse UUID: %s", err)
  1279. }
  1280. switch v := value.(type) {
  1281. case *string:
  1282. *v = u.String()
  1283. return nil
  1284. case *[]byte:
  1285. *v = u[:]
  1286. return nil
  1287. case *UUID:
  1288. *v = u
  1289. return nil
  1290. }
  1291. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1292. }
  1293. func unmarshalTimeUUID(info TypeInfo, data []byte, value interface{}) error {
  1294. switch v := value.(type) {
  1295. case Unmarshaler:
  1296. return v.UnmarshalCQL(info, data)
  1297. case *time.Time:
  1298. id, err := UUIDFromBytes(data)
  1299. if err != nil {
  1300. return err
  1301. } else if id.Version() != 1 {
  1302. return unmarshalErrorf("invalid timeuuid")
  1303. }
  1304. *v = id.Time()
  1305. return nil
  1306. default:
  1307. return unmarshalUUID(info, data, value)
  1308. }
  1309. }
  1310. func marshalInet(info TypeInfo, value interface{}) ([]byte, error) {
  1311. // we return either the 4 or 16 byte representation of an
  1312. // ip address here otherwise the db value will be prefixed
  1313. // with the remaining byte values e.g. ::ffff:127.0.0.1 and not 127.0.0.1
  1314. switch val := value.(type) {
  1315. case net.IP:
  1316. t := val.To4()
  1317. if t == nil {
  1318. return val.To16(), nil
  1319. }
  1320. return t, nil
  1321. case string:
  1322. b := net.ParseIP(val)
  1323. if b != nil {
  1324. t := b.To4()
  1325. if t == nil {
  1326. return b.To16(), nil
  1327. }
  1328. return t, nil
  1329. }
  1330. return nil, marshalErrorf("cannot marshal. invalid ip string %s", val)
  1331. }
  1332. if value == nil {
  1333. return nil, nil
  1334. }
  1335. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1336. }
  1337. func unmarshalInet(info TypeInfo, data []byte, value interface{}) error {
  1338. switch v := value.(type) {
  1339. case Unmarshaler:
  1340. return v.UnmarshalCQL(info, data)
  1341. case *net.IP:
  1342. if x := len(data); !(x == 4 || x == 16) {
  1343. return unmarshalErrorf("cannot unmarshal %s into %T: invalid sized IP: got %d bytes not 4 or 16", info, value, x)
  1344. }
  1345. buf := copyBytes(data)
  1346. ip := net.IP(buf)
  1347. if v4 := ip.To4(); v4 != nil {
  1348. *v = v4
  1349. return nil
  1350. }
  1351. *v = ip
  1352. return nil
  1353. case *string:
  1354. if len(data) == 0 {
  1355. *v = ""
  1356. return nil
  1357. }
  1358. ip := net.IP(data)
  1359. if v4 := ip.To4(); v4 != nil {
  1360. *v = v4.String()
  1361. return nil
  1362. }
  1363. *v = ip.String()
  1364. return nil
  1365. }
  1366. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1367. }
  1368. func marshalTuple(info TypeInfo, value interface{}) ([]byte, error) {
  1369. tuple := info.(TupleTypeInfo)
  1370. switch v := value.(type) {
  1371. case []interface{}:
  1372. var buf []byte
  1373. if len(v) != len(tuple.Elems) {
  1374. return nil, unmarshalErrorf("cannont marshal tuple: wrong number of elements")
  1375. }
  1376. for i, elem := range v {
  1377. data, err := Marshal(tuple.Elems[i], elem)
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. n := len(data)
  1382. buf = appendInt(buf, int32(n))
  1383. buf = append(buf, data...)
  1384. }
  1385. return buf, nil
  1386. }
  1387. return nil, unmarshalErrorf("cannot marshal %T into %s", value, tuple)
  1388. }
  1389. // currently only support unmarshal into a list of values, this makes it possible
  1390. // to support tuples without changing the query API. In the future this can be extend
  1391. // to allow unmarshalling into custom tuple types.
  1392. func unmarshalTuple(info TypeInfo, data []byte, value interface{}) error {
  1393. if v, ok := value.(Unmarshaler); ok {
  1394. return v.UnmarshalCQL(info, data)
  1395. }
  1396. tuple := info.(TupleTypeInfo)
  1397. switch v := value.(type) {
  1398. case []interface{}:
  1399. for i, elem := range tuple.Elems {
  1400. // each element inside data is a [bytes]
  1401. size := readInt(data)
  1402. data = data[4:]
  1403. err := Unmarshal(elem, data[:size], v[i])
  1404. if err != nil {
  1405. return err
  1406. }
  1407. data = data[size:]
  1408. }
  1409. return nil
  1410. }
  1411. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1412. }
  1413. // UDTMarshaler is an interface which should be implemented by users wishing to
  1414. // handle encoding UDT types to sent to Cassandra. Note: due to current implentations
  1415. // methods defined for this interface must be value receivers not pointer receivers.
  1416. type UDTMarshaler interface {
  1417. // MarshalUDT will be called for each field in the the UDT returned by Cassandra,
  1418. // the implementor should marshal the type to return by for example calling
  1419. // Marshal.
  1420. MarshalUDT(name string, info TypeInfo) ([]byte, error)
  1421. }
  1422. // UDTUnmarshaler should be implemented by users wanting to implement custom
  1423. // UDT unmarshaling.
  1424. type UDTUnmarshaler interface {
  1425. // UnmarshalUDT will be called for each field in the UDT return by Cassandra,
  1426. // the implementor should unmarshal the data into the value of their chosing,
  1427. // for example by calling Unmarshal.
  1428. UnmarshalUDT(name string, info TypeInfo, data []byte) error
  1429. }
  1430. func marshalUDT(info TypeInfo, value interface{}) ([]byte, error) {
  1431. udt := info.(UDTTypeInfo)
  1432. switch v := value.(type) {
  1433. case Marshaler:
  1434. return v.MarshalCQL(info)
  1435. case UDTMarshaler:
  1436. var buf []byte
  1437. for _, e := range udt.Elements {
  1438. data, err := v.MarshalUDT(e.Name, e.Type)
  1439. if err != nil {
  1440. return nil, err
  1441. }
  1442. buf = appendBytes(buf, data)
  1443. }
  1444. return buf, nil
  1445. case map[string]interface{}:
  1446. var buf []byte
  1447. for _, e := range udt.Elements {
  1448. val, ok := v[e.Name]
  1449. if !ok {
  1450. continue
  1451. }
  1452. data, err := Marshal(e.Type, val)
  1453. if err != nil {
  1454. return nil, err
  1455. }
  1456. buf = appendBytes(buf, data)
  1457. }
  1458. return buf, nil
  1459. }
  1460. k := reflect.ValueOf(value)
  1461. if k.Kind() == reflect.Ptr {
  1462. if k.IsNil() {
  1463. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1464. }
  1465. k = k.Elem()
  1466. }
  1467. if k.Kind() != reflect.Struct || !k.IsValid() {
  1468. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1469. }
  1470. fields := make(map[string]reflect.Value)
  1471. t := reflect.TypeOf(value)
  1472. for i := 0; i < t.NumField(); i++ {
  1473. sf := t.Field(i)
  1474. if tag := sf.Tag.Get("cql"); tag != "" {
  1475. fields[tag] = k.Field(i)
  1476. }
  1477. }
  1478. var buf []byte
  1479. for _, e := range udt.Elements {
  1480. f, ok := fields[e.Name]
  1481. if !ok {
  1482. f = k.FieldByName(e.Name)
  1483. }
  1484. var data []byte
  1485. if f.IsValid() && f.CanInterface() {
  1486. var err error
  1487. data, err = Marshal(e.Type, f.Interface())
  1488. if err != nil {
  1489. return nil, err
  1490. }
  1491. }
  1492. buf = appendBytes(buf, data)
  1493. }
  1494. return buf, nil
  1495. }
  1496. func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
  1497. switch v := value.(type) {
  1498. case Unmarshaler:
  1499. return v.UnmarshalCQL(info, data)
  1500. case UDTUnmarshaler:
  1501. udt := info.(UDTTypeInfo)
  1502. for _, e := range udt.Elements {
  1503. if len(data) == 0 {
  1504. return nil
  1505. }
  1506. size := readInt(data[:4])
  1507. data = data[4:]
  1508. var err error
  1509. if size < 0 {
  1510. err = v.UnmarshalUDT(e.Name, e.Type, nil)
  1511. } else {
  1512. err = v.UnmarshalUDT(e.Name, e.Type, data[:size])
  1513. data = data[size:]
  1514. }
  1515. if err != nil {
  1516. return err
  1517. }
  1518. }
  1519. return nil
  1520. case *map[string]interface{}:
  1521. udt := info.(UDTTypeInfo)
  1522. rv := reflect.ValueOf(value)
  1523. if rv.Kind() != reflect.Ptr {
  1524. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1525. }
  1526. rv = rv.Elem()
  1527. t := rv.Type()
  1528. if t.Kind() != reflect.Map {
  1529. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1530. } else if data == nil {
  1531. rv.Set(reflect.Zero(t))
  1532. return nil
  1533. }
  1534. rv.Set(reflect.MakeMap(t))
  1535. m := *v
  1536. for _, e := range udt.Elements {
  1537. if len(data) == 0 {
  1538. return nil
  1539. }
  1540. size := readInt(data[:4])
  1541. data = data[4:]
  1542. val := reflect.New(goType(e.Type))
  1543. var err error
  1544. if size < 0 {
  1545. err = Unmarshal(e.Type, nil, val.Interface())
  1546. } else {
  1547. err = Unmarshal(e.Type, data[:size], val.Interface())
  1548. data = data[size:]
  1549. }
  1550. if err != nil {
  1551. return err
  1552. }
  1553. m[e.Name] = val.Elem().Interface()
  1554. }
  1555. return nil
  1556. }
  1557. k := reflect.ValueOf(value).Elem()
  1558. if k.Kind() != reflect.Struct || !k.IsValid() {
  1559. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1560. }
  1561. fields := make(map[string]reflect.Value)
  1562. t := k.Type()
  1563. for i := 0; i < t.NumField(); i++ {
  1564. sf := t.Field(i)
  1565. if tag := sf.Tag.Get("cql"); tag != "" {
  1566. fields[tag] = k.Field(i)
  1567. }
  1568. }
  1569. if len(data) == 0 {
  1570. if k.CanSet() {
  1571. k.Set(reflect.Zero(k.Type()))
  1572. }
  1573. return nil
  1574. }
  1575. udt := info.(UDTTypeInfo)
  1576. for _, e := range udt.Elements {
  1577. if len(data) < 4 {
  1578. // UDT def does not match the column value
  1579. return nil
  1580. }
  1581. size := readInt(data[:4])
  1582. data = data[4:]
  1583. var err error
  1584. if size >= 0 {
  1585. f, ok := fields[e.Name]
  1586. if !ok {
  1587. f = k.FieldByName(e.Name)
  1588. }
  1589. if !f.IsValid() || !f.CanAddr() {
  1590. return unmarshalErrorf("cannot unmarshal %s into %T: field %v is not valid", info, value, e.Name)
  1591. }
  1592. fk := f.Addr().Interface()
  1593. if err := Unmarshal(e.Type, data[:size], fk); err != nil {
  1594. return err
  1595. }
  1596. data = data[size:]
  1597. }
  1598. if err != nil {
  1599. return err
  1600. }
  1601. }
  1602. return nil
  1603. }
  1604. // TypeInfo describes a Cassandra specific data type.
  1605. type TypeInfo interface {
  1606. Type() Type
  1607. Version() byte
  1608. Custom() string
  1609. // New creates a pointer to an empty version of whatever type
  1610. // is referenced by the TypeInfo receiver
  1611. New() interface{}
  1612. }
  1613. type NativeType struct {
  1614. proto byte
  1615. typ Type
  1616. custom string // only used for TypeCustom
  1617. }
  1618. func (t NativeType) New() interface{} {
  1619. return reflect.New(goType(t)).Interface()
  1620. }
  1621. func (s NativeType) Type() Type {
  1622. return s.typ
  1623. }
  1624. func (s NativeType) Version() byte {
  1625. return s.proto
  1626. }
  1627. func (s NativeType) Custom() string {
  1628. return s.custom
  1629. }
  1630. func (s NativeType) String() string {
  1631. switch s.typ {
  1632. case TypeCustom:
  1633. return fmt.Sprintf("%s(%s)", s.typ, s.custom)
  1634. default:
  1635. return s.typ.String()
  1636. }
  1637. }
  1638. type CollectionType struct {
  1639. NativeType
  1640. Key TypeInfo // only used for TypeMap
  1641. Elem TypeInfo // only used for TypeMap, TypeList and TypeSet
  1642. }
  1643. func (t CollectionType) New() interface{} {
  1644. return reflect.New(goType(t)).Interface()
  1645. }
  1646. func (c CollectionType) String() string {
  1647. switch c.typ {
  1648. case TypeMap:
  1649. return fmt.Sprintf("%s(%s, %s)", c.typ, c.Key, c.Elem)
  1650. case TypeList, TypeSet:
  1651. return fmt.Sprintf("%s(%s)", c.typ, c.Elem)
  1652. case TypeCustom:
  1653. return fmt.Sprintf("%s(%s)", c.typ, c.custom)
  1654. default:
  1655. return c.typ.String()
  1656. }
  1657. }
  1658. type TupleTypeInfo struct {
  1659. NativeType
  1660. Elems []TypeInfo
  1661. }
  1662. func (t TupleTypeInfo) New() interface{} {
  1663. return reflect.New(goType(t)).Interface()
  1664. }
  1665. type UDTField struct {
  1666. Name string
  1667. Type TypeInfo
  1668. }
  1669. type UDTTypeInfo struct {
  1670. NativeType
  1671. KeySpace string
  1672. Name string
  1673. Elements []UDTField
  1674. }
  1675. func (u UDTTypeInfo) New() interface{} {
  1676. return reflect.New(goType(u)).Interface()
  1677. }
  1678. func (u UDTTypeInfo) String() string {
  1679. buf := &bytes.Buffer{}
  1680. fmt.Fprintf(buf, "%s.%s{", u.KeySpace, u.Name)
  1681. first := true
  1682. for _, e := range u.Elements {
  1683. if !first {
  1684. fmt.Fprint(buf, ",")
  1685. } else {
  1686. first = false
  1687. }
  1688. fmt.Fprintf(buf, "%s=%v", e.Name, e.Type)
  1689. }
  1690. fmt.Fprint(buf, "}")
  1691. return buf.String()
  1692. }
  1693. // String returns a human readable name for the Cassandra datatype
  1694. // described by t.
  1695. // Type is the identifier of a Cassandra internal datatype.
  1696. type Type int
  1697. const (
  1698. TypeCustom Type = 0x0000
  1699. TypeAscii Type = 0x0001
  1700. TypeBigInt Type = 0x0002
  1701. TypeBlob Type = 0x0003
  1702. TypeBoolean Type = 0x0004
  1703. TypeCounter Type = 0x0005
  1704. TypeDecimal Type = 0x0006
  1705. TypeDouble Type = 0x0007
  1706. TypeFloat Type = 0x0008
  1707. TypeInt Type = 0x0009
  1708. TypeText Type = 0x000A
  1709. TypeTimestamp Type = 0x000B
  1710. TypeUUID Type = 0x000C
  1711. TypeVarchar Type = 0x000D
  1712. TypeVarint Type = 0x000E
  1713. TypeTimeUUID Type = 0x000F
  1714. TypeInet Type = 0x0010
  1715. TypeDate Type = 0x0011
  1716. TypeTime Type = 0x0012
  1717. TypeSmallInt Type = 0x0013
  1718. TypeTinyInt Type = 0x0014
  1719. TypeList Type = 0x0020
  1720. TypeMap Type = 0x0021
  1721. TypeSet Type = 0x0022
  1722. TypeUDT Type = 0x0030
  1723. TypeTuple Type = 0x0031
  1724. )
  1725. // String returns the name of the identifier.
  1726. func (t Type) String() string {
  1727. switch t {
  1728. case TypeCustom:
  1729. return "custom"
  1730. case TypeAscii:
  1731. return "ascii"
  1732. case TypeBigInt:
  1733. return "bigint"
  1734. case TypeBlob:
  1735. return "blob"
  1736. case TypeBoolean:
  1737. return "boolean"
  1738. case TypeCounter:
  1739. return "counter"
  1740. case TypeDecimal:
  1741. return "decimal"
  1742. case TypeDouble:
  1743. return "double"
  1744. case TypeFloat:
  1745. return "float"
  1746. case TypeInt:
  1747. return "int"
  1748. case TypeText:
  1749. return "text"
  1750. case TypeTimestamp:
  1751. return "timestamp"
  1752. case TypeUUID:
  1753. return "uuid"
  1754. case TypeVarchar:
  1755. return "varchar"
  1756. case TypeTimeUUID:
  1757. return "timeuuid"
  1758. case TypeInet:
  1759. return "inet"
  1760. case TypeDate:
  1761. return "date"
  1762. case TypeTime:
  1763. return "time"
  1764. case TypeSmallInt:
  1765. return "smallint"
  1766. case TypeTinyInt:
  1767. return "tinyint"
  1768. case TypeList:
  1769. return "list"
  1770. case TypeMap:
  1771. return "map"
  1772. case TypeSet:
  1773. return "set"
  1774. case TypeVarint:
  1775. return "varint"
  1776. case TypeTuple:
  1777. return "tuple"
  1778. default:
  1779. return fmt.Sprintf("unknown_type_%d", t)
  1780. }
  1781. }
  1782. type MarshalError string
  1783. func (m MarshalError) Error() string {
  1784. return string(m)
  1785. }
  1786. func marshalErrorf(format string, args ...interface{}) MarshalError {
  1787. return MarshalError(fmt.Sprintf(format, args...))
  1788. }
  1789. type UnmarshalError string
  1790. func (m UnmarshalError) Error() string {
  1791. return string(m)
  1792. }
  1793. func unmarshalErrorf(format string, args ...interface{}) UnmarshalError {
  1794. return UnmarshalError(fmt.Sprintf(format, args...))
  1795. }