Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix handling of files #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions ouitools.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ package ouidb
import (
"bufio"
"errors"
"fmt"
"os"
"regexp"
"sort"
"strconv"
"strings"
)

const ouiReStr = `^(\S+)\t+(\S+)(\s+#\s+(\S.*))?`

var ErrInvalidMACAddress = errors.New("invalid MAC address")

// Helper functions
Expand Down Expand Up @@ -172,8 +175,9 @@ func (m *OuiDB) load(path string) error {
if err != nil {
return (err)
}
defer file.Close()

fieldsRe := regexp.MustCompile(`^(\S+)\t+(\S+)(\s+#\s+(\S.*))?`)
fieldsRe := regexp.MustCompile(ouiReStr)

scanner := bufio.NewScanner(file)
for scanner.Scan() {
Expand Down Expand Up @@ -238,20 +242,24 @@ func (m *OuiDB) load(path string) error {
return err
}

if len(m.blocks48) == 0 && len(m.blocks24) == 0 {
return fmt.Errorf("database is empty")
}

return nil
}

// New returns a new OUI database loaded from the specified file.
func New(file string) *OuiDB {
func New(file string) (*OuiDB, error) {
db := &OuiDB{}
if err := db.load(file); err != nil {
return nil
return nil, err
}

sort.Sort(db.blocks48)
sort.Sort(db.blocks24)

return db
return db, nil
}

func (db *OuiDB) blockLookup(address [6]byte) addressBlock {
Expand Down
19 changes: 10 additions & 9 deletions ouitools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,24 @@ func invalid(t *testing.T, mac string) {
}

func TestInitialization(t *testing.T) {
db = New("oui.txt")
if db == nil {
t.Fatal("can't load database file oui.txt")
var err error
db, err = New("oui.txt")
if err != nil {
t.Fatalf("can't load database file oui.txt: %s", err)
}
}

func TestMissingDBFile(t *testing.T) {
db := New("bad-file")
if db != nil {
t.Fatal("didn't return nil on missing file")
_, err := New("bad-file")
if err == nil {
t.Fatal("didn't return err on missing file")
}
}

func TestInvalidDBFile(t *testing.T) {
db := New("ouidb_test.go")
if db != nil {
t.Fatal("didn't return nil on bad file")
_, err := New("ouidb_test.go")
if err == nil {
t.Fatal("didn't return err on bad file")
}
}

Expand Down