Skip to content
This repository has been archived by the owner on Jun 4, 2019. It is now read-only.

Commit

Permalink
Add ReadFrom and WriteTo methods
Browse files Browse the repository at this point in the history
These operate on the io.Writer/io.Reader interfaces which should make them
more widely applicable. We also change the Load function to use ReadFrom.
  • Loading branch information
Shugyousha committed Mar 4, 2016
1 parent ab6b5ab commit bf990f0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
14 changes: 14 additions & 0 deletions decoder.go
Expand Up @@ -3,6 +3,8 @@ package mafsa
import (
"encoding/binary"
"errors"
"io"
"io/ioutil"
)

// Decoder is a type which can decode a byte slice into a MinTree.
Expand All @@ -22,6 +24,18 @@ func (d *Decoder) Decode(data []byte) (*MinTree, error) {
return tree, d.decodeMinTree(tree, data)
}

// ReadFrom reads the binary serialization of a MA-FSA into a
// new MinTree (a read-only MA-FSA) from a io.Reader.
func (d *Decoder) ReadFrom(r io.Reader) (*MinTree, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}

tree := newMinTree()
return tree, d.decodeMinTree(tree, data)
}

// decodeMinTree transforms the binary serialization of a MA-FSA into a
// read-only MA-FSA pointed to by t.
func (d *Decoder) decodeMinTree(t *MinTree, data []byte) error {
Expand Down
17 changes: 17 additions & 0 deletions encoder.go
@@ -1,7 +1,9 @@
package mafsa

import (
"bytes"
"encoding/binary"
"io"
"sort"
)

Expand Down Expand Up @@ -45,6 +47,21 @@ func (e *Encoder) Encode(t *BuildTree) ([]byte, error) {
return data, nil
}

// WriteTo encodes and saves the BuildTree to a io.Writer.
func (e *Encoder) WriteTo(wr io.Writer, t *BuildTree) error {
bs, err := e.Encode(t)
if err != nil {
return err
}

_, err = io.Copy(wr, bytes.NewReader(bs))
if err != nil {
return err
}

return nil
}

// encodeEdges encodes the edges going out of node into bytes which are appended
// to data. The modified byte slice is returned.
func (e *Encoder) encodeEdges(node *BuildTreeNode, data []byte) []byte {
Expand Down
7 changes: 3 additions & 4 deletions mafsa.go
@@ -1,6 +1,6 @@
package mafsa

import "io/ioutil"
import "os"

// New constructs a new, empty MA-FSA that can be filled with data.
func New() *BuildTree {
Expand All @@ -14,12 +14,11 @@ func New() *BuildTree {
// Load loads an existing MA-FSA from a file specified by filename.
// It returns a read-only MA-FSA, or an error if loading failed.
func Load(filename string) (*MinTree, error) {
data, err := ioutil.ReadFile(filename)
f, err := os.Open(filename)
if err != nil {
return nil, err
}

mtree, err := new(Decoder).Decode(data)
mtree, err := new(Decoder).ReadFrom(f)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit bf990f0

Please sign in to comment.