marshal.go 56 KB

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