-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
85 lines (64 loc) · 1.59 KB
/
main.go
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
package fleep
import (
"bytes"
"errors"
)
// GetInfo returns file info
func GetInfo(file []byte) (Info, error) {
var info Info
sequence, err := getSequenceFromFile(file)
if err != nil {
return info, err
}
info, err = getInfo(sequence)
if err != nil {
return info, err
}
return info, nil
}
func getSequenceFromFile(file []byte) ([]byte, error) {
sequenceLength := 128
if len(file) < sequenceLength {
return nil, errors.New("not enough bytes")
}
sequence := file[:sequenceLength]
return sequence, nil
}
func getInfo(sequence []byte) (Info, error) {
var info Info
items := findMatchesInCollection(sequence)
if len(items) == 0 {
return info, errors.New("unknown file format")
}
info = constructInfo(items)
return info, nil
}
func findMatchesInCollection(sequence []byte) []collectionItem {
var selectedItems []collectionItem
for _, item := range collection {
if itemMatches(item, sequence) {
selectedItems = append(selectedItems, item)
}
}
return selectedItems
}
func itemMatches(item collectionItem, sequence []byte) bool {
for _, signature := range item.Signature {
if signatureMatches(signature, item.Offset, sequence) {
return true
}
}
return false
}
func signatureMatches(signature []byte, offset int, sequence []byte) bool {
return bytes.Equal(sequence[offset:offset+len(signature)], signature)
}
func constructInfo(items []collectionItem) Info {
var info Info
for _, item := range items {
info.Type = append(info.Type, item.Type)
info.Extension = append(info.Extension, item.Extension)
info.Mime = append(info.Mime, item.Mime)
}
return info
}