summaryrefslogtreecommitdiff
path: root/cmd/btrfs-rec/util.go
blob: ffc03cc5d4527facef5541c5ce4c571e7369dac5 (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
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
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package main

import (
	"bufio"
	"context"
	"io"
	"os"
	"time"

	"git.lukeshu.com/go/lowmemjson"
	"github.com/datawire/dlib/dlog"

	"git.lukeshu.com/btrfs-progs-ng/lib/textui"
)

type runeScanner struct {
	progress       textui.Portion[int64]
	progressWriter *textui.Progress[textui.Portion[int64]]
	unreadCnt      uint64
	reader         *bufio.Reader
	closer         io.Closer
}

func newRuneScanner(ctx context.Context, fh *os.File) (*runeScanner, error) {
	fi, err := fh.Stat()
	if err != nil {
		return nil, err
	}
	ret := &runeScanner{
		progress: textui.Portion[int64]{
			D: fi.Size(),
		},
		progressWriter: textui.NewProgress[textui.Portion[int64]](ctx, dlog.LogLevelInfo, textui.Tunable(1*time.Second)),
		reader:         bufio.NewReader(fh),
		closer:         fh,
	}
	return ret, nil
}

func (rs *runeScanner) ReadRune() (r rune, size int, err error) {
	r, size, err = rs.reader.ReadRune()
	if rs.unreadCnt > 0 {
		rs.unreadCnt--
	} else {
		rs.progress.N += int64(size)
		rs.progressWriter.Set(rs.progress)
	}
	return
}

func (rs *runeScanner) UnreadRune() error {
	rs.unreadCnt++
	return rs.reader.UnreadRune()
}

func (rs *runeScanner) Close() error {
	rs.progressWriter.Done()
	return rs.closer.Close()
}

func readJSONFile[T any](ctx context.Context, filename string) (T, error) {
	fh, err := os.Open(filename)
	if err != nil {
		var zero T
		return zero, err
	}
	buf, err := newRuneScanner(dlog.WithField(ctx, "btrfs.read-json-file", filename), fh)
	if err != nil {
		var zero T
		return zero, err
	}
	var ret T
	if err := lowmemjson.DecodeThenEOF(buf, &ret); err != nil {
		var zero T
		return zero, err
	}
	_ = buf.Close()
	return ret, nil
}

func writeJSONFile(w io.Writer, obj any, cfg lowmemjson.ReEncoder) (err error) {
	buffer := bufio.NewWriter(w)
	defer func() {
		if _err := buffer.Flush(); err == nil && _err != nil {
			err = _err
		}
	}()
	cfg.Out = buffer
	return lowmemjson.Encode(&cfg, obj)
}