marshal.go 47 KB

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