Browse Source

feat: Adding chunk split function

Matthias Ladkau 3 years ago
parent
commit
76aaf6d8c0
2 changed files with 91 additions and 0 deletions
  1. 42 0
      stringutil/stringutil.go
  2. 49 0
      stringutil/stringutil_test.go

+ 42 - 0
stringutil/stringutil.go

@@ -790,3 +790,45 @@ func CamelCaseSplit(src string) []string {
 
 	return result
 }
+
+/*
+ChunkSplit splits a string into chunks of a defined size. Attempts to only split
+at white space characters if spaceSplit is set.
+*/
+func ChunkSplit(s string, size int, spaceSplit bool) []string {
+	var res []string
+	var cl, wpos int
+
+	if size >= len(s) {
+		return []string{s}
+	}
+
+	chunk := make([]rune, size)
+
+	for _, r := range s {
+		chunk[cl] = r
+		cl++
+
+		if spaceSplit && unicode.IsSpace(r) {
+			wpos = cl
+		}
+
+		if cl == size {
+			if !spaceSplit || wpos == 0 {
+				res = append(res, string(chunk))
+				cl = 0
+			} else {
+				res = append(res, string(chunk[:wpos]))
+				copy(chunk, chunk[wpos:])
+				cl = len(chunk[wpos:])
+				wpos = 0
+			}
+		}
+	}
+
+	if cl > 0 {
+		res = append(res, string(chunk[:cl]))
+	}
+
+	return res
+}

+ 49 - 0
stringutil/stringutil_test.go

@@ -13,6 +13,7 @@ import (
 	"bytes"
 	"fmt"
 	"regexp"
+	"strings"
 	"sync"
 	"testing"
 )
@@ -732,3 +733,51 @@ func TestCamelCaseSplit(t *testing.T) {
 		return
 	}
 }
+
+func TestChunkSplit(t *testing.T) {
+	if res := fmt.Sprint(ChunkSplit("Foobar tester fooooo", 4, false)); res != "[Foob ar t este r fo oooo]" {
+		t.Error("Unexpected result:", res)
+		return
+	}
+
+	resSplit := ChunkSplit("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", 15, true)
+
+	if res := strings.Join(resSplit, "\n"); res != `
+Lorem ipsum 
+dolor sit 
+amet, 
+consectetur 
+adipiscing 
+elit, sed do 
+eiusmod tempor 
+incididunt ut 
+labore et 
+dolore magna 
+aliqua.`[1:] {
+		t.Errorf("Unexpected result:\n===============\n#%v#", res)
+		return
+	}
+
+	resSplit = ChunkSplit("Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididunt ut labore etdoloremagnaaliqua.", 15, true)
+
+	if res := strings.Join(resSplit, "\n"); res != `
+Loremipsumdolor
+sitamet,consect
+eturadipiscinge
+lit,seddoeiusmo
+dtemporincididu
+nt ut labore 
+etdoloremagnaal
+iqua.`[1:] {
+		t.Errorf("Unexpected result:\n===============\n#%v#", res)
+		return
+	}
+
+	resSplit = ChunkSplit("Lor", 15, true)
+
+	if res := strings.Join(resSplit, "\n"); res != `
+Lor`[1:] {
+		t.Errorf("Unexpected result:\n===============\n#%v#", res)
+		return
+	}
+}