Skip to content

Instantly share code, notes, and snippets.

@joshuarubin
Created July 18, 2016 18:19
Show Gist options
  • Save joshuarubin/b6d3f1044f050085baf143321c007aa8 to your computer and use it in GitHub Desktop.
Save joshuarubin/b6d3f1044f050085baf143321c007aa8 to your computer and use it in GitHub Desktop.
Replace
// Replace reimplements bytes.Replace in a way that can reuse the buffer
func Replace(s, old, new []byte, n int, buf *bytes.Buffer) error {
m := 0
if n != 0 {
// Compute number of replacements.
m = bytes.Count(s, old)
}
if buf == nil {
buf = &bytes.Buffer{}
}
buf.Reset()
if m == 0 {
// Just return a copy.
_, err := buf.Write(s)
return err
}
if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
buf.Grow(len(s) + n*(len(new)-len(old)))
start := 0
for i := 0; i < n; i++ {
j := start
if len(old) == 0 {
if i > 0 {
_, wid := utf8.DecodeRune(s[start:])
j += wid
}
} else {
j += bytes.Index(s[start:], old)
}
if _, err := buf.Write(s[start:j]); err != nil {
return err
}
if _, err := buf.Write(new); err != nil {
return err
}
start = j + len(old)
}
_, err := buf.Write(s[start:])
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment