chunkOfSize.go 1.5 KB

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