chunkOfSize.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.limit {
  28. c.errors = append(c.errors, fmt.Sprintf("Chunk {%s} is bigger than limit %d!", c.chunks[i], c.limit))
  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. }