Skip to content

Commit c3fe070

Browse files
fix(extgen): escape quotes and control chars in C string literals
1 parent af07c17 commit c3fe070

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

internal/extgen/cfile.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,25 @@ func (cg *cFileGenerator) getTemplateContent() (string, error) {
7676
return buf.String(), nil
7777
}
7878

79-
// escapeCString escapes backslashes for C string literals
79+
// escapeCString escapes characters that would break a C double-quoted string literal.
8080
func escapeCString(s string) string {
81-
return strings.ReplaceAll(s, `\`, `\\`)
81+
var b strings.Builder
82+
b.Grow(len(s))
83+
for _, r := range s {
84+
switch r {
85+
case '\\':
86+
b.WriteString(`\\`)
87+
case '"':
88+
b.WriteString(`\"`)
89+
case '\n':
90+
b.WriteString(`\n`)
91+
case '\r':
92+
b.WriteString(`\r`)
93+
case '\t':
94+
b.WriteString(`\t`)
95+
default:
96+
b.WriteRune(r)
97+
}
98+
}
99+
return b.String()
82100
}

internal/extgen/cfile_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,16 @@ func TestEscapeCString(t *testing.T) {
521521
input: `Namespace\Über\Test`,
522522
expected: `Namespace\\Über\\Test`,
523523
},
524+
{
525+
name: "double quote is escaped",
526+
input: `say "hi"`,
527+
expected: `say \"hi\"`,
528+
},
529+
{
530+
name: "newline, carriage return and tab are escaped",
531+
input: "line1\nline2\r\tend",
532+
expected: `line1\nline2\r\tend`,
533+
},
524534
}
525535

526536
for _, tt := range tests {

0 commit comments

Comments
 (0)