summaryrefslogtreecommitdiff
path: root/pkg/btrfs/btrfsitem/items.go
blob: 91b7029a69176f901b40bd0ba8b301af5fad680b (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
package btrfsitem

import (
	"fmt"
	"reflect"

	"lukeshu.com/btrfs-tools/pkg/binstruct"
	"lukeshu.com/btrfs-tools/pkg/btrfs/internal"
)

type Type = internal.ItemType

type Item interface {
	isItem()
}

func UnmarshalItem(keytyp Type, dat []byte) (Item, error) {
	gotyp, ok := keytype2gotype[keytyp]
	if !ok {
		return nil, fmt.Errorf("btrfsitem.UnmarshalItem: unknown item type: %v", keytyp)
	}
	retPtr := reflect.New(gotyp)
	n, err := binstruct.Unmarshal(dat, retPtr.Interface())
	if err != nil {
		return nil, fmt.Errorf("btrfsitem.UnmarshalItem: %w", err)
	}
	if n < len(dat) {
		return nil, fmt.Errorf("btrfsitem.UnmarshalItem: left over data: got %d bytes but only consumed %d",
			len(dat), n)
	}
	return retPtr.Elem().Interface().(Item), nil
}