chunkOfSize.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package cos
  2. import (
  3. "fmt"
  4. "strings"
  5. "unicode/utf8"
  6. )
  7. type chunkOfSize struct {
  8. current int
  9. limit int
  10. chunks []string
  11. errors []string
  12. }
  13. // NewChunkOfSize returns new instance of ChunkOfSize initialized with given text and size
  14. func NewChunkOfSize(text string, size int) *chunkOfSize {
  15. if utf8.RuneCountInString(text) < size {
  16. return nil
  17. }
  18. return &chunkOfSize{
  19. current: 0,
  20. limit: size,
  21. chunks: strings.Split(text, " "),
  22. }
  23. }
  24. // Next returns next chunk of text or empty string if nothing left to process
  25. func (c *chunkOfSize) Next() string {
  26. var b strings.Builder
  27. for i := range c.chunks {
  28. l := utf8.RuneCountInString(c.chunks[i])
  29. if l >= c.limit {
  30. c.errors = append(c.errors, fmt.Sprintf("Chunk {%s} is bigger than limit %d!", c.chunks[i], c.limit))
  31. c.chunks = []string{}
  32. return ""
  33. }
  34. if l+c.current >= c.limit {
  35. c.current = 0
  36. c.chunks = c.chunks[i:]
  37. return b.String()
  38. }
  39. var toWrite string
  40. if c.current == 0 || c.chunks[i] == "\n" {
  41. toWrite = c.chunks[i]
  42. } else {
  43. toWrite = fmt.Sprintf(" %s", c.chunks[i])
  44. l++
  45. }
  46. w, err := b.WriteString(toWrite)
  47. if w == 0 || err != nil {
  48. c.errors = append(c.errors, fmt.Sprintf("Error writing: %s; %s", toWrite, err))
  49. continue
  50. }
  51. c.current += l
  52. }
  53. c.chunks = []string{}
  54. return b.String()
  55. }
  56. // Success returns true if there are no errors
  57. func (c *chunkOfSize) Success() bool {
  58. return len(c.errors) == 0
  59. }
  60. // GetErrors returns erorrs
  61. func (c *chunkOfSize) GetErrors() []string {
  62. return c.errors
  63. }