aboutsummaryrefslogtreecommitdiff
path: root/go/typdown.go
blob: 386b77956b25c576c3048cba0552e2a2addd2e70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package typdown

// #cgo LDFLAGS: -L${SRCDIR}/zig-out/lib -ltypdown
// #include <stdlib.h>
// #include "typdown.h"
import "C"
import (
	"errors"
	"html/template"
	"unsafe"
)

var (
	codeErrors = map[uint8]error{
		1: errors.New("out of memory"),
		2: ErrInvalidUtf8,
		3: ErrNotSupported,
		4: ErrModifierNotClosed,
		5: ErrInvalidTitleContent,
		6: ErrIllegalPlacement,
		7: ErrInvalidLink,
	}
	ErrInvalidUtf8         = errors.New("invalid UTF-8")
	ErrNotSupported        = errors.New("feature not supported")
	ErrModifierNotClosed   = errors.New("modifier not closed")
	ErrInvalidTitleContent = errors.New("invalid title content")
	ErrIllegalPlacement    = errors.New("illegal placement")
	ErrInvalidLink         = errors.New("invalid link")
)

func Parse(content string) (template.HTML, error) {
	code := C.uchar(0)
	conv := C.CString(content)
	raw := C.typdown_parse(conv, &code)
	defer C.free(unsafe.Pointer(conv))
	if code > 0 {
		err := codeErrors[uint8(code)]
		if code == 1 {
			panic(err)
		}
		return "", err
	}
	defer C.free(unsafe.Pointer(raw))
	return template.HTML(C.GoString(raw)), nil
}