summaryrefslogtreecommitdiff
path: root/lib/diskio/seq.go
blob: 3c5f4ae3c427d9f47cfa932265987b1a79bf74d3 (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package diskio

import (
	"fmt"
	"io"
)

// interface /////////////////////////////////////////////////////////

type Sequence[K ~int64, V any] interface {
	// Get the value at 'pos' in the sequence.  Positions start at
	// 0 and increment naturally.  Return an error that is io.EOF
	// if 'pos' is past the end of the sequence'.
	Get(pos K) (V, error)
}

// implementation: slice /////////////////////////////////////////////

type SliceSequence[K ~int64, V any] []V

var _ Sequence[assertAddr, byte] = SliceSequence[assertAddr, byte]([]byte(nil))

func (s SliceSequence[K, V]) Get(i K) (V, error) {
	if i >= K(len(s)) {
		var v V
		return v, io.EOF
	}
	return s[int(i)], nil
}

// implementation: string ////////////////////////////////////////////

type StringSequence[K ~int64] string

var _ Sequence[assertAddr, byte] = StringSequence[assertAddr]("")

func (s StringSequence[K]) Get(i K) (byte, error) {
	if i >= K(len(s)) {
		return 0, io.EOF
	}
	return s[int(i)], nil
}

// implementation: io.ByteReader /////////////////////////////////////

type ByteReaderSequence[K ~int64] struct {
	R   io.ByteReader
	pos K
}

var _ Sequence[assertAddr, byte] = &ByteReaderSequence[assertAddr]{R: nil}

func (s *ByteReaderSequence[K]) Get(i K) (byte, error) {
	if i != s.pos {
		return 0, fmt.Errorf("%T.Get(%v): can only call .Get(%v)",
			s, i, s.pos)
	}
	chr, err := s.R.ReadByte()
	if err != nil {
		return chr, err
	}
	s.pos++
	return chr, nil
}