gconv.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gconv implements powerful and convenient converting functionality for any types of variables.
  7. //
  8. // This package should keep much less dependencies with other packages.
  9. package gconv
  10. import (
  11. "fmt"
  12. "github.com/gogf/gf/internal/json"
  13. "github.com/gogf/gf/os/gtime"
  14. "math"
  15. "reflect"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/gogf/gf/encoding/gbinary"
  20. )
  21. type (
  22. // errorStack is the interface for Stack feature.
  23. errorStack interface {
  24. Error() string
  25. Stack() string
  26. }
  27. )
  28. var (
  29. // Empty strings.
  30. emptyStringMap = map[string]struct{}{
  31. "": {},
  32. "0": {},
  33. "no": {},
  34. "off": {},
  35. "false": {},
  36. }
  37. // StructTagPriority defines the default priority tags for Map*/Struct* functions.
  38. // Note, the "gconv", "param", "params" tags are used by old version of package.
  39. // It is strongly recommended using short tag "c" or "p" instead in the future.
  40. StructTagPriority = []string{"gconv", "param", "params", "c", "p", "json"}
  41. )
  42. type doConvertInput struct {
  43. FromValue interface{} // Value that is converted from.
  44. ToTypeName string // Target value type name in string.
  45. ReferValue interface{} // Referred value, a value in type `ToTypeName`.
  46. Extra []interface{} // Extra values for implementing the converting.
  47. }
  48. // doConvert does commonly used types converting.
  49. func doConvert(input doConvertInput) interface{} {
  50. switch input.ToTypeName {
  51. case "int":
  52. return Int(input.FromValue)
  53. case "*int":
  54. if _, ok := input.FromValue.(*int); ok {
  55. return input.FromValue
  56. }
  57. v := Int(input.FromValue)
  58. return &v
  59. case "int8":
  60. return Int8(input.FromValue)
  61. case "*int8":
  62. if _, ok := input.FromValue.(*int8); ok {
  63. return input.FromValue
  64. }
  65. v := Int8(input.FromValue)
  66. return &v
  67. case "int16":
  68. return Int16(input.FromValue)
  69. case "*int16":
  70. if _, ok := input.FromValue.(*int16); ok {
  71. return input.FromValue
  72. }
  73. v := Int16(input.FromValue)
  74. return &v
  75. case "int32":
  76. return Int32(input.FromValue)
  77. case "*int32":
  78. if _, ok := input.FromValue.(*int32); ok {
  79. return input.FromValue
  80. }
  81. v := Int32(input.FromValue)
  82. return &v
  83. case "int64":
  84. return Int64(input.FromValue)
  85. case "*int64":
  86. if _, ok := input.FromValue.(*int64); ok {
  87. return input.FromValue
  88. }
  89. v := Int64(input.FromValue)
  90. return &v
  91. case "uint":
  92. return Uint(input.FromValue)
  93. case "*uint":
  94. if _, ok := input.FromValue.(*uint); ok {
  95. return input.FromValue
  96. }
  97. v := Uint(input.FromValue)
  98. return &v
  99. case "uint8":
  100. return Uint8(input.FromValue)
  101. case "*uint8":
  102. if _, ok := input.FromValue.(*uint8); ok {
  103. return input.FromValue
  104. }
  105. v := Uint8(input.FromValue)
  106. return &v
  107. case "uint16":
  108. return Uint16(input.FromValue)
  109. case "*uint16":
  110. if _, ok := input.FromValue.(*uint16); ok {
  111. return input.FromValue
  112. }
  113. v := Uint16(input.FromValue)
  114. return &v
  115. case "uint32":
  116. return Uint32(input.FromValue)
  117. case "*uint32":
  118. if _, ok := input.FromValue.(*uint32); ok {
  119. return input.FromValue
  120. }
  121. v := Uint32(input.FromValue)
  122. return &v
  123. case "uint64":
  124. return Uint64(input.FromValue)
  125. case "*uint64":
  126. if _, ok := input.FromValue.(*uint64); ok {
  127. return input.FromValue
  128. }
  129. v := Uint64(input.FromValue)
  130. return &v
  131. case "float32":
  132. return Float32(input.FromValue)
  133. case "*float32":
  134. if _, ok := input.FromValue.(*float32); ok {
  135. return input.FromValue
  136. }
  137. v := Float32(input.FromValue)
  138. return &v
  139. case "float64":
  140. return Float64(input.FromValue)
  141. case "*float64":
  142. if _, ok := input.FromValue.(*float64); ok {
  143. return input.FromValue
  144. }
  145. v := Float64(input.FromValue)
  146. return &v
  147. case "bool":
  148. return Bool(input.FromValue)
  149. case "*bool":
  150. if _, ok := input.FromValue.(*bool); ok {
  151. return input.FromValue
  152. }
  153. v := Bool(input.FromValue)
  154. return &v
  155. case "string":
  156. return String(input.FromValue)
  157. case "*string":
  158. if _, ok := input.FromValue.(*string); ok {
  159. return input.FromValue
  160. }
  161. v := String(input.FromValue)
  162. return &v
  163. case "[]byte":
  164. return Bytes(input.FromValue)
  165. case "[]int":
  166. return Ints(input.FromValue)
  167. case "[]int32":
  168. return Int32s(input.FromValue)
  169. case "[]int64":
  170. return Int64s(input.FromValue)
  171. case "[]uint":
  172. return Uints(input.FromValue)
  173. case "[]uint8":
  174. return Bytes(input.FromValue)
  175. case "[]uint32":
  176. return Uint32s(input.FromValue)
  177. case "[]uint64":
  178. return Uint64s(input.FromValue)
  179. case "[]float32":
  180. return Float32s(input.FromValue)
  181. case "[]float64":
  182. return Float64s(input.FromValue)
  183. case "[]string":
  184. return Strings(input.FromValue)
  185. case "Time", "time.Time":
  186. if len(input.Extra) > 0 {
  187. return Time(input.FromValue, String(input.Extra[0]))
  188. }
  189. return Time(input.FromValue)
  190. case "*time.Time":
  191. var v interface{}
  192. if len(input.Extra) > 0 {
  193. v = Time(input.FromValue, String(input.Extra[0]))
  194. } else {
  195. if _, ok := input.FromValue.(*time.Time); ok {
  196. return input.FromValue
  197. }
  198. v = Time(input.FromValue)
  199. }
  200. return &v
  201. case "GTime", "gtime.Time":
  202. if len(input.Extra) > 0 {
  203. if v := GTime(input.FromValue, String(input.Extra[0])); v != nil {
  204. return *v
  205. } else {
  206. return *gtime.New()
  207. }
  208. }
  209. if v := GTime(input.FromValue); v != nil {
  210. return *v
  211. } else {
  212. return *gtime.New()
  213. }
  214. case "*gtime.Time":
  215. if len(input.Extra) > 0 {
  216. if v := GTime(input.FromValue, String(input.Extra[0])); v != nil {
  217. return v
  218. } else {
  219. return gtime.New()
  220. }
  221. }
  222. if v := GTime(input.FromValue); v != nil {
  223. return v
  224. } else {
  225. return gtime.New()
  226. }
  227. case "Duration", "time.Duration":
  228. return Duration(input.FromValue)
  229. case "*time.Duration":
  230. if _, ok := input.FromValue.(*time.Duration); ok {
  231. return input.FromValue
  232. }
  233. v := Duration(input.FromValue)
  234. return &v
  235. case "map[string]string":
  236. return MapStrStr(input.FromValue)
  237. case "map[string]interface{}":
  238. return Map(input.FromValue)
  239. case "[]map[string]interface{}":
  240. return Maps(input.FromValue)
  241. default:
  242. if input.ReferValue != nil {
  243. var (
  244. referReflectValue reflect.Value
  245. )
  246. if v, ok := input.ReferValue.(reflect.Value); ok {
  247. referReflectValue = v
  248. } else {
  249. referReflectValue = reflect.ValueOf(input.ReferValue)
  250. }
  251. input.ToTypeName = referReflectValue.Kind().String()
  252. input.ReferValue = nil
  253. return reflect.ValueOf(doConvert(input)).Convert(referReflectValue.Type()).Interface()
  254. }
  255. return input.FromValue
  256. }
  257. }
  258. // Convert converts the variable `fromValue` to the type `toTypeName`, the type `toTypeName` is specified by string.
  259. // The optional parameter `extraParams` is used for additional necessary parameter for this conversion.
  260. // It supports common types conversion as its conversion based on type name string.
  261. func Convert(fromValue interface{}, toTypeName string, extraParams ...interface{}) interface{} {
  262. return doConvert(doConvertInput{
  263. FromValue: fromValue,
  264. ToTypeName: toTypeName,
  265. ReferValue: nil,
  266. Extra: extraParams,
  267. })
  268. }
  269. // Byte converts `any` to byte.
  270. func Byte(any interface{}) byte {
  271. if v, ok := any.(byte); ok {
  272. return v
  273. }
  274. return Uint8(any)
  275. }
  276. // Bytes converts `any` to []byte.
  277. func Bytes(any interface{}) []byte {
  278. if any == nil {
  279. return nil
  280. }
  281. switch value := any.(type) {
  282. case string:
  283. return []byte(value)
  284. case []byte:
  285. return value
  286. default:
  287. if f, ok := value.(apiBytes); ok {
  288. return f.Bytes()
  289. }
  290. var (
  291. reflectValue = reflect.ValueOf(any)
  292. reflectKind = reflectValue.Kind()
  293. )
  294. for reflectKind == reflect.Ptr {
  295. reflectValue = reflectValue.Elem()
  296. reflectKind = reflectValue.Kind()
  297. }
  298. switch reflectKind {
  299. case reflect.Array, reflect.Slice:
  300. var (
  301. ok = true
  302. bytes = make([]byte, reflectValue.Len())
  303. )
  304. for i, _ := range bytes {
  305. int32Value := Int32(reflectValue.Index(i).Interface())
  306. if int32Value < 0 || int32Value > math.MaxUint8 {
  307. ok = false
  308. break
  309. }
  310. bytes[i] = byte(int32Value)
  311. }
  312. if ok {
  313. return bytes
  314. }
  315. }
  316. return gbinary.Encode(any)
  317. }
  318. }
  319. // Rune converts `any` to rune.
  320. func Rune(any interface{}) rune {
  321. if v, ok := any.(rune); ok {
  322. return v
  323. }
  324. return Int32(any)
  325. }
  326. // Runes converts `any` to []rune.
  327. func Runes(any interface{}) []rune {
  328. if v, ok := any.([]rune); ok {
  329. return v
  330. }
  331. return []rune(String(any))
  332. }
  333. // String converts `any` to string.
  334. // It's most commonly used converting function.
  335. func String(any interface{}) string {
  336. if any == nil {
  337. return ""
  338. }
  339. switch value := any.(type) {
  340. case int:
  341. return strconv.Itoa(value)
  342. case int8:
  343. return strconv.Itoa(int(value))
  344. case int16:
  345. return strconv.Itoa(int(value))
  346. case int32:
  347. return strconv.Itoa(int(value))
  348. case int64:
  349. return strconv.FormatInt(value, 10)
  350. case uint:
  351. return strconv.FormatUint(uint64(value), 10)
  352. case uint8:
  353. return strconv.FormatUint(uint64(value), 10)
  354. case uint16:
  355. return strconv.FormatUint(uint64(value), 10)
  356. case uint32:
  357. return strconv.FormatUint(uint64(value), 10)
  358. case uint64:
  359. return strconv.FormatUint(value, 10)
  360. case float32:
  361. return strconv.FormatFloat(float64(value), 'f', -1, 32)
  362. case float64:
  363. return strconv.FormatFloat(value, 'f', -1, 64)
  364. case bool:
  365. return strconv.FormatBool(value)
  366. case string:
  367. return value
  368. case []byte:
  369. return string(value)
  370. case time.Time:
  371. if value.IsZero() {
  372. return ""
  373. }
  374. return value.String()
  375. case *time.Time:
  376. if value == nil {
  377. return ""
  378. }
  379. return value.String()
  380. case gtime.Time:
  381. if value.IsZero() {
  382. return ""
  383. }
  384. return value.String()
  385. case *gtime.Time:
  386. if value == nil {
  387. return ""
  388. }
  389. return value.String()
  390. default:
  391. // Empty checks.
  392. if value == nil {
  393. return ""
  394. }
  395. if f, ok := value.(apiString); ok {
  396. // If the variable implements the String() interface,
  397. // then use that interface to perform the conversion
  398. return f.String()
  399. }
  400. if f, ok := value.(apiError); ok {
  401. // If the variable implements the Error() interface,
  402. // then use that interface to perform the conversion
  403. return f.Error()
  404. }
  405. // Reflect checks.
  406. var (
  407. rv = reflect.ValueOf(value)
  408. kind = rv.Kind()
  409. )
  410. switch kind {
  411. case reflect.Chan,
  412. reflect.Map,
  413. reflect.Slice,
  414. reflect.Func,
  415. reflect.Ptr,
  416. reflect.Interface,
  417. reflect.UnsafePointer:
  418. if rv.IsNil() {
  419. return ""
  420. }
  421. case reflect.String:
  422. return rv.String()
  423. }
  424. if kind == reflect.Ptr {
  425. return String(rv.Elem().Interface())
  426. }
  427. // Finally, we use json.Marshal to convert.
  428. if jsonContent, err := json.Marshal(value); err != nil {
  429. return fmt.Sprint(value)
  430. } else {
  431. return string(jsonContent)
  432. }
  433. }
  434. }
  435. // Bool converts `any` to bool.
  436. // It returns false if `any` is: false, "", 0, "false", "off", "no", empty slice/map.
  437. func Bool(any interface{}) bool {
  438. if any == nil {
  439. return false
  440. }
  441. switch value := any.(type) {
  442. case bool:
  443. return value
  444. case []byte:
  445. if _, ok := emptyStringMap[strings.ToLower(string(value))]; ok {
  446. return false
  447. }
  448. return true
  449. case string:
  450. if _, ok := emptyStringMap[strings.ToLower(value)]; ok {
  451. return false
  452. }
  453. return true
  454. default:
  455. if f, ok := value.(apiBool); ok {
  456. return f.Bool()
  457. }
  458. rv := reflect.ValueOf(any)
  459. switch rv.Kind() {
  460. case reflect.Ptr:
  461. return !rv.IsNil()
  462. case reflect.Map:
  463. fallthrough
  464. case reflect.Array:
  465. fallthrough
  466. case reflect.Slice:
  467. return rv.Len() != 0
  468. case reflect.Struct:
  469. return true
  470. default:
  471. s := strings.ToLower(String(any))
  472. if _, ok := emptyStringMap[s]; ok {
  473. return false
  474. }
  475. return true
  476. }
  477. }
  478. }
  479. // Int converts `any` to int.
  480. func Int(any interface{}) int {
  481. if any == nil {
  482. return 0
  483. }
  484. if v, ok := any.(int); ok {
  485. return v
  486. }
  487. return int(Int64(any))
  488. }
  489. // Int8 converts `any` to int8.
  490. func Int8(any interface{}) int8 {
  491. if any == nil {
  492. return 0
  493. }
  494. if v, ok := any.(int8); ok {
  495. return v
  496. }
  497. return int8(Int64(any))
  498. }
  499. // Int16 converts `any` to int16.
  500. func Int16(any interface{}) int16 {
  501. if any == nil {
  502. return 0
  503. }
  504. if v, ok := any.(int16); ok {
  505. return v
  506. }
  507. return int16(Int64(any))
  508. }
  509. // Int32 converts `any` to int32.
  510. func Int32(any interface{}) int32 {
  511. if any == nil {
  512. return 0
  513. }
  514. if v, ok := any.(int32); ok {
  515. return v
  516. }
  517. return int32(Int64(any))
  518. }
  519. // Int64 converts `any` to int64.
  520. func Int64(any interface{}) int64 {
  521. if any == nil {
  522. return 0
  523. }
  524. switch value := any.(type) {
  525. case int:
  526. return int64(value)
  527. case int8:
  528. return int64(value)
  529. case int16:
  530. return int64(value)
  531. case int32:
  532. return int64(value)
  533. case int64:
  534. return value
  535. case uint:
  536. return int64(value)
  537. case uint8:
  538. return int64(value)
  539. case uint16:
  540. return int64(value)
  541. case uint32:
  542. return int64(value)
  543. case uint64:
  544. return int64(value)
  545. case float32:
  546. return int64(value)
  547. case float64:
  548. return int64(value)
  549. case bool:
  550. if value {
  551. return 1
  552. }
  553. return 0
  554. case []byte:
  555. return gbinary.DecodeToInt64(value)
  556. default:
  557. if f, ok := value.(apiInt64); ok {
  558. return f.Int64()
  559. }
  560. s := String(value)
  561. isMinus := false
  562. if len(s) > 0 {
  563. if s[0] == '-' {
  564. isMinus = true
  565. s = s[1:]
  566. } else if s[0] == '+' {
  567. s = s[1:]
  568. }
  569. }
  570. // Hexadecimal
  571. if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
  572. if v, e := strconv.ParseInt(s[2:], 16, 64); e == nil {
  573. if isMinus {
  574. return -v
  575. }
  576. return v
  577. }
  578. }
  579. // Octal
  580. if len(s) > 1 && s[0] == '0' {
  581. if v, e := strconv.ParseInt(s[1:], 8, 64); e == nil {
  582. if isMinus {
  583. return -v
  584. }
  585. return v
  586. }
  587. }
  588. // Decimal
  589. if v, e := strconv.ParseInt(s, 10, 64); e == nil {
  590. if isMinus {
  591. return -v
  592. }
  593. return v
  594. }
  595. // Float64
  596. return int64(Float64(value))
  597. }
  598. }
  599. // Uint converts `any` to uint.
  600. func Uint(any interface{}) uint {
  601. if any == nil {
  602. return 0
  603. }
  604. if v, ok := any.(uint); ok {
  605. return v
  606. }
  607. return uint(Uint64(any))
  608. }
  609. // Uint8 converts `any` to uint8.
  610. func Uint8(any interface{}) uint8 {
  611. if any == nil {
  612. return 0
  613. }
  614. if v, ok := any.(uint8); ok {
  615. return v
  616. }
  617. return uint8(Uint64(any))
  618. }
  619. // Uint16 converts `any` to uint16.
  620. func Uint16(any interface{}) uint16 {
  621. if any == nil {
  622. return 0
  623. }
  624. if v, ok := any.(uint16); ok {
  625. return v
  626. }
  627. return uint16(Uint64(any))
  628. }
  629. // Uint32 converts `any` to uint32.
  630. func Uint32(any interface{}) uint32 {
  631. if any == nil {
  632. return 0
  633. }
  634. if v, ok := any.(uint32); ok {
  635. return v
  636. }
  637. return uint32(Uint64(any))
  638. }
  639. // Uint64 converts `any` to uint64.
  640. func Uint64(any interface{}) uint64 {
  641. if any == nil {
  642. return 0
  643. }
  644. switch value := any.(type) {
  645. case int:
  646. return uint64(value)
  647. case int8:
  648. return uint64(value)
  649. case int16:
  650. return uint64(value)
  651. case int32:
  652. return uint64(value)
  653. case int64:
  654. return uint64(value)
  655. case uint:
  656. return uint64(value)
  657. case uint8:
  658. return uint64(value)
  659. case uint16:
  660. return uint64(value)
  661. case uint32:
  662. return uint64(value)
  663. case uint64:
  664. return value
  665. case float32:
  666. return uint64(value)
  667. case float64:
  668. return uint64(value)
  669. case bool:
  670. if value {
  671. return 1
  672. }
  673. return 0
  674. case []byte:
  675. return gbinary.DecodeToUint64(value)
  676. default:
  677. if f, ok := value.(apiUint64); ok {
  678. return f.Uint64()
  679. }
  680. s := String(value)
  681. // Hexadecimal
  682. if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
  683. if v, e := strconv.ParseUint(s[2:], 16, 64); e == nil {
  684. return v
  685. }
  686. }
  687. // Octal
  688. if len(s) > 1 && s[0] == '0' {
  689. if v, e := strconv.ParseUint(s[1:], 8, 64); e == nil {
  690. return v
  691. }
  692. }
  693. // Decimal
  694. if v, e := strconv.ParseUint(s, 10, 64); e == nil {
  695. return v
  696. }
  697. // Float64
  698. return uint64(Float64(value))
  699. }
  700. }
  701. // Float32 converts `any` to float32.
  702. func Float32(any interface{}) float32 {
  703. if any == nil {
  704. return 0
  705. }
  706. switch value := any.(type) {
  707. case float32:
  708. return value
  709. case float64:
  710. return float32(value)
  711. case []byte:
  712. return gbinary.DecodeToFloat32(value)
  713. default:
  714. if f, ok := value.(apiFloat32); ok {
  715. return f.Float32()
  716. }
  717. v, _ := strconv.ParseFloat(String(any), 64)
  718. return float32(v)
  719. }
  720. }
  721. // Float64 converts `any` to float64.
  722. func Float64(any interface{}) float64 {
  723. if any == nil {
  724. return 0
  725. }
  726. switch value := any.(type) {
  727. case float32:
  728. return float64(value)
  729. case float64:
  730. return value
  731. case []byte:
  732. return gbinary.DecodeToFloat64(value)
  733. default:
  734. if f, ok := value.(apiFloat64); ok {
  735. return f.Float64()
  736. }
  737. v, _ := strconv.ParseFloat(String(any), 64)
  738. return v
  739. }
  740. }