utility.go (2058B)
1 package jpegstructure 2 3 import ( 4 "bytes" 5 "fmt" 6 "sort" 7 "strings" 8 9 "github.com/dsoprea/go-logging" 10 "github.com/go-xmlfmt/xmlfmt" 11 ) 12 13 // DumpBytes prints the hex for a given byte-slice. 14 func DumpBytes(data []byte) { 15 fmt.Printf("DUMP: ") 16 for _, x := range data { 17 fmt.Printf("%02x ", x) 18 } 19 20 fmt.Printf("\n") 21 } 22 23 // DumpBytesClause prints a Go-formatted byte-slice expression. 24 func DumpBytesClause(data []byte) { 25 fmt.Printf("DUMP: ") 26 27 fmt.Printf("[]byte { ") 28 29 for i, x := range data { 30 fmt.Printf("0x%02x", x) 31 32 if i < len(data)-1 { 33 fmt.Printf(", ") 34 } 35 } 36 37 fmt.Printf(" }\n") 38 } 39 40 // DumpBytesToString returns a string of hex-encoded bytes. 41 func DumpBytesToString(data []byte) string { 42 b := new(bytes.Buffer) 43 44 for i, x := range data { 45 _, err := b.WriteString(fmt.Sprintf("%02x", x)) 46 log.PanicIf(err) 47 48 if i < len(data)-1 { 49 _, err := b.WriteRune(' ') 50 log.PanicIf(err) 51 } 52 } 53 54 return b.String() 55 } 56 57 // DumpBytesClauseToString returns a string of Go-formatted byte values. 58 func DumpBytesClauseToString(data []byte) string { 59 b := new(bytes.Buffer) 60 61 for i, x := range data { 62 _, err := b.WriteString(fmt.Sprintf("0x%02x", x)) 63 log.PanicIf(err) 64 65 if i < len(data)-1 { 66 _, err := b.WriteString(", ") 67 log.PanicIf(err) 68 } 69 } 70 71 return b.String() 72 } 73 74 // FormatXml prettifies XML data. 75 func FormatXml(raw string) (formatted string, err error) { 76 defer func() { 77 if state := recover(); state != nil { 78 err = log.Wrap(state.(error)) 79 } 80 }() 81 82 formatted = xmlfmt.FormatXML(raw, " ", " ") 83 formatted = strings.TrimSpace(formatted) 84 85 return formatted, nil 86 } 87 88 // SortStringStringMap sorts a string-string dictionary and returns it as a list 89 // of 2-tuples. 90 func SortStringStringMap(data map[string]string) (sorted [][2]string) { 91 // Sort keys. 92 93 sortedKeys := make([]string, len(data)) 94 i := 0 95 for key := range data { 96 sortedKeys[i] = key 97 i++ 98 } 99 100 sort.Strings(sortedKeys) 101 102 // Build result. 103 104 sorted = make([][2]string, len(sortedKeys)) 105 for i, key := range sortedKeys { 106 sorted[i] = [2]string{key, data[key]} 107 } 108 109 return sorted 110 }