-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathids.go
59 lines (51 loc) · 1.17 KB
/
ids.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package toc
import (
"fmt"
"github.com/gosimple/slug"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/util"
)
// Lang define the default language for generating slug id fo headers.
var Lang = ""
type ids struct {
lang string
values map[string]struct{}
}
// NewIDs return initialized ID generator for goldmark parser context.
func NewIDs(lang string) parser.IDs {
return &ids{
lang: lang,
values: make(map[string]struct{}),
}
}
func (s *ids) Generate(value []byte, kind ast.NodeKind) []byte {
var (
slugStr = slug.MakeLang(
util.BytesToReadOnlyString(value), s.lang)
counter int
)
if slugStr == "" {
slugStr = "id"
}
var result = slugStr
for {
if _, ok := s.values[result]; !ok {
s.values[result] = struct{}{}
return util.StringToReadOnlyBytes(result)
}
counter++
result = fmt.Sprintf("%s-%d", slugStr, counter)
}
}
func (s *ids) Put(value []byte) {
s.values[util.BytesToReadOnlyString(value)] = struct{}{}
}
// WithIDs return new initializer parser option with ID generator.
func WithIDs() parser.ParseOption {
return parser.WithContext(
parser.NewContext(
parser.WithIDs(NewIDs(Lang)),
),
)
}