Check-in [e72b637df4]
Overview
Comment:Initial implementation of commands/mtf (based on commands/pdc)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:e72b637df4da3b4267e03d12fedcf6a0d31efe8c
User & Date: spaskalev on 2014-12-26 16:02:18
Other Links: manifest | tags
Context
2014-12-26
21:35
Added 0dev.org/types, providing aliases that implement sort.Interface for [u]int{8|16|32|64} check-in: 129d90b4a8 user: spaskalev tags: trunk
16:02
Initial implementation of commands/mtf (based on commands/pdc) check-in: e72b637df4 user: spaskalev tags: trunk
15:50
Initial implementation of package mtf - a move-to-front transform. check-in: ad5c25d9ab user: spaskalev tags: trunk
Changes

Added src/0dev.org/commands/mtf/main.go version [b672c1daee].

































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
package main

import (
	iou "0dev.org/ioutil"
	mtf "0dev.org/mtf"
	"fmt"
	"io"
	"os"
)

func main() {
	var code int
	switch {
	case len(os.Args) == 1:
		code = transform(os.Stdout, os.Stdin)
	case len(os.Args) == 2 && os.Args[1] == "-d":
		code = reverse(os.Stdout, os.Stdin)
	default:
		fmt.Fprintln(os.Stdout, "Usage: mtf [-d]")
	}
	os.Exit(code)
}

// Transforms the data according to the move-to-front algorithm
// I/O is buffered for better performance
func transform(output io.Writer, input io.Reader) int {
	var (
		err     error
		buffer  io.Writer = iou.SizedWriter(output, 4096)
		encoder io.Writer = mtf.Encoder(buffer)
	)

	_, err = io.Copy(encoder, input)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error while encoding.\n", err)
		return 1
	}

	// Flush the buffer
	_, err = buffer.Write(nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error while flushing output buffer.\n", err)
		return 1
	}

	return 0
}

// Reverses MTF`ed data and writes back the original bytes
// I/O is buffered for better performance
func reverse(output io.Writer, input io.Reader) int {
	var (
		err     error
		decoder io.Reader = mtf.Decoder(iou.SizedReader(input, 4096))
	)

	_, err = io.Copy(output, decoder)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error while decoding.\n", err)
		return 1
	}

	return 0
}