marshal.go 47 KB

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