File: bytes_content_range.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 872 kB
  • sloc: makefile: 4
file content (106 lines) | stat: -rw-r--r-- 1,902 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package httptoo

import (
	"fmt"
	"math"
	"regexp"
	"strconv"
	"strings"
)

type BytesContentRange struct {
	First, Last, Length int64
}

type BytesRange struct {
	First, Last int64
}

func (me BytesRange) String() string {
	if me.Last == math.MaxInt64 {
		return fmt.Sprintf("bytes=%d-", me.First)
	}
	return fmt.Sprintf("bytes=%d-%d", me.First, me.Last)
}

var (
	httpBytesRangeRegexp = regexp.MustCompile(`bytes[ =](\d+)-(\d*)`)
)

func ParseBytesRange(s string) (ret BytesRange, ok bool) {
	ss := httpBytesRangeRegexp.FindStringSubmatch(s)
	if ss == nil {
		return
	}
	var err error
	ret.First, err = strconv.ParseInt(ss[1], 10, 64)
	if err != nil {
		return
	}
	if ss[2] == "" {
		ret.Last = math.MaxInt64
	} else {
		ret.Last, err = strconv.ParseInt(ss[2], 10, 64)
		if err != nil {
			return
		}
	}
	ok = true
	return
}

func parseUnitRanges(s string) (unit, ranges string) {
	s = strings.TrimSpace(s)
	i := strings.IndexAny(s, " =")
	if i == -1 {
		return
	}
	unit = s[:i]
	ranges = s[i+1:]
	return
}

func parseFirstLast(s string) (first, last int64) {
	ss := strings.SplitN(s, "-", 2)
	first, err := strconv.ParseInt(ss[0], 10, 64)
	if err != nil {
		panic(err)
	}
	last, err = strconv.ParseInt(ss[1], 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func parseContentRange(s string) (ret BytesContentRange) {
	ss := strings.SplitN(s, "/", 2)
	firstLast := strings.TrimSpace(ss[0])
	if firstLast == "*" {
		ret.First = -1
		ret.Last = -1
	} else {
		ret.First, ret.Last = parseFirstLast(firstLast)
	}
	il := strings.TrimSpace(ss[1])
	if il == "*" {
		ret.Length = -1
	} else {
		var err error
		ret.Length, err = strconv.ParseInt(il, 10, 64)
		if err != nil {
			panic(err)
		}
	}
	return
}

func ParseBytesContentRange(s string) (ret BytesContentRange, ok bool) {
	unit, ranges := parseUnitRanges(s)
	if unit != "bytes" {
		return
	}
	ret = parseContentRange(ranges)
	ok = true
	return
}