File: lex.go

package info (click to toggle)
golang-github-malfunkt-iprange 0.9.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 116 kB
  • sloc: yacc: 86; makefile: 2
file content (84 lines) | stat: -rw-r--r-- 1,333 bytes parent folder | download | duplicates (2)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package iprange

import (
	"bytes"
	"errors"
	"log"
	"strconv"
	"unicode/utf8"
)

const eof = 0

type ipLex struct {
	line   []byte
	peek   rune
	output AddressRangeList
	err    error
}

func (ip *ipLex) Lex(yylval *ipSymType) int {
	for {
		c := ip.next()
		switch c {
		case eof:
			return eof
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return ip.byte(c, yylval)
		default:
			return int(c)
		}
	}
}

func (ip *ipLex) byte(c rune, yylval *ipSymType) int {
	add := func(b *bytes.Buffer, c rune) {
		if _, err := b.WriteRune(c); err != nil {
			log.Fatalf("WriteRune: %s", err)
		}
	}
	var b bytes.Buffer
	add(&b, c)
L:
	for {
		c = ip.next()
		switch c {
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			add(&b, c)
		default:
			break L
		}
	}
	if c != eof {
		ip.peek = c
	}
	octet, err := strconv.ParseUint(b.String(), 10, 32)
	if err != nil {
		log.Printf("badly formatted octet")
		return eof
	}
	yylval.num = byte(octet)
	return num
}

func (ip *ipLex) next() rune {
	if ip.peek != eof {
		r := ip.peek
		ip.peek = eof
		return r
	}
	if len(ip.line) == 0 {
		return eof
	}
	c, size := utf8.DecodeRune(ip.line)
	ip.line = ip.line[size:]
	if c == utf8.RuneError && size == 1 {
		log.Print("invalid utf8")
		return ip.next()
	}
	return c
}

func (ip *ipLex) Error(s string) {
	ip.err = errors.New(s)
}