chunkOfSize.go 1.4 KB

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