main.go at [89bfe97384]

File src/0dev.org/commands/pdc/main.go artifact c6f8b3fe28 part of check-in 89bfe97384


package main

import (
	predictor "0dev.org/predictor"
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	switch {
	case len(os.Args) == 1:
		os.Exit(compress(os.Stdout, os.Stdin))
	case len(os.Args) == 2 && os.Args[1] == "-d":
		os.Exit(decompress(os.Stdout, os.Stdin))
	default:
		fmt.Fprintln(os.Stdout, "Usage: pdc [-d]")
	}
}

// Compress the data from the given io.Reader and write it to the given io.Writer
// I/O is buffered for better performance
func compress(output io.Writer, input io.Reader) int {
	var (
		err        error
		buffer     *bufio.Writer = bufio.NewWriter(output)
		compressor io.Writer     = predictor.Compressor(buffer)
	)

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

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

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

	return 0
}

// Decompress the data from the given io.Reader and write it to the given io.Writer
// I/O is buffered for better performance
func decompress(output io.Writer, input io.Reader) int {
	var (
		err          error
		buffer       *bufio.Writer = bufio.NewWriter(output)
		decompressor io.Reader     = predictor.Decompressor(bufio.NewReader(input))
	)

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

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

	return 0
}