marshal.go 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  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. switch info.Type() {
  652. case TypeInt:
  653. *v = uint(unitVal) & 0xFFFFFFFF
  654. case TypeSmallInt:
  655. *v = uint(unitVal) & 0xFFFF
  656. case TypeTinyInt:
  657. *v = uint(unitVal) & 0xFF
  658. default:
  659. if ^uint(0) == math.MaxUint32 && (int64Val < 0 || int64Val > math.MaxUint32) {
  660. return unmarshalErrorf("unmarshal int: value %d out of range for %T", unitVal, *v)
  661. }
  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. switch info.Type() {
  688. case TypeInt:
  689. *v = uint32(int64Val) & 0xFFFFFFFF
  690. case TypeSmallInt:
  691. *v = uint32(int64Val) & 0xFFFF
  692. case TypeTinyInt:
  693. *v = uint32(int64Val) & 0xFF
  694. default:
  695. if int64Val < 0 || int64Val > math.MaxUint32 {
  696. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  697. }
  698. *v = uint32(int64Val) & 0xFFFFFFFF
  699. }
  700. return nil
  701. case *int16:
  702. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  703. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  704. }
  705. *v = int16(int64Val)
  706. return nil
  707. case *uint16:
  708. switch info.Type() {
  709. case TypeSmallInt:
  710. *v = uint16(int64Val) & 0xFFFF
  711. case TypeTinyInt:
  712. *v = uint16(int64Val) & 0xFF
  713. default:
  714. if int64Val < 0 || int64Val > math.MaxUint16 {
  715. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  716. }
  717. *v = uint16(int64Val) & 0xFFFF
  718. }
  719. return nil
  720. case *int8:
  721. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  722. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  723. }
  724. *v = int8(int64Val)
  725. return nil
  726. case *uint8:
  727. if info.Type() != TypeTinyInt && (int64Val < 0 || int64Val > math.MaxUint8) {
  728. return unmarshalErrorf("unmarshal int: value %d out of range for %T", int64Val, *v)
  729. }
  730. *v = uint8(int64Val) & 0xFF
  731. return nil
  732. case *big.Int:
  733. decBigInt2C(data, v)
  734. return nil
  735. case *string:
  736. *v = strconv.FormatInt(int64Val, 10)
  737. return nil
  738. }
  739. rv := reflect.ValueOf(value)
  740. if rv.Kind() != reflect.Ptr {
  741. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  742. }
  743. rv = rv.Elem()
  744. switch rv.Type().Kind() {
  745. case reflect.Int:
  746. if ^uint(0) == math.MaxUint32 && (int64Val < math.MinInt32 || int64Val > math.MaxInt32) {
  747. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  748. }
  749. rv.SetInt(int64Val)
  750. return nil
  751. case reflect.Int64:
  752. rv.SetInt(int64Val)
  753. return nil
  754. case reflect.Int32:
  755. if int64Val < math.MinInt32 || int64Val > math.MaxInt32 {
  756. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  757. }
  758. rv.SetInt(int64Val)
  759. return nil
  760. case reflect.Int16:
  761. if int64Val < math.MinInt16 || int64Val > math.MaxInt16 {
  762. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  763. }
  764. rv.SetInt(int64Val)
  765. return nil
  766. case reflect.Int8:
  767. if int64Val < math.MinInt8 || int64Val > math.MaxInt8 {
  768. return unmarshalErrorf("unmarshal int: value %d out of range", int64Val)
  769. }
  770. rv.SetInt(int64Val)
  771. return nil
  772. case reflect.Uint:
  773. unitVal := uint64(int64Val)
  774. switch info.Type() {
  775. case TypeInt:
  776. rv.SetUint(unitVal & 0xFFFFFFFF)
  777. case TypeSmallInt:
  778. rv.SetUint(unitVal & 0xFFFF)
  779. case TypeTinyInt:
  780. rv.SetUint(unitVal & 0xFF)
  781. default:
  782. if ^uint(0) == math.MaxUint32 && (int64Val < 0 || int64Val > math.MaxUint32) {
  783. return unmarshalErrorf("unmarshal int: value %d out of range for %s", unitVal, rv.Type())
  784. }
  785. rv.SetUint(unitVal)
  786. }
  787. return nil
  788. case reflect.Uint64:
  789. unitVal := uint64(int64Val)
  790. switch info.Type() {
  791. case TypeInt:
  792. rv.SetUint(unitVal & 0xFFFFFFFF)
  793. case TypeSmallInt:
  794. rv.SetUint(unitVal & 0xFFFF)
  795. case TypeTinyInt:
  796. rv.SetUint(unitVal & 0xFF)
  797. default:
  798. rv.SetUint(unitVal)
  799. }
  800. return nil
  801. case reflect.Uint32:
  802. unitVal := uint64(int64Val)
  803. switch info.Type() {
  804. case TypeInt:
  805. rv.SetUint(unitVal & 0xFFFFFFFF)
  806. case TypeSmallInt:
  807. rv.SetUint(unitVal & 0xFFFF)
  808. case TypeTinyInt:
  809. rv.SetUint(unitVal & 0xFF)
  810. default:
  811. if int64Val < 0 || int64Val > math.MaxUint32 {
  812. return unmarshalErrorf("unmarshal int: value %d out of range for %s", int64Val, rv.Type())
  813. }
  814. rv.SetUint(unitVal & 0xFFFFFFFF)
  815. }
  816. return nil
  817. case reflect.Uint16:
  818. unitVal := uint64(int64Val)
  819. switch info.Type() {
  820. case TypeSmallInt:
  821. rv.SetUint(unitVal & 0xFFFF)
  822. case TypeTinyInt:
  823. rv.SetUint(unitVal & 0xFF)
  824. default:
  825. if int64Val < 0 || int64Val > math.MaxUint16 {
  826. return unmarshalErrorf("unmarshal int: value %d out of range for %s", int64Val, rv.Type())
  827. }
  828. rv.SetUint(unitVal & 0xFFFF)
  829. }
  830. return nil
  831. case reflect.Uint8:
  832. if info.Type() != TypeTinyInt && (int64Val < 0 || int64Val > math.MaxUint8) {
  833. return unmarshalErrorf("unmarshal int: value %d out of range for %s", int64Val, rv.Type())
  834. }
  835. rv.SetUint(uint64(int64Val) & 0xff)
  836. return nil
  837. }
  838. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  839. }
  840. func decBigInt(data []byte) int64 {
  841. if len(data) != 8 {
  842. return 0
  843. }
  844. return int64(data[0])<<56 | int64(data[1])<<48 |
  845. int64(data[2])<<40 | int64(data[3])<<32 |
  846. int64(data[4])<<24 | int64(data[5])<<16 |
  847. int64(data[6])<<8 | int64(data[7])
  848. }
  849. func marshalBool(info TypeInfo, value interface{}) ([]byte, error) {
  850. switch v := value.(type) {
  851. case Marshaler:
  852. return v.MarshalCQL(info)
  853. case unsetColumn:
  854. return nil, nil
  855. case bool:
  856. return encBool(v), nil
  857. }
  858. if value == nil {
  859. return nil, nil
  860. }
  861. rv := reflect.ValueOf(value)
  862. switch rv.Type().Kind() {
  863. case reflect.Bool:
  864. return encBool(rv.Bool()), nil
  865. }
  866. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  867. }
  868. func encBool(v bool) []byte {
  869. if v {
  870. return []byte{1}
  871. }
  872. return []byte{0}
  873. }
  874. func unmarshalBool(info TypeInfo, data []byte, value interface{}) error {
  875. switch v := value.(type) {
  876. case Unmarshaler:
  877. return v.UnmarshalCQL(info, data)
  878. case *bool:
  879. *v = decBool(data)
  880. return nil
  881. }
  882. rv := reflect.ValueOf(value)
  883. if rv.Kind() != reflect.Ptr {
  884. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  885. }
  886. rv = rv.Elem()
  887. switch rv.Type().Kind() {
  888. case reflect.Bool:
  889. rv.SetBool(decBool(data))
  890. return nil
  891. }
  892. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  893. }
  894. func decBool(v []byte) bool {
  895. if len(v) == 0 {
  896. return false
  897. }
  898. return v[0] != 0
  899. }
  900. func marshalFloat(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 float32:
  907. return encInt(int32(math.Float32bits(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.Float32:
  915. return encInt(int32(math.Float32bits(float32(rv.Float())))), nil
  916. }
  917. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  918. }
  919. func unmarshalFloat(info TypeInfo, data []byte, value interface{}) error {
  920. switch v := value.(type) {
  921. case Unmarshaler:
  922. return v.UnmarshalCQL(info, data)
  923. case *float32:
  924. *v = math.Float32frombits(uint32(decInt(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.Float32:
  934. rv.SetFloat(float64(math.Float32frombits(uint32(decInt(data)))))
  935. return nil
  936. }
  937. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  938. }
  939. func marshalDouble(info TypeInfo, value interface{}) ([]byte, error) {
  940. switch v := value.(type) {
  941. case Marshaler:
  942. return v.MarshalCQL(info)
  943. case unsetColumn:
  944. return nil, nil
  945. case float64:
  946. return encBigInt(int64(math.Float64bits(v))), nil
  947. }
  948. if value == nil {
  949. return nil, nil
  950. }
  951. rv := reflect.ValueOf(value)
  952. switch rv.Type().Kind() {
  953. case reflect.Float64:
  954. return encBigInt(int64(math.Float64bits(rv.Float()))), nil
  955. }
  956. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  957. }
  958. func unmarshalDouble(info TypeInfo, data []byte, value interface{}) error {
  959. switch v := value.(type) {
  960. case Unmarshaler:
  961. return v.UnmarshalCQL(info, data)
  962. case *float64:
  963. *v = math.Float64frombits(uint64(decBigInt(data)))
  964. return nil
  965. }
  966. rv := reflect.ValueOf(value)
  967. if rv.Kind() != reflect.Ptr {
  968. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  969. }
  970. rv = rv.Elem()
  971. switch rv.Type().Kind() {
  972. case reflect.Float64:
  973. rv.SetFloat(math.Float64frombits(uint64(decBigInt(data))))
  974. return nil
  975. }
  976. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  977. }
  978. func marshalDecimal(info TypeInfo, value interface{}) ([]byte, error) {
  979. if value == nil {
  980. return nil, nil
  981. }
  982. switch v := value.(type) {
  983. case Marshaler:
  984. return v.MarshalCQL(info)
  985. case unsetColumn:
  986. return nil, nil
  987. case inf.Dec:
  988. unscaled := encBigInt2C(v.UnscaledBig())
  989. if unscaled == nil {
  990. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  991. }
  992. buf := make([]byte, 4+len(unscaled))
  993. copy(buf[0:4], encInt(int32(v.Scale())))
  994. copy(buf[4:], unscaled)
  995. return buf, nil
  996. }
  997. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  998. }
  999. func unmarshalDecimal(info TypeInfo, data []byte, value interface{}) error {
  1000. switch v := value.(type) {
  1001. case Unmarshaler:
  1002. return v.UnmarshalCQL(info, data)
  1003. case *inf.Dec:
  1004. scale := decInt(data[0:4])
  1005. unscaled := decBigInt2C(data[4:], nil)
  1006. *v = *inf.NewDecBig(unscaled, inf.Scale(scale))
  1007. return nil
  1008. }
  1009. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1010. }
  1011. // decBigInt2C sets the value of n to the big-endian two's complement
  1012. // value stored in the given data. If data[0]&80 != 0, the number
  1013. // is negative. If data is empty, the result will be 0.
  1014. func decBigInt2C(data []byte, n *big.Int) *big.Int {
  1015. if n == nil {
  1016. n = new(big.Int)
  1017. }
  1018. n.SetBytes(data)
  1019. if len(data) > 0 && data[0]&0x80 > 0 {
  1020. n.Sub(n, new(big.Int).Lsh(bigOne, uint(len(data))*8))
  1021. }
  1022. return n
  1023. }
  1024. // encBigInt2C returns the big-endian two's complement
  1025. // form of n.
  1026. func encBigInt2C(n *big.Int) []byte {
  1027. switch n.Sign() {
  1028. case 0:
  1029. return []byte{0}
  1030. case 1:
  1031. b := n.Bytes()
  1032. if b[0]&0x80 > 0 {
  1033. b = append([]byte{0}, b...)
  1034. }
  1035. return b
  1036. case -1:
  1037. length := uint(n.BitLen()/8+1) * 8
  1038. b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
  1039. // When the most significant bit is on a byte
  1040. // boundary, we can get some extra significant
  1041. // bits, so strip them off when that happens.
  1042. if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
  1043. b = b[1:]
  1044. }
  1045. return b
  1046. }
  1047. return nil
  1048. }
  1049. func marshalTime(info TypeInfo, value interface{}) ([]byte, error) {
  1050. switch v := value.(type) {
  1051. case Marshaler:
  1052. return v.MarshalCQL(info)
  1053. case unsetColumn:
  1054. return nil, nil
  1055. case int64:
  1056. return encBigInt(v), nil
  1057. case time.Duration:
  1058. return encBigInt(v.Nanoseconds()), nil
  1059. }
  1060. if value == nil {
  1061. return nil, nil
  1062. }
  1063. rv := reflect.ValueOf(value)
  1064. switch rv.Type().Kind() {
  1065. case reflect.Int64:
  1066. return encBigInt(rv.Int()), nil
  1067. }
  1068. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1069. }
  1070. func marshalTimestamp(info TypeInfo, value interface{}) ([]byte, error) {
  1071. switch v := value.(type) {
  1072. case Marshaler:
  1073. return v.MarshalCQL(info)
  1074. case unsetColumn:
  1075. return nil, nil
  1076. case int64:
  1077. return encBigInt(v), nil
  1078. case time.Time:
  1079. if v.IsZero() {
  1080. return []byte{}, nil
  1081. }
  1082. x := int64(v.UTC().Unix()*1e3) + int64(v.UTC().Nanosecond()/1e6)
  1083. return encBigInt(x), nil
  1084. }
  1085. if value == nil {
  1086. return nil, nil
  1087. }
  1088. rv := reflect.ValueOf(value)
  1089. switch rv.Type().Kind() {
  1090. case reflect.Int64:
  1091. return encBigInt(rv.Int()), nil
  1092. }
  1093. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1094. }
  1095. func unmarshalTime(info TypeInfo, data []byte, value interface{}) error {
  1096. switch v := value.(type) {
  1097. case Unmarshaler:
  1098. return v.UnmarshalCQL(info, data)
  1099. case *int64:
  1100. *v = decBigInt(data)
  1101. return nil
  1102. case *time.Duration:
  1103. *v = time.Duration(decBigInt(data))
  1104. return nil
  1105. }
  1106. rv := reflect.ValueOf(value)
  1107. if rv.Kind() != reflect.Ptr {
  1108. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1109. }
  1110. rv = rv.Elem()
  1111. switch rv.Type().Kind() {
  1112. case reflect.Int64:
  1113. rv.SetInt(decBigInt(data))
  1114. return nil
  1115. }
  1116. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1117. }
  1118. func unmarshalTimestamp(info TypeInfo, data []byte, value interface{}) error {
  1119. switch v := value.(type) {
  1120. case Unmarshaler:
  1121. return v.UnmarshalCQL(info, data)
  1122. case *int64:
  1123. *v = decBigInt(data)
  1124. return nil
  1125. case *time.Time:
  1126. if len(data) == 0 {
  1127. *v = time.Time{}
  1128. return nil
  1129. }
  1130. x := decBigInt(data)
  1131. sec := x / 1000
  1132. nsec := (x - sec*1000) * 1000000
  1133. *v = time.Unix(sec, nsec).In(time.UTC)
  1134. return nil
  1135. }
  1136. rv := reflect.ValueOf(value)
  1137. if rv.Kind() != reflect.Ptr {
  1138. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1139. }
  1140. rv = rv.Elem()
  1141. switch rv.Type().Kind() {
  1142. case reflect.Int64:
  1143. rv.SetInt(decBigInt(data))
  1144. return nil
  1145. }
  1146. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1147. }
  1148. func marshalDate(info TypeInfo, value interface{}) ([]byte, error) {
  1149. var timestamp int64
  1150. switch v := value.(type) {
  1151. case Marshaler:
  1152. return v.MarshalCQL(info)
  1153. case unsetColumn:
  1154. return nil, nil
  1155. case int64:
  1156. timestamp = v
  1157. x := timestamp/86400000 + int64(1<<31)
  1158. return encInt(int32(x)), nil
  1159. case time.Time:
  1160. if v.IsZero() {
  1161. return []byte{}, nil
  1162. }
  1163. timestamp = int64(v.UTC().Unix()*1e3) + int64(v.UTC().Nanosecond()/1e6)
  1164. x := timestamp/86400000 + int64(1<<31)
  1165. return encInt(int32(x)), nil
  1166. case *time.Time:
  1167. if v.IsZero() {
  1168. return []byte{}, nil
  1169. }
  1170. timestamp = int64(v.UTC().Unix()*1e3) + int64(v.UTC().Nanosecond()/1e6)
  1171. x := timestamp/86400000 + int64(1<<31)
  1172. return encInt(int32(x)), nil
  1173. case string:
  1174. if v == "" {
  1175. return []byte{}, nil
  1176. }
  1177. t, err := time.Parse("2006-01-02", v)
  1178. if err != nil {
  1179. return nil, marshalErrorf("can not marshal %T into %s, date layout must be '2006-01-02'", value, info)
  1180. }
  1181. timestamp = int64(t.UTC().Unix()*1e3) + int64(t.UTC().Nanosecond()/1e6)
  1182. x := timestamp/86400000 + int64(1<<31)
  1183. return encInt(int32(x)), nil
  1184. }
  1185. if value == nil {
  1186. return nil, nil
  1187. }
  1188. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1189. }
  1190. func unmarshalDate(info TypeInfo, data []byte, value interface{}) error {
  1191. switch v := value.(type) {
  1192. case Unmarshaler:
  1193. return v.UnmarshalCQL(info, data)
  1194. case *time.Time:
  1195. if len(data) == 0 {
  1196. *v = time.Time{}
  1197. return nil
  1198. }
  1199. var origin uint32 = 1 << 31
  1200. var current uint32 = binary.BigEndian.Uint32(data)
  1201. timestamp := (int64(current) - int64(origin)) * 86400000
  1202. *v = time.Unix(0, timestamp*int64(time.Millisecond)).In(time.UTC)
  1203. return nil
  1204. case *string:
  1205. if len(data) == 0 {
  1206. *v = ""
  1207. return nil
  1208. }
  1209. var origin uint32 = 1 << 31
  1210. var current uint32 = binary.BigEndian.Uint32(data)
  1211. timestamp := (int64(current) - int64(origin)) * 86400000
  1212. *v = time.Unix(0, timestamp*int64(time.Millisecond)).In(time.UTC).Format("2006-01-02")
  1213. return nil
  1214. }
  1215. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1216. }
  1217. func marshalDuration(info TypeInfo, value interface{}) ([]byte, error) {
  1218. switch v := value.(type) {
  1219. case Marshaler:
  1220. return v.MarshalCQL(info)
  1221. case unsetColumn:
  1222. return nil, nil
  1223. case int64:
  1224. return encVints(0, 0, v), nil
  1225. case time.Duration:
  1226. return encVints(0, 0, v.Nanoseconds()), nil
  1227. case string:
  1228. d, err := time.ParseDuration(v)
  1229. if err != nil {
  1230. return nil, err
  1231. }
  1232. return encVints(0, 0, d.Nanoseconds()), nil
  1233. case Duration:
  1234. return encVints(v.Months, v.Days, v.Nanoseconds), nil
  1235. }
  1236. if value == nil {
  1237. return nil, nil
  1238. }
  1239. rv := reflect.ValueOf(value)
  1240. switch rv.Type().Kind() {
  1241. case reflect.Int64:
  1242. return encBigInt(rv.Int()), nil
  1243. }
  1244. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1245. }
  1246. func unmarshalDuration(info TypeInfo, data []byte, value interface{}) error {
  1247. switch v := value.(type) {
  1248. case Unmarshaler:
  1249. return v.UnmarshalCQL(info, data)
  1250. case *Duration:
  1251. if len(data) == 0 {
  1252. *v = Duration{
  1253. Months: 0,
  1254. Days: 0,
  1255. Nanoseconds: 0,
  1256. }
  1257. return nil
  1258. }
  1259. months, days, nanos := decVints(data)
  1260. *v = Duration{
  1261. Months: months,
  1262. Days: days,
  1263. Nanoseconds: nanos,
  1264. }
  1265. return nil
  1266. }
  1267. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1268. }
  1269. func decVints(data []byte) (int32, int32, int64) {
  1270. month, i := decVint(data)
  1271. days, j := decVint(data[i:])
  1272. nanos, _ := decVint(data[i+j:])
  1273. return int32(month), int32(days), nanos
  1274. }
  1275. func decVint(data []byte) (int64, int) {
  1276. firstByte := data[0]
  1277. if firstByte&0x80 == 0 {
  1278. return decIntZigZag(uint64(firstByte)), 1
  1279. }
  1280. numBytes := bits.LeadingZeros32(uint32(^firstByte)) - 24
  1281. ret := uint64(firstByte & (0xff >> uint(numBytes)))
  1282. for i := 0; i < numBytes; i++ {
  1283. ret <<= 8
  1284. ret |= uint64(data[i+1] & 0xff)
  1285. }
  1286. return decIntZigZag(ret), numBytes + 1
  1287. }
  1288. func decIntZigZag(n uint64) int64 {
  1289. return int64((n >> 1) ^ -(n & 1))
  1290. }
  1291. func encIntZigZag(n int64) uint64 {
  1292. return uint64((n >> 63) ^ (n << 1))
  1293. }
  1294. func encVints(months int32, seconds int32, nanos int64) []byte {
  1295. buf := append(encVint(int64(months)), encVint(int64(seconds))...)
  1296. return append(buf, encVint(nanos)...)
  1297. }
  1298. func encVint(v int64) []byte {
  1299. vEnc := encIntZigZag(v)
  1300. lead0 := bits.LeadingZeros64(vEnc)
  1301. numBytes := (639 - lead0*9) >> 6
  1302. // It can be 1 or 0 is v ==0
  1303. if numBytes <= 1 {
  1304. return []byte{byte(vEnc)}
  1305. }
  1306. extraBytes := numBytes - 1
  1307. var buf = make([]byte, numBytes)
  1308. for i := extraBytes; i >= 0; i-- {
  1309. buf[i] = byte(vEnc)
  1310. vEnc >>= 8
  1311. }
  1312. buf[0] |= byte(^(0xff >> uint(extraBytes)))
  1313. return buf
  1314. }
  1315. func writeCollectionSize(info CollectionType, n int, buf *bytes.Buffer) error {
  1316. if info.proto > protoVersion2 {
  1317. if n > math.MaxInt32 {
  1318. return marshalErrorf("marshal: collection too large")
  1319. }
  1320. buf.WriteByte(byte(n >> 24))
  1321. buf.WriteByte(byte(n >> 16))
  1322. buf.WriteByte(byte(n >> 8))
  1323. buf.WriteByte(byte(n))
  1324. } else {
  1325. if n > math.MaxUint16 {
  1326. return marshalErrorf("marshal: collection too large")
  1327. }
  1328. buf.WriteByte(byte(n >> 8))
  1329. buf.WriteByte(byte(n))
  1330. }
  1331. return nil
  1332. }
  1333. func marshalList(info TypeInfo, value interface{}) ([]byte, error) {
  1334. listInfo, ok := info.(CollectionType)
  1335. if !ok {
  1336. return nil, marshalErrorf("marshal: can not marshal non collection type into list")
  1337. }
  1338. if value == nil {
  1339. return nil, nil
  1340. } else if _, ok := value.(unsetColumn); ok {
  1341. return nil, nil
  1342. }
  1343. rv := reflect.ValueOf(value)
  1344. t := rv.Type()
  1345. k := t.Kind()
  1346. if k == reflect.Slice && rv.IsNil() {
  1347. return nil, nil
  1348. }
  1349. switch k {
  1350. case reflect.Slice, reflect.Array:
  1351. buf := &bytes.Buffer{}
  1352. n := rv.Len()
  1353. if err := writeCollectionSize(listInfo, n, buf); err != nil {
  1354. return nil, err
  1355. }
  1356. for i := 0; i < n; i++ {
  1357. item, err := Marshal(listInfo.Elem, rv.Index(i).Interface())
  1358. if err != nil {
  1359. return nil, err
  1360. }
  1361. if err := writeCollectionSize(listInfo, len(item), buf); err != nil {
  1362. return nil, err
  1363. }
  1364. buf.Write(item)
  1365. }
  1366. return buf.Bytes(), nil
  1367. case reflect.Map:
  1368. elem := t.Elem()
  1369. if elem.Kind() == reflect.Struct && elem.NumField() == 0 {
  1370. rkeys := rv.MapKeys()
  1371. keys := make([]interface{}, len(rkeys))
  1372. for i := 0; i < len(keys); i++ {
  1373. keys[i] = rkeys[i].Interface()
  1374. }
  1375. return marshalList(listInfo, keys)
  1376. }
  1377. }
  1378. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1379. }
  1380. func readCollectionSize(info CollectionType, data []byte) (size, read int, err error) {
  1381. if info.proto > protoVersion2 {
  1382. if len(data) < 4 {
  1383. return 0, 0, unmarshalErrorf("unmarshal list: unexpected eof")
  1384. }
  1385. size = int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1386. read = 4
  1387. } else {
  1388. if len(data) < 2 {
  1389. return 0, 0, unmarshalErrorf("unmarshal list: unexpected eof")
  1390. }
  1391. size = int(data[0])<<8 | int(data[1])
  1392. read = 2
  1393. }
  1394. return
  1395. }
  1396. func unmarshalList(info TypeInfo, data []byte, value interface{}) error {
  1397. listInfo, ok := info.(CollectionType)
  1398. if !ok {
  1399. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into list")
  1400. }
  1401. rv := reflect.ValueOf(value)
  1402. if rv.Kind() != reflect.Ptr {
  1403. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1404. }
  1405. rv = rv.Elem()
  1406. t := rv.Type()
  1407. k := t.Kind()
  1408. switch k {
  1409. case reflect.Slice, reflect.Array:
  1410. if data == nil {
  1411. if k == reflect.Array {
  1412. return unmarshalErrorf("unmarshal list: can not store nil in array value")
  1413. }
  1414. if rv.IsNil() {
  1415. return nil
  1416. }
  1417. rv.Set(reflect.Zero(t))
  1418. return nil
  1419. }
  1420. n, p, err := readCollectionSize(listInfo, data)
  1421. if err != nil {
  1422. return err
  1423. }
  1424. data = data[p:]
  1425. if k == reflect.Array {
  1426. if rv.Len() != n {
  1427. return unmarshalErrorf("unmarshal list: array with wrong size")
  1428. }
  1429. } else {
  1430. rv.Set(reflect.MakeSlice(t, n, n))
  1431. }
  1432. for i := 0; i < n; i++ {
  1433. m, p, err := readCollectionSize(listInfo, data)
  1434. if err != nil {
  1435. return err
  1436. }
  1437. data = data[p:]
  1438. if err := Unmarshal(listInfo.Elem, data[:m], rv.Index(i).Addr().Interface()); err != nil {
  1439. return err
  1440. }
  1441. data = data[m:]
  1442. }
  1443. return nil
  1444. }
  1445. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1446. }
  1447. func marshalMap(info TypeInfo, value interface{}) ([]byte, error) {
  1448. mapInfo, ok := info.(CollectionType)
  1449. if !ok {
  1450. return nil, marshalErrorf("marshal: can not marshal none collection type into map")
  1451. }
  1452. if value == nil {
  1453. return nil, nil
  1454. } else if _, ok := value.(unsetColumn); ok {
  1455. return nil, nil
  1456. }
  1457. rv := reflect.ValueOf(value)
  1458. t := rv.Type()
  1459. if t.Kind() != reflect.Map {
  1460. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1461. }
  1462. if rv.IsNil() {
  1463. return nil, nil
  1464. }
  1465. buf := &bytes.Buffer{}
  1466. n := rv.Len()
  1467. if err := writeCollectionSize(mapInfo, n, buf); err != nil {
  1468. return nil, err
  1469. }
  1470. keys := rv.MapKeys()
  1471. for _, key := range keys {
  1472. item, err := Marshal(mapInfo.Key, key.Interface())
  1473. if err != nil {
  1474. return nil, err
  1475. }
  1476. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  1477. return nil, err
  1478. }
  1479. buf.Write(item)
  1480. item, err = Marshal(mapInfo.Elem, rv.MapIndex(key).Interface())
  1481. if err != nil {
  1482. return nil, err
  1483. }
  1484. if err := writeCollectionSize(mapInfo, len(item), buf); err != nil {
  1485. return nil, err
  1486. }
  1487. buf.Write(item)
  1488. }
  1489. return buf.Bytes(), nil
  1490. }
  1491. func unmarshalMap(info TypeInfo, data []byte, value interface{}) error {
  1492. mapInfo, ok := info.(CollectionType)
  1493. if !ok {
  1494. return unmarshalErrorf("unmarshal: can not unmarshal none collection type into map")
  1495. }
  1496. rv := reflect.ValueOf(value)
  1497. if rv.Kind() != reflect.Ptr {
  1498. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1499. }
  1500. rv = rv.Elem()
  1501. t := rv.Type()
  1502. if t.Kind() != reflect.Map {
  1503. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1504. }
  1505. if data == nil {
  1506. rv.Set(reflect.Zero(t))
  1507. return nil
  1508. }
  1509. rv.Set(reflect.MakeMap(t))
  1510. n, p, err := readCollectionSize(mapInfo, data)
  1511. if err != nil {
  1512. return err
  1513. }
  1514. data = data[p:]
  1515. for i := 0; i < n; i++ {
  1516. m, p, err := readCollectionSize(mapInfo, data)
  1517. if err != nil {
  1518. return err
  1519. }
  1520. data = data[p:]
  1521. key := reflect.New(t.Key())
  1522. if err := Unmarshal(mapInfo.Key, data[:m], key.Interface()); err != nil {
  1523. return err
  1524. }
  1525. data = data[m:]
  1526. m, p, err = readCollectionSize(mapInfo, data)
  1527. if err != nil {
  1528. return err
  1529. }
  1530. data = data[p:]
  1531. val := reflect.New(t.Elem())
  1532. if err := Unmarshal(mapInfo.Elem, data[:m], val.Interface()); err != nil {
  1533. return err
  1534. }
  1535. data = data[m:]
  1536. rv.SetMapIndex(key.Elem(), val.Elem())
  1537. }
  1538. return nil
  1539. }
  1540. func marshalUUID(info TypeInfo, value interface{}) ([]byte, error) {
  1541. switch val := value.(type) {
  1542. case unsetColumn:
  1543. return nil, nil
  1544. case UUID:
  1545. return val.Bytes(), nil
  1546. case []byte:
  1547. if len(val) != 16 {
  1548. return nil, marshalErrorf("can not marshal []byte %d bytes long into %s, must be exactly 16 bytes long", len(val), info)
  1549. }
  1550. return val, nil
  1551. case string:
  1552. b, err := ParseUUID(val)
  1553. if err != nil {
  1554. return nil, err
  1555. }
  1556. return b[:], nil
  1557. }
  1558. if value == nil {
  1559. return nil, nil
  1560. }
  1561. return nil, marshalErrorf("can not marshal %T into %s", value, info)
  1562. }
  1563. func unmarshalUUID(info TypeInfo, data []byte, value interface{}) error {
  1564. if data == nil || len(data) == 0 {
  1565. switch v := value.(type) {
  1566. case *string:
  1567. *v = ""
  1568. case *[]byte:
  1569. *v = nil
  1570. case *UUID:
  1571. *v = UUID{}
  1572. default:
  1573. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1574. }
  1575. return nil
  1576. }
  1577. u, err := UUIDFromBytes(data)
  1578. if err != nil {
  1579. return unmarshalErrorf("Unable to parse UUID: %s", err)
  1580. }
  1581. switch v := value.(type) {
  1582. case *string:
  1583. *v = u.String()
  1584. return nil
  1585. case *[]byte:
  1586. *v = u[:]
  1587. return nil
  1588. case *UUID:
  1589. *v = u
  1590. return nil
  1591. }
  1592. return unmarshalErrorf("can not unmarshal X %s into %T", info, value)
  1593. }
  1594. func unmarshalTimeUUID(info TypeInfo, data []byte, value interface{}) error {
  1595. switch v := value.(type) {
  1596. case Unmarshaler:
  1597. return v.UnmarshalCQL(info, data)
  1598. case *time.Time:
  1599. id, err := UUIDFromBytes(data)
  1600. if err != nil {
  1601. return err
  1602. } else if id.Version() != 1 {
  1603. return unmarshalErrorf("invalid timeuuid")
  1604. }
  1605. *v = id.Time()
  1606. return nil
  1607. default:
  1608. return unmarshalUUID(info, data, value)
  1609. }
  1610. }
  1611. func marshalInet(info TypeInfo, value interface{}) ([]byte, error) {
  1612. // we return either the 4 or 16 byte representation of an
  1613. // ip address here otherwise the db value will be prefixed
  1614. // with the remaining byte values e.g. ::ffff:127.0.0.1 and not 127.0.0.1
  1615. switch val := value.(type) {
  1616. case unsetColumn:
  1617. return nil, nil
  1618. case net.IP:
  1619. t := val.To4()
  1620. if t == nil {
  1621. return val.To16(), nil
  1622. }
  1623. return t, nil
  1624. case string:
  1625. b := net.ParseIP(val)
  1626. if b != nil {
  1627. t := b.To4()
  1628. if t == nil {
  1629. return b.To16(), nil
  1630. }
  1631. return t, nil
  1632. }
  1633. return nil, marshalErrorf("cannot marshal. invalid ip string %s", val)
  1634. }
  1635. if value == nil {
  1636. return nil, nil
  1637. }
  1638. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1639. }
  1640. func unmarshalInet(info TypeInfo, data []byte, value interface{}) error {
  1641. switch v := value.(type) {
  1642. case Unmarshaler:
  1643. return v.UnmarshalCQL(info, data)
  1644. case *net.IP:
  1645. if x := len(data); !(x == 4 || x == 16) {
  1646. return unmarshalErrorf("cannot unmarshal %s into %T: invalid sized IP: got %d bytes not 4 or 16", info, value, x)
  1647. }
  1648. buf := copyBytes(data)
  1649. ip := net.IP(buf)
  1650. if v4 := ip.To4(); v4 != nil {
  1651. *v = v4
  1652. return nil
  1653. }
  1654. *v = ip
  1655. return nil
  1656. case *string:
  1657. if len(data) == 0 {
  1658. *v = ""
  1659. return nil
  1660. }
  1661. ip := net.IP(data)
  1662. if v4 := ip.To4(); v4 != nil {
  1663. *v = v4.String()
  1664. return nil
  1665. }
  1666. *v = ip.String()
  1667. return nil
  1668. }
  1669. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1670. }
  1671. func marshalTuple(info TypeInfo, value interface{}) ([]byte, error) {
  1672. tuple := info.(TupleTypeInfo)
  1673. switch v := value.(type) {
  1674. case unsetColumn:
  1675. return nil, unmarshalErrorf("Invalid request: UnsetValue is unsupported for tuples")
  1676. case []interface{}:
  1677. if len(v) != len(tuple.Elems) {
  1678. return nil, unmarshalErrorf("cannont marshal tuple: wrong number of elements")
  1679. }
  1680. var buf []byte
  1681. for i, elem := range v {
  1682. data, err := Marshal(tuple.Elems[i], elem)
  1683. if err != nil {
  1684. return nil, err
  1685. }
  1686. n := len(data)
  1687. buf = appendInt(buf, int32(n))
  1688. buf = append(buf, data...)
  1689. }
  1690. return buf, nil
  1691. }
  1692. rv := reflect.ValueOf(value)
  1693. t := rv.Type()
  1694. k := t.Kind()
  1695. switch k {
  1696. case reflect.Struct:
  1697. if v := t.NumField(); v != len(tuple.Elems) {
  1698. return nil, marshalErrorf("can not marshal tuple into struct %v, not enough fields have %d need %d", t, v, len(tuple.Elems))
  1699. }
  1700. var buf []byte
  1701. for i, elem := range tuple.Elems {
  1702. data, err := Marshal(elem, rv.Field(i).Interface())
  1703. if err != nil {
  1704. return nil, err
  1705. }
  1706. n := len(data)
  1707. buf = appendInt(buf, int32(n))
  1708. buf = append(buf, data...)
  1709. }
  1710. return buf, nil
  1711. case reflect.Slice, reflect.Array:
  1712. size := rv.Len()
  1713. if size != len(tuple.Elems) {
  1714. return nil, marshalErrorf("can not marshal tuple into %v of length %d need %d elements", k, size, len(tuple.Elems))
  1715. }
  1716. var buf []byte
  1717. for i, elem := range tuple.Elems {
  1718. data, err := Marshal(elem, rv.Index(i).Interface())
  1719. if err != nil {
  1720. return nil, err
  1721. }
  1722. n := len(data)
  1723. buf = appendInt(buf, int32(n))
  1724. buf = append(buf, data...)
  1725. }
  1726. return buf, nil
  1727. }
  1728. return nil, marshalErrorf("cannot marshal %T into %s", value, tuple)
  1729. }
  1730. func readBytes(p []byte) ([]byte, []byte) {
  1731. // TODO: really should use a framer
  1732. size := readInt(p)
  1733. p = p[4:]
  1734. if size < 0 {
  1735. return nil, p
  1736. }
  1737. return p[:size], p[size:]
  1738. }
  1739. // currently only support unmarshal into a list of values, this makes it possible
  1740. // to support tuples without changing the query API. In the future this can be extend
  1741. // to allow unmarshalling into custom tuple types.
  1742. func unmarshalTuple(info TypeInfo, data []byte, value interface{}) error {
  1743. if v, ok := value.(Unmarshaler); ok {
  1744. return v.UnmarshalCQL(info, data)
  1745. }
  1746. tuple := info.(TupleTypeInfo)
  1747. switch v := value.(type) {
  1748. case []interface{}:
  1749. for i, elem := range tuple.Elems {
  1750. // each element inside data is a [bytes]
  1751. var p []byte
  1752. p, data = readBytes(data)
  1753. err := Unmarshal(elem, p, v[i])
  1754. if err != nil {
  1755. return err
  1756. }
  1757. }
  1758. return nil
  1759. }
  1760. rv := reflect.ValueOf(value)
  1761. if rv.Kind() != reflect.Ptr {
  1762. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1763. }
  1764. rv = rv.Elem()
  1765. t := rv.Type()
  1766. k := t.Kind()
  1767. switch k {
  1768. case reflect.Struct:
  1769. if v := t.NumField(); v != len(tuple.Elems) {
  1770. return unmarshalErrorf("can not unmarshal tuple into struct %v, not enough fields have %d need %d", t, v, len(tuple.Elems))
  1771. }
  1772. for i, elem := range tuple.Elems {
  1773. m := readInt(data)
  1774. data = data[4:]
  1775. v := elem.New()
  1776. if err := Unmarshal(elem, data[:m], v); err != nil {
  1777. return err
  1778. }
  1779. rv.Field(i).Set(reflect.ValueOf(v).Elem())
  1780. data = data[m:]
  1781. }
  1782. return nil
  1783. case reflect.Slice, reflect.Array:
  1784. if k == reflect.Array {
  1785. size := rv.Len()
  1786. if size != len(tuple.Elems) {
  1787. return unmarshalErrorf("can not unmarshal tuple into array of length %d need %d elements", size, len(tuple.Elems))
  1788. }
  1789. } else {
  1790. rv.Set(reflect.MakeSlice(t, len(tuple.Elems), len(tuple.Elems)))
  1791. }
  1792. for i, elem := range tuple.Elems {
  1793. m := readInt(data)
  1794. data = data[4:]
  1795. v := elem.New()
  1796. if err := Unmarshal(elem, data[:m], v); err != nil {
  1797. return err
  1798. }
  1799. rv.Index(i).Set(reflect.ValueOf(v).Elem())
  1800. data = data[m:]
  1801. }
  1802. return nil
  1803. }
  1804. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1805. }
  1806. // UDTMarshaler is an interface which should be implemented by users wishing to
  1807. // handle encoding UDT types to sent to Cassandra. Note: due to current implentations
  1808. // methods defined for this interface must be value receivers not pointer receivers.
  1809. type UDTMarshaler interface {
  1810. // MarshalUDT will be called for each field in the the UDT returned by Cassandra,
  1811. // the implementor should marshal the type to return by for example calling
  1812. // Marshal.
  1813. MarshalUDT(name string, info TypeInfo) ([]byte, error)
  1814. }
  1815. // UDTUnmarshaler should be implemented by users wanting to implement custom
  1816. // UDT unmarshaling.
  1817. type UDTUnmarshaler interface {
  1818. // UnmarshalUDT will be called for each field in the UDT return by Cassandra,
  1819. // the implementor should unmarshal the data into the value of their chosing,
  1820. // for example by calling Unmarshal.
  1821. UnmarshalUDT(name string, info TypeInfo, data []byte) error
  1822. }
  1823. func marshalUDT(info TypeInfo, value interface{}) ([]byte, error) {
  1824. udt := info.(UDTTypeInfo)
  1825. switch v := value.(type) {
  1826. case Marshaler:
  1827. return v.MarshalCQL(info)
  1828. case unsetColumn:
  1829. return nil, unmarshalErrorf("Invalid request: UnsetValue is unsupported for user defined types")
  1830. case UDTMarshaler:
  1831. var buf []byte
  1832. for _, e := range udt.Elements {
  1833. data, err := v.MarshalUDT(e.Name, e.Type)
  1834. if err != nil {
  1835. return nil, err
  1836. }
  1837. buf = appendBytes(buf, data)
  1838. }
  1839. return buf, nil
  1840. case map[string]interface{}:
  1841. var buf []byte
  1842. for _, e := range udt.Elements {
  1843. val, ok := v[e.Name]
  1844. if !ok {
  1845. continue
  1846. }
  1847. data, err := Marshal(e.Type, val)
  1848. if err != nil {
  1849. return nil, err
  1850. }
  1851. buf = appendBytes(buf, data)
  1852. }
  1853. return buf, nil
  1854. }
  1855. k := reflect.ValueOf(value)
  1856. if k.Kind() == reflect.Ptr {
  1857. if k.IsNil() {
  1858. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1859. }
  1860. k = k.Elem()
  1861. }
  1862. if k.Kind() != reflect.Struct || !k.IsValid() {
  1863. return nil, marshalErrorf("cannot marshal %T into %s", value, info)
  1864. }
  1865. fields := make(map[string]reflect.Value)
  1866. t := reflect.TypeOf(value)
  1867. for i := 0; i < t.NumField(); i++ {
  1868. sf := t.Field(i)
  1869. if tag := sf.Tag.Get("cql"); tag != "" {
  1870. fields[tag] = k.Field(i)
  1871. }
  1872. }
  1873. var buf []byte
  1874. for _, e := range udt.Elements {
  1875. f, ok := fields[e.Name]
  1876. if !ok {
  1877. f = k.FieldByName(e.Name)
  1878. }
  1879. var data []byte
  1880. if f.IsValid() && f.CanInterface() {
  1881. var err error
  1882. data, err = Marshal(e.Type, f.Interface())
  1883. if err != nil {
  1884. return nil, err
  1885. }
  1886. }
  1887. buf = appendBytes(buf, data)
  1888. }
  1889. return buf, nil
  1890. }
  1891. func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
  1892. switch v := value.(type) {
  1893. case Unmarshaler:
  1894. return v.UnmarshalCQL(info, data)
  1895. case UDTUnmarshaler:
  1896. udt := info.(UDTTypeInfo)
  1897. for _, e := range udt.Elements {
  1898. if len(data) == 0 {
  1899. return nil
  1900. }
  1901. var p []byte
  1902. p, data = readBytes(data)
  1903. if err := v.UnmarshalUDT(e.Name, e.Type, p); err != nil {
  1904. return err
  1905. }
  1906. }
  1907. return nil
  1908. case *map[string]interface{}:
  1909. udt := info.(UDTTypeInfo)
  1910. rv := reflect.ValueOf(value)
  1911. if rv.Kind() != reflect.Ptr {
  1912. return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
  1913. }
  1914. rv = rv.Elem()
  1915. t := rv.Type()
  1916. if t.Kind() != reflect.Map {
  1917. return unmarshalErrorf("can not unmarshal %s into %T", info, value)
  1918. } else if data == nil {
  1919. rv.Set(reflect.Zero(t))
  1920. return nil
  1921. }
  1922. rv.Set(reflect.MakeMap(t))
  1923. m := *v
  1924. for _, e := range udt.Elements {
  1925. if len(data) == 0 {
  1926. return nil
  1927. }
  1928. val := reflect.New(goType(e.Type))
  1929. var p []byte
  1930. p, data = readBytes(data)
  1931. if err := Unmarshal(e.Type, p, val.Interface()); err != nil {
  1932. return err
  1933. }
  1934. m[e.Name] = val.Elem().Interface()
  1935. }
  1936. return nil
  1937. }
  1938. k := reflect.ValueOf(value).Elem()
  1939. if k.Kind() != reflect.Struct || !k.IsValid() {
  1940. return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
  1941. }
  1942. if len(data) == 0 {
  1943. if k.CanSet() {
  1944. k.Set(reflect.Zero(k.Type()))
  1945. }
  1946. return nil
  1947. }
  1948. t := k.Type()
  1949. fields := make(map[string]reflect.Value, t.NumField())
  1950. for i := 0; i < t.NumField(); i++ {
  1951. sf := t.Field(i)
  1952. if tag := sf.Tag.Get("cql"); tag != "" {
  1953. fields[tag] = k.Field(i)
  1954. }
  1955. }
  1956. udt := info.(UDTTypeInfo)
  1957. for _, e := range udt.Elements {
  1958. if len(data) < 4 {
  1959. // UDT def does not match the column value
  1960. return nil
  1961. }
  1962. var p []byte
  1963. p, data = readBytes(data)
  1964. f, ok := fields[e.Name]
  1965. if !ok {
  1966. f = k.FieldByName(e.Name)
  1967. if f == emptyValue {
  1968. // skip fields which exist in the UDT but not in
  1969. // the struct passed in
  1970. continue
  1971. }
  1972. }
  1973. if !f.IsValid() || !f.CanAddr() {
  1974. return unmarshalErrorf("cannot unmarshal %s into %T: field %v is not valid", info, value, e.Name)
  1975. }
  1976. fk := f.Addr().Interface()
  1977. if err := Unmarshal(e.Type, p, fk); err != nil {
  1978. return err
  1979. }
  1980. }
  1981. return nil
  1982. }
  1983. // TypeInfo describes a Cassandra specific data type.
  1984. type TypeInfo interface {
  1985. Type() Type
  1986. Version() byte
  1987. Custom() string
  1988. // New creates a pointer to an empty version of whatever type
  1989. // is referenced by the TypeInfo receiver
  1990. New() interface{}
  1991. }
  1992. type NativeType struct {
  1993. proto byte
  1994. typ Type
  1995. custom string // only used for TypeCustom
  1996. }
  1997. func NewNativeType(proto byte, typ Type, custom string) NativeType {
  1998. return NativeType{proto, typ, custom}
  1999. }
  2000. func (t NativeType) New() interface{} {
  2001. return reflect.New(goType(t)).Interface()
  2002. }
  2003. func (s NativeType) Type() Type {
  2004. return s.typ
  2005. }
  2006. func (s NativeType) Version() byte {
  2007. return s.proto
  2008. }
  2009. func (s NativeType) Custom() string {
  2010. return s.custom
  2011. }
  2012. func (s NativeType) String() string {
  2013. switch s.typ {
  2014. case TypeCustom:
  2015. return fmt.Sprintf("%s(%s)", s.typ, s.custom)
  2016. default:
  2017. return s.typ.String()
  2018. }
  2019. }
  2020. type CollectionType struct {
  2021. NativeType
  2022. Key TypeInfo // only used for TypeMap
  2023. Elem TypeInfo // only used for TypeMap, TypeList and TypeSet
  2024. }
  2025. func (t CollectionType) New() interface{} {
  2026. return reflect.New(goType(t)).Interface()
  2027. }
  2028. func (c CollectionType) String() string {
  2029. switch c.typ {
  2030. case TypeMap:
  2031. return fmt.Sprintf("%s(%s, %s)", c.typ, c.Key, c.Elem)
  2032. case TypeList, TypeSet:
  2033. return fmt.Sprintf("%s(%s)", c.typ, c.Elem)
  2034. case TypeCustom:
  2035. return fmt.Sprintf("%s(%s)", c.typ, c.custom)
  2036. default:
  2037. return c.typ.String()
  2038. }
  2039. }
  2040. type TupleTypeInfo struct {
  2041. NativeType
  2042. Elems []TypeInfo
  2043. }
  2044. func (t TupleTypeInfo) String() string {
  2045. var buf bytes.Buffer
  2046. buf.WriteString(fmt.Sprintf("%s(", t.typ))
  2047. for _, elem := range t.Elems {
  2048. buf.WriteString(fmt.Sprintf("%s, ", elem))
  2049. }
  2050. buf.Truncate(buf.Len() - 2)
  2051. buf.WriteByte(')')
  2052. return buf.String()
  2053. }
  2054. func (t TupleTypeInfo) New() interface{} {
  2055. return reflect.New(goType(t)).Interface()
  2056. }
  2057. type UDTField struct {
  2058. Name string
  2059. Type TypeInfo
  2060. }
  2061. type UDTTypeInfo struct {
  2062. NativeType
  2063. KeySpace string
  2064. Name string
  2065. Elements []UDTField
  2066. }
  2067. func (u UDTTypeInfo) New() interface{} {
  2068. return reflect.New(goType(u)).Interface()
  2069. }
  2070. func (u UDTTypeInfo) String() string {
  2071. buf := &bytes.Buffer{}
  2072. fmt.Fprintf(buf, "%s.%s{", u.KeySpace, u.Name)
  2073. first := true
  2074. for _, e := range u.Elements {
  2075. if !first {
  2076. fmt.Fprint(buf, ",")
  2077. } else {
  2078. first = false
  2079. }
  2080. fmt.Fprintf(buf, "%s=%v", e.Name, e.Type)
  2081. }
  2082. fmt.Fprint(buf, "}")
  2083. return buf.String()
  2084. }
  2085. // String returns a human readable name for the Cassandra datatype
  2086. // described by t.
  2087. // Type is the identifier of a Cassandra internal datatype.
  2088. type Type int
  2089. const (
  2090. TypeCustom Type = 0x0000
  2091. TypeAscii Type = 0x0001
  2092. TypeBigInt Type = 0x0002
  2093. TypeBlob Type = 0x0003
  2094. TypeBoolean Type = 0x0004
  2095. TypeCounter Type = 0x0005
  2096. TypeDecimal Type = 0x0006
  2097. TypeDouble Type = 0x0007
  2098. TypeFloat Type = 0x0008
  2099. TypeInt Type = 0x0009
  2100. TypeText Type = 0x000A
  2101. TypeTimestamp Type = 0x000B
  2102. TypeUUID Type = 0x000C
  2103. TypeVarchar Type = 0x000D
  2104. TypeVarint Type = 0x000E
  2105. TypeTimeUUID Type = 0x000F
  2106. TypeInet Type = 0x0010
  2107. TypeDate Type = 0x0011
  2108. TypeTime Type = 0x0012
  2109. TypeSmallInt Type = 0x0013
  2110. TypeTinyInt Type = 0x0014
  2111. TypeDuration Type = 0x0015
  2112. TypeList Type = 0x0020
  2113. TypeMap Type = 0x0021
  2114. TypeSet Type = 0x0022
  2115. TypeUDT Type = 0x0030
  2116. TypeTuple Type = 0x0031
  2117. )
  2118. // String returns the name of the identifier.
  2119. func (t Type) String() string {
  2120. switch t {
  2121. case TypeCustom:
  2122. return "custom"
  2123. case TypeAscii:
  2124. return "ascii"
  2125. case TypeBigInt:
  2126. return "bigint"
  2127. case TypeBlob:
  2128. return "blob"
  2129. case TypeBoolean:
  2130. return "boolean"
  2131. case TypeCounter:
  2132. return "counter"
  2133. case TypeDecimal:
  2134. return "decimal"
  2135. case TypeDouble:
  2136. return "double"
  2137. case TypeFloat:
  2138. return "float"
  2139. case TypeInt:
  2140. return "int"
  2141. case TypeText:
  2142. return "text"
  2143. case TypeTimestamp:
  2144. return "timestamp"
  2145. case TypeUUID:
  2146. return "uuid"
  2147. case TypeVarchar:
  2148. return "varchar"
  2149. case TypeTimeUUID:
  2150. return "timeuuid"
  2151. case TypeInet:
  2152. return "inet"
  2153. case TypeDate:
  2154. return "date"
  2155. case TypeDuration:
  2156. return "duration"
  2157. case TypeTime:
  2158. return "time"
  2159. case TypeSmallInt:
  2160. return "smallint"
  2161. case TypeTinyInt:
  2162. return "tinyint"
  2163. case TypeList:
  2164. return "list"
  2165. case TypeMap:
  2166. return "map"
  2167. case TypeSet:
  2168. return "set"
  2169. case TypeVarint:
  2170. return "varint"
  2171. case TypeTuple:
  2172. return "tuple"
  2173. default:
  2174. return fmt.Sprintf("unknown_type_%d", t)
  2175. }
  2176. }
  2177. type MarshalError string
  2178. func (m MarshalError) Error() string {
  2179. return string(m)
  2180. }
  2181. func marshalErrorf(format string, args ...interface{}) MarshalError {
  2182. return MarshalError(fmt.Sprintf(format, args...))
  2183. }
  2184. type UnmarshalError string
  2185. func (m UnmarshalError) Error() string {
  2186. return string(m)
  2187. }
  2188. func unmarshalErrorf(format string, args ...interface{}) UnmarshalError {
  2189. return UnmarshalError(fmt.Sprintf(format, args...))
  2190. }