Debian Codegraph @

internal/magic/netpbm.go

raw symbols SCIP
1 package magic
2
3 import (
4 "bytes"
5 "strconv"
6
7 "github.com/gabriel-vasile/mimetype/internal/scan"
8 )
9
10 // NetPBM matches a Netpbm Portable BitMap ASCII/Binary file.
11 //
12 // See: https://en.wikipedia.org/wiki/Netpbm
13 func NetPBM(raw []byte, _ uint32) bool {
14 return netp(raw, "P1\n", "P4\n")
15 }
16
17 // NetPGM matches a Netpbm Portable GrayMap ASCII/Binary file.
18 //
19 // See: https://en.wikipedia.org/wiki/Netpbm
20 func NetPGM(raw []byte, _ uint32) bool {
21 return netp(raw, "P2\n", "P5\n")
22 }
23
24 // NetPPM matches a Netpbm Portable PixMap ASCII/Binary file.
25 //
26 // See: https://en.wikipedia.org/wiki/Netpbm
27 func NetPPM(raw []byte, _ uint32) bool {
28 return netp(raw, "P3\n", "P6\n")
29 }
30
31 // NetPAM matches a Netpbm Portable Arbitrary Map file.
32 //
33 // See: https://en.wikipedia.org/wiki/Netpbm
34 func NetPAM(raw []byte, _ uint32) bool {
35 if !bytes.HasPrefix(raw, []byte("P7\n")) {
36 return false
37 }
38 w, h, d, m, e := false, false, false, false, false
39 s := scan.Bytes(raw)
40 var l scan.Bytes
41 // Read line by line.
42 for i := 0; i < 128; i++ {
43 l = s.Line()
44 // If the line is empty or a comment, skip.
45 if len(l) == 0 || l.Peek() == '#' {
46 if len(s) == 0 {
47 return false
48 }
49 continue
50 } else if bytes.HasPrefix(l, []byte("TUPLTYPE")) {
51 continue
52 } else if bytes.HasPrefix(l, []byte("WIDTH ")) {
53 w = true
54 } else if bytes.HasPrefix(l, []byte("HEIGHT ")) {
55 h = true
56 } else if bytes.HasPrefix(l, []byte("DEPTH ")) {
57 d = true
58 } else if bytes.HasPrefix(l, []byte("MAXVAL ")) {
59 m = true
60 } else if bytes.HasPrefix(l, []byte("ENDHDR")) {
61 e = true
62 }
63 // When we reached header, return true if we collected all four required headers.
64 // WIDTH, HEIGHT, DEPTH and MAXVAL.
65 if e {
66 return w && h && d && m
67 }
68 }
69 return false
70 }
71
72 func netp(s scan.Bytes, prefixes ...string) bool {
73 foundPrefix := ""
74 for _, p := range prefixes {
75 if bytes.HasPrefix(s, []byte(p)) {
76 foundPrefix = p
77 }
78 }
79 if foundPrefix == "" {
80 return false
81 }
82 s.Advance(len(foundPrefix)) // jump over P1, P2, P3, etc.
83
84 var l scan.Bytes
85 // Read line by line.
86 for i := 0; i < 128; i++ {
87 l = s.Line()
88 // If the line is a comment, skip.
89 if l.Peek() == '#' {
90 continue
91 }
92 // If line has leading whitespace, then skip over whitespace.
93 for scan.ByteIsWS(l.Peek()) {
94 l.Advance(1)
95 }
96 if len(s) == 0 || len(l) > 0 {
97 break
98 }
99 }
100
101 // At this point l should be the two integers denoting the size of the matrix.
102 width := l.PopUntil(scan.ASCIISpaces...)
103 for scan.ByteIsWS(l.Peek()) {
104 l.Advance(1)
105 }
106 height := l.PopUntil(scan.ASCIISpaces...)
107
108 w, errw := strconv.ParseInt(string(width), 10, 64)
109 h, errh := strconv.ParseInt(string(height), 10, 64)
110 return errw == nil && errh == nil && w > 0 && h > 0
111 }