marshal.go 52 KB

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