git.lucas.co / go_mono
git clone https://git.lucas.co/go_mono.git

riff/example_test.go (2.2K)

  1 // Copyright 2014 The Go Authors. All rights reserved.
  2 // Use of this source code is governed by a BSD-style
  3 // license that can be found in the LICENSE file.
  4 
  5 package riff_test
  6 
  7 import (
  8 	"fmt"
  9 	"io"
 10 	"io/ioutil"
 11 	"log"
 12 	"strings"
 13 
 14 	"golang.org/x/image/riff"
 15 )
 16 
 17 func ExampleReader() {
 18 	formType, r, err := riff.NewReader(strings.NewReader(data))
 19 	if err != nil {
 20 		log.Fatal(err)
 21 	}
 22 	fmt.Printf("RIFF(%s)\n", formType)
 23 	if err := dump(r, ".\t"); err != nil {
 24 		log.Fatal(err)
 25 	}
 26 	// Output:
 27 	// RIFF(ROOT)
 28 	// .	ZERO ""
 29 	// .	ONE  "a"
 30 	// .	LIST(META)
 31 	// .	.	LIST(GOOD)
 32 	// .	.	.	ONE  "a"
 33 	// .	.	.	FIVE "klmno"
 34 	// .	.	ZERO ""
 35 	// .	.	LIST(BAD )
 36 	// .	.	.	THRE "def"
 37 	// .	TWO  "bc"
 38 	// .	LIST(UGLY)
 39 	// .	.	FOUR "ghij"
 40 	// .	.	SIX  "pqrstu"
 41 }
 42 
 43 func dump(r *riff.Reader, indent string) error {
 44 	for {
 45 		chunkID, chunkLen, chunkData, err := r.Next()
 46 		if err == io.EOF {
 47 			return nil
 48 		}
 49 		if err != nil {
 50 			return err
 51 		}
 52 		if chunkID == riff.LIST {
 53 			listType, list, err := riff.NewListReader(chunkLen, chunkData)
 54 			if err != nil {
 55 				return err
 56 			}
 57 			fmt.Printf("%sLIST(%s)\n", indent, listType)
 58 			if err := dump(list, indent+".\t"); err != nil {
 59 				return err
 60 			}
 61 			continue
 62 		}
 63 		b, err := ioutil.ReadAll(chunkData)
 64 		if err != nil {
 65 			return err
 66 		}
 67 		fmt.Printf("%s%s %q\n", indent, chunkID, b)
 68 	}
 69 }
 70 
 71 func encodeU32(u uint32) string {
 72 	return string([]byte{
 73 		byte(u >> 0),
 74 		byte(u >> 8),
 75 		byte(u >> 16),
 76 		byte(u >> 24),
 77 	})
 78 }
 79 
 80 func encode(chunkID, contents string) string {
 81 	n := len(contents)
 82 	if n&1 == 1 {
 83 		contents += "\x00"
 84 	}
 85 	return chunkID + encodeU32(uint32(n)) + contents
 86 }
 87 
 88 func encodeMulti(typ0, typ1 string, chunks ...string) string {
 89 	n := 4
 90 	for _, c := range chunks {
 91 		n += len(c)
 92 	}
 93 	s := typ0 + encodeU32(uint32(n)) + typ1
 94 	for _, c := range chunks {
 95 		s += c
 96 	}
 97 	return s
 98 }
 99 
100 var (
101 	d0   = encode("ZERO", "")
102 	d1   = encode("ONE ", "a")
103 	d2   = encode("TWO ", "bc")
104 	d3   = encode("THRE", "def")
105 	d4   = encode("FOUR", "ghij")
106 	d5   = encode("FIVE", "klmno")
107 	d6   = encode("SIX ", "pqrstu")
108 	l0   = encodeMulti("LIST", "GOOD", d1, d5)
109 	l1   = encodeMulti("LIST", "BAD ", d3)
110 	l2   = encodeMulti("LIST", "UGLY", d4, d6)
111 	l01  = encodeMulti("LIST", "META", l0, d0, l1)
112 	data = encodeMulti("RIFF", "ROOT", d0, d1, l01, d2, l2)
113 )