Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,14 @@ Some highlights from an Apple M4, constructing and rendering to `io.Discard`:

| Benchmark | ns/op | B/op | allocs/op |
|---|---:|---:|---:|
| `El` | 17 | 48 | 1 |
| `Attr`, boolean | 11 | 24 | 1 |
| `Attr`, key-value | 20 | 48 | 1 |
| `Text` | 14 | 16 | 1 |
| `Textf` | 44 | 40 | 2 |
| `El` | 16 | 48 | 1 |
| `Attr`, boolean | 10 | 24 | 1 |
| `Attr`, key-value | 18 | 48 | 1 |
| `Text` | 13 | 16 | 1 |
| `Textf` | 41 | 40 | 2 |
| `Raw` | 3 | 0 | 0 |
| `Rawf` | 38 | 40 | 2 |
| Realistic full page | 68624 | 129686 | 3044 |
| `Rawf` | 36 | 40 | 2 |
| Realistic full page | 63560 | 126580 | 2858 |

### I don't like how HTML looks in Go.

Expand Down
52 changes: 36 additions & 16 deletions gomponents.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ func booleanAttr(name string) Node {
}

// htmlEscapeSet holds the characters that need escaping, and htmlEscaper is what escapes
// them. Both are the six replacements [text/template.HTMLEscape] makes, and escapeString
// them. Both are the six replacements [text/template.HTMLEscape] makes, and writeEscaped
// is required by test to agree with [text/template.HTMLEscapeString] on every input.
var htmlEscapeSet = [256]bool{0: true, '\'': true, '"': true, '&': true, '<': true, '>': true}

Expand All @@ -232,19 +232,12 @@ var htmlEscaper = strings.NewReplacer(
">", "&gt;",
)

// escapeString escapes the characters that HTML gives meaning to, deciding whether there is
// anything to escape with a table built once rather than with [strings.ContainsAny], which
// rebuilds an ASCII bitmap from its constant cutset on every call. Strings with nothing to
// escape, which is nearly all of them, are returned untouched.
func escapeString(s string) string {
for i := 0; i < len(s); i++ {
if htmlEscapeSet[s[i]] {
return htmlEscaper.Replace(s)
}
}
return s
}

// writeEscaped writes s to w with the characters that HTML gives meaning to escaped. It
// decides whether there is anything to escape with a table built once rather than with
// [strings.ContainsAny], which rebuilds an ASCII bitmap from its constant cutset on every
// call, and strings with nothing to escape, which is nearly all of them, are written as they
// are. When there is, an [io.StringWriter] gets the escaped runs streamed into it, and any
// other writer gets one write of the escaped string.
func writeEscaped(w io.Writer, s string) (int, error) {
for i := 0; i < len(s); i++ {
if htmlEscapeSet[s[i]] {
Expand Down Expand Up @@ -316,12 +309,39 @@ func (a attrFunc) String() string {

// Text creates a text DOM [Node] that Renders the escaped string t.
func Text(t string) Node {
return raw(escapeString(t))
return text(t)
}

// Textf creates a text DOM [Node] that Renders the interpolated and escaped string format.
func Textf(format string, a ...interface{}) Node {
return raw(escapeString(fmt.Sprintf(format, a...)))
return text(fmt.Sprintf(format, a...))
}

// Compile-time check that [text] implements [fmt.Stringer], [Node], and [nodeTypeDescriber].
var _ interface {
fmt.Stringer
Node
nodeTypeDescriber
} = text("")

// text is a text DOM [Node] that escapes the underlying string as it Renders, against the
// writer rather than into a new string.
type text string

func (t text) Render(w io.Writer) error {
_, err := writeEscaped(w, string(t))
return err
}

// String satisfies [fmt.Stringer] with the escaped string.
func (t text) String() string {
var b strings.Builder
_ = t.Render(&b)
return b.String()
}

func (t text) Type() NodeType {
return ElementType
}

// Compile-time check that [raw] implements [fmt.Stringer], [Node], and [nodeTypeDescriber].
Expand Down
58 changes: 49 additions & 9 deletions gomponents_internal_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gomponents

import (
"bytes"
"html/template"
"strings"
"testing"
Expand All @@ -15,14 +16,39 @@ func TestRaw(t *testing.T) {
})
}

func TestEscapeString(t *testing.T) {
// escapeString must agree with template.HTMLEscapeString on every input. It no longer
// calls it — it decides whether to escape and then escapes on its own — so this is what
// holds the two together. A false negative would pass markup through.
// writeOnlyBuffer is a [bytes.Buffer] without its WriteString method, so that writeEscaped
// takes the path for writers that only have Write.
type writeOnlyBuffer struct {
b *bytes.Buffer
}

func (w writeOnlyBuffer) Write(p []byte) (int, error) {
return w.b.Write(p)
}

func TestWriteEscaped(t *testing.T) {
// writeEscaped must agree with template.HTMLEscapeString on every input, through both
// the streaming path for an io.StringWriter and the one write for any other writer. It
// never calls it, so this is what holds the two together. A false negative would pass
// markup through.
same := func(t *testing.T, s string) {
t.Helper()
if got, want := escapeString(s), template.HTMLEscapeString(s); got != want {
t.Fatalf("escapeString(%q) = %q, template.HTMLEscapeString = %q", s, got, want)
want := template.HTMLEscapeString(s)

var sb strings.Builder
if _, err := writeEscaped(&sb, s); err != nil {
t.Fatal(err)
}
if got := sb.String(); got != want {
t.Fatalf("writeEscaped(strings.Builder, %q) = %q, template.HTMLEscapeString = %q", s, got, want)
}

var bb bytes.Buffer
if _, err := writeEscaped(writeOnlyBuffer{&bb}, s); err != nil {
t.Fatal(err)
}
if got := bb.String(); got != want {
t.Fatalf("writeEscaped(write-only, %q) = %q, template.HTMLEscapeString = %q", s, got, want)
}
}

Expand Down Expand Up @@ -85,13 +111,27 @@ func TestEscapeString(t *testing.T) {
})
}

func FuzzEscapeString(f *testing.F) {
func FuzzWriteEscaped(f *testing.F) {
for _, s := range []string{"", "hat", "<script>", "a&b", `"x"`, "日本語", "\x00"} {
f.Add(s)
}
f.Fuzz(func(t *testing.T, s string) {
if got, want := escapeString(s), template.HTMLEscapeString(s); got != want {
t.Fatalf("escapeString(%q) = %q, template.HTMLEscapeString = %q", s, got, want)
want := template.HTMLEscapeString(s)

var sb strings.Builder
if _, err := writeEscaped(&sb, s); err != nil {
t.Fatal(err)
}
if got := sb.String(); got != want {
t.Fatalf("writeEscaped(strings.Builder, %q) = %q, template.HTMLEscapeString = %q", s, got, want)
}

var bb bytes.Buffer
if _, err := writeEscaped(writeOnlyBuffer{&bb}, s); err != nil {
t.Fatal(err)
}
if got := bb.String(); got != want {
t.Fatalf("writeEscaped(write-only, %q) = %q, template.HTMLEscapeString = %q", s, got, want)
}
})
}
8 changes: 8 additions & 0 deletions gomponents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,14 @@ func (w writeOnly) Write(p []byte) (int, error) {
}

func TestText(t *testing.T) {
t.Run("satisfies fmt.Stringer with the escaped string", func(t *testing.T) {
e := g.Text("<div>")
s, ok := e.(fmt.Stringer)
if !ok || s.String() != "&lt;div&gt;" {
t.Fatalf("expected escaped string, got %v %q", ok, fmt.Sprint(e))
}
})

t.Run("renders escaped text", func(t *testing.T) {
e := g.Text("<div>")
assert.Equal(t, "&lt;div&gt;", e)
Expand Down
Loading