chunkOfSize.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. return &chunkOfSize{
  16. current: 0,
  17. limit: size,
  18. chunks: strings.Split(text, " "),
  19. }
  20. }
  21. // Next returns next chunk of text or empty string if nothing left to process
  22. func (c *chunkOfSize) Next() string {
  23. var b strings.Builder
  24. for i := range c.chunks {
  25. l := utf8.RuneCountInString(c.chunks[i])
  26. if l >= c.limit {
  27. c.errors = append(c.errors, fmt.Sprintf("Chunk {%s} is bigger than limit %d!", c.chunks[i], c.limit))
  28. c.chunks = []string{}
  29. return ""
  30. }
  31. if l+c.current >= c.limit {
  32. c.current = 0
  33. c.chunks = c.chunks[i:]
  34. return b.String()
  35. }
  36. var toWrite string
  37. if c.current == 0 || c.chunks[i] == "\n" {
  38. toWrite = c.chunks[i]
  39. } else {
  40. toWrite = fmt.Sprintf(" %s", c.chunks[i])
  41. l++
  42. }
  43. w, err := b.WriteString(toWrite)
  44. if w == 0 || err != nil {
  45. c.errors = append(c.errors, fmt.Sprintf("Error writing: %s; %s", toWrite, err))
  46. continue
  47. }
  48. c.current += l
  49. }
  50. c.chunks = []string{}
  51. return b.String()
  52. }
  53. // Success returns true if there are no errors
  54. func (c *chunkOfSize) Success() bool {
  55. return len(c.errors) == 0
  56. }
  57. // GetErrors returns erorrs
  58. func (c *chunkOfSize) GetErrors() []string {
  59. return c.errors
  60. }