stop.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "strings"
  4. )
  5. func findStop(sequence string, stops []string) (bool, string) {
  6. for _, stop := range stops {
  7. if strings.Contains(sequence, stop) {
  8. return true, stop
  9. }
  10. }
  11. return false, ""
  12. }
  13. // maybeStop returns true if the provided sequence ends with
  14. // the start of any of the provided stop sequences, meaning
  15. // a stop sequence is likely to follow
  16. func maybeStop(sequence string, stops []string) bool {
  17. for _, stop := range stops {
  18. for i := 1; i <= len(stop); i++ {
  19. if strings.HasSuffix(sequence, stop[:i]) {
  20. return true
  21. }
  22. }
  23. }
  24. return false
  25. }
  26. // truncateStop removes the provided stop string from pieces,
  27. // returning the partial pieces with stop removed, including truncating
  28. // the last piece if required
  29. func truncateStop(pieces []string, stop string) []string {
  30. joined := strings.Join(pieces, "")
  31. index := strings.Index(joined, stop)
  32. if index == -1 {
  33. return pieces
  34. }
  35. joined = joined[:index]
  36. // Split truncated string back into pieces of original lengths
  37. lengths := make([]int, len(pieces))
  38. for i, piece := range pieces {
  39. lengths[i] = len(piece)
  40. }
  41. var result []string
  42. start := 0
  43. for _, length := range lengths {
  44. if start >= len(joined) {
  45. break
  46. }
  47. end := start + length
  48. if end > len(joined) {
  49. end = len(joined)
  50. }
  51. result = append(result, joined[start:end])
  52. start = end
  53. }
  54. return result
  55. }