~shulhan/asciidoctor-go

ref: v0.1.0 asciidoctor-go/section_counters.go -rw-r--r-- 1.0 KiB
4c1ded16Shulhan Release asciidoctor-go v0.1.0 (2021-03-06) 4 months ago
                                                                                
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
// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package asciidoctor

import (
	"fmt"
	"strings"
)

type sectionCounters struct {
	// index 0 represent counter for level 0,
	// index 1 represent coutner for level 1, and so on.
	nums [6]byte
	curr int
}

func (sec *sectionCounters) set(level int) *sectionCounters {
	if level == sec.curr {
		sec.nums[level]++
	} else if level > sec.curr {
		// Check if the section level out of sequence.
		if level > sec.curr+1 {
			level = sec.curr + 1
		}
		sec.nums[level] = 1
		sec.curr = level
	} else {
		for x := sec.curr; x > level; x-- {
			sec.nums[x] = 0
		}
		sec.nums[level]++
		sec.curr = level
	}
	clone := *sec
	return &clone
}

func (sec *sectionCounters) String() string {
	var (
		sb strings.Builder
	)

	for x := 1; x < 6; x++ {
		if sec.nums[x] == 0 {
			break
		}
		fmt.Fprintf(&sb, "%d.", sec.nums[x])
	}
	sb.WriteByte(' ')
	return sb.String()
}