marshal.go 41 KB

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