chunkOfSize.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package cos
  2. import (
  3. "strings"
  4. "unicode/utf8"
  5. "fmt"
  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.current >= c.limit {
  28. c.current = 0
  29. c.chunks = c.chunks[i:]
  30. return b.String()
  31. }
  32. var toWrite string
  33. if c.current == 0 || c.chunks[i] == "\n" {
  34. toWrite = c.chunks[i]
  35. } else {
  36. toWrite = fmt.Sprintf(" %s", c.chunks[i])
  37. l++
  38. }
  39. w, err := b.WriteString(toWrite)
  40. if w == 0 || err != nil {
  41. c.errors = append(c.errors, fmt.Sprintf("Error writing: %s; %s", toWrite, err))
  42. continue
  43. }
  44. c.current += l
  45. }
  46. c.chunks = []string{}
  47. return b.String()
  48. }
  49. // Success returns true if there are no errors
  50. func (c *ChunkOfSize) Success() bool {
  51. return len(c.errors) == 0
  52. }
  53. // GetErrors returns erorrs
  54. func (c *ChunkOfSize) GetErrors() []string {
  55. return c.errors
  56. }