You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

string.go 2.0 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "strconv"
  7. "strings"
  8. )
  9. func IndexAt(s, sep string, n int) int {
  10. idx := strings.Index(s[n:], sep)
  11. if idx > -1 {
  12. idx += n
  13. }
  14. return idx
  15. }
  16. func ParseInt(s string) int {
  17. i, err := strconv.Atoi(s)
  18. if err != nil {
  19. panic(err)
  20. }
  21. return i
  22. }
  23. func ParseIntWithError(s string) (int, error) {
  24. i, err := strconv.Atoi(s)
  25. if err != nil {
  26. return -1, err
  27. }
  28. if i < 0 {
  29. return -1, errors.New("negative version number")
  30. }
  31. return i, nil
  32. }
  33. func ParseFloat(s string) float64 {
  34. f, err := strconv.ParseFloat(s, 64)
  35. if err != nil {
  36. panic(err)
  37. }
  38. return f
  39. }
  40. func GetOwnerAndNameFromId(id string) (string, string) {
  41. tokens := strings.Split(id, "/")
  42. if len(tokens) != 2 {
  43. panic(errors.New("GetOwnerAndNameFromId() error, wrong token count for ID: " + id))
  44. }
  45. return tokens[0], tokens[1]
  46. }
  47. func GetOwnerAndNameFromId3(id string) (string, string, string) {
  48. tokens := strings.Split(id, "/")
  49. if len(tokens) != 3 {
  50. panic(errors.New("GetOwnerAndNameFromId3() error, wrong token count for ID: " + id))
  51. }
  52. return tokens[0], fmt.Sprintf("%s/%s", tokens[0], tokens[1]), tokens[2]
  53. }
  54. func GetOwnerAndNameFromId3New(id string) (string, string, string) {
  55. tokens := strings.Split(id, "/")
  56. if len(tokens) != 3 {
  57. panic(errors.New("GetOwnerAndNameFromId3New() error, wrong token count for ID: " + id))
  58. }
  59. return tokens[0], tokens[1], tokens[2]
  60. }
  61. func GetIdFromOwnerAndName(owner string, name string) string {
  62. return fmt.Sprintf("%s/%s", owner, name)
  63. }
  64. func ReadStringFromPath(path string) string {
  65. data, err := ioutil.ReadFile(path)
  66. if err != nil {
  67. panic(err)
  68. }
  69. return string(data)
  70. }
  71. func WriteStringToPath(s string, path string) {
  72. err := ioutil.WriteFile(path, []byte(s), 0644)
  73. if err != nil {
  74. panic(err)
  75. }
  76. }
  77. func ReadBytesFromPath(path string) []byte {
  78. data, err := ioutil.ReadFile(path)
  79. if err != nil {
  80. panic(err)
  81. }
  82. return data
  83. }
  84. func WriteBytesToPath(b []byte, path string) {
  85. err := ioutil.WriteFile(path, b, 0644)
  86. if err != nil {
  87. panic(err)
  88. }
  89. }

No Description

Contributors (1)