marshal.go 39 KB

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