marshal.go 53 KB

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