strutil.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package strutil
  5. import (
  6. "crypto/rand"
  7. "math/big"
  8. "unicode"
  9. )
  10. // ToUpperFirst returns s with only the first Unicode letter mapped to its upper case.
  11. func ToUpperFirst(s string) string {
  12. for i, v := range s {
  13. return string(unicode.ToUpper(v)) + s[i+1:]
  14. }
  15. return ""
  16. }
  17. // RandomChars returns a generated string in given number of random characters.
  18. func RandomChars(n int) (string, error) {
  19. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  20. randomInt := func(max *big.Int) (int, error) {
  21. r, err := rand.Int(rand.Reader, max)
  22. if err != nil {
  23. return 0, err
  24. }
  25. return int(r.Int64()), nil
  26. }
  27. buffer := make([]byte, n)
  28. max := big.NewInt(int64(len(alphanum)))
  29. for i := 0; i < n; i++ {
  30. index, err := randomInt(max)
  31. if err != nil {
  32. return "", err
  33. }
  34. buffer[i] = alphanum[index]
  35. }
  36. return string(buffer), nil
  37. }
  38. // Ellipsis returns a truncated string and appends "..." to the end of the
  39. // string if the string length is larger than the threshold. Otherwise, the
  40. // original string is returned.
  41. func Ellipsis(str string, threshold int) string {
  42. if len(str) <= threshold || threshold < 0 {
  43. return str
  44. }
  45. return str[:threshold] + "..."
  46. }
  47. // Truncate returns a truncated string if its length is over the limit.
  48. // Otherwise, it returns the original string.
  49. func Truncate(str string, limit int) string {
  50. if len(str) < limit {
  51. return str
  52. }
  53. return str[:limit]
  54. }