Improved performance

This commit is contained in:
Eduard Urbach 2024-04-02 20:14:07 +02:00
parent 52c995659d
commit 56e2a65ec1
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
2 changed files with 27 additions and 28 deletions

View File

@ -4,7 +4,8 @@ A markdown renderer that supports only a subset of the CommonMark spec in order
## Features
- Code
- Code blocks
- Formatting (bold, italic, monospace)
- Links
- Lists
- Headers
@ -47,9 +48,9 @@ coverage: 100.0% of statements
## Benchmarks
```
BenchmarkSmall-12 8109500 145.1 ns/op 32 B/op 1 allocs/op
BenchmarkMedium-12 556713 1906 ns/op 512 B/op 1 allocs/op
BenchmarkLarge-12 218116 4588 ns/op 2560 B/op 2 allocs/op
BenchmarkSmall-12 5986922 187.5 ns/op 32 B/op 1 allocs/op
BenchmarkMedium-12 1000000 1077 ns/op 512 B/op 1 allocs/op
BenchmarkLarge-12 255178 4055 ns/op 2560 B/op 2 allocs/op
```
## License

View File

@ -249,36 +249,37 @@ func (r *renderer) closeTables() {
// writeText converts inline markdown to HTML.
func (r *renderer) writeText(markdown string) {
var (
i = 0
tokenStart = 0
)
var (
textStart = -1
textEnd = -1
urlStart = -1
codeStart = -1
emStart = -1
strongStart = -1
parentheses = 0
tokenStart = 0
searchStart = 0
linkTextStart = -1
linkTextEnd = -1
urlStart = -1
codeStart = -1
emStart = -1
strongStart = -1
parentheses = 0
)
for {
if i >= len(markdown) {
i := strings.IndexAny(markdown[searchStart:], "[]()`*_")
if i == -1 {
r.WriteString(html.EscapeString(markdown[tokenStart:]))
return
}
i += searchStart
searchStart = i + 1
c := markdown[i]
switch c {
case '[':
r.WriteString(html.EscapeString(markdown[tokenStart:i]))
tokenStart = i
textStart = i
linkTextStart = i
case ']':
textEnd = i
linkTextEnd = i
case '(':
if parentheses == 0 {
@ -290,8 +291,8 @@ func (r *renderer) writeText(markdown string) {
case ')':
parentheses--
if parentheses == 0 && textStart >= 0 && textEnd >= 0 && urlStart >= 0 {
linkText := markdown[textStart+1 : textEnd]
if parentheses == 0 && linkTextStart >= 0 && linkTextEnd >= 0 && urlStart >= 0 {
linkText := markdown[linkTextStart+1 : linkTextEnd]
linkURL := markdown[urlStart+1 : i]
r.WriteString("<a href=\"")
@ -300,8 +301,8 @@ func (r *renderer) writeText(markdown string) {
r.WriteString(html.EscapeString(linkText))
r.WriteString("</a>")
textStart = -1
textEnd = -1
linkTextStart = -1
linkTextEnd = -1
urlStart = -1
tokenStart = i + 1
@ -329,9 +330,8 @@ func (r *renderer) writeText(markdown string) {
r.WriteString(html.EscapeString(markdown[strongStart:i]))
r.WriteString("</strong>")
strongStart = -1
i++
tokenStart = i + 1
tokenStart = i + 2
searchStart = tokenStart
} else if emStart != -1 {
r.WriteString("<em>")
r.WriteString(html.EscapeString(markdown[emStart:i]))
@ -344,8 +344,6 @@ func (r *renderer) writeText(markdown string) {
emStart = i + 1
}
}
i++
}
}