Skip to content

Commit

Permalink
Create strutils.BytesToRuneOffsetConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
marco-nicola committed Dec 11, 2020
1 parent c6c3124 commit 8f76652
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions strutils/strutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,34 @@ type RuneOffsets struct {
// End rune position, exclusive.
End int
}

type BytesToRuneOffsetConverter struct {
mapping []int
}

func NewBytesToRuneOffsetConverter(sequence string) *BytesToRuneOffsetConverter {
mapping := make([]int, 0, len(sequence))
for runeIndex, r := range sequence {
for _ = range []byte(string(r)) {
mapping = append(mapping, runeIndex)
}
}
return &BytesToRuneOffsetConverter{mapping: mapping}
}

func (b *BytesToRuneOffsetConverter) Convert(offsets ByteOffsets) RuneOffsets {
if len(b.mapping) == 0 {
return RuneOffsets{Start: 0, End: 0}
}

start := b.mapping[offsets.Start]

var end int
if offsets.End == len(b.mapping) {
end = b.mapping[offsets.End-1] + 1
} else {
end = b.mapping[offsets.End]
}

return RuneOffsets{Start: start, End: end}
}

0 comments on commit 8f76652

Please sign in to comment.