marshal.go 57 KB

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