Commit 45ca9f7a authored by Robert Griesemer's avatar Robert Griesemer

1) Change default gofmt default settings for

   parsing and printing to new syntax.

   Use -oldparser to parse the old syntax,
   use -oldprinter to print the old syntax.

2) Change default gofmt formatting settings
   to use tabs for indentation only and to use
   spaces for alignment. This will make the code
   alignment insensitive to an editor's tabwidth.

   Use -spaces=false to use tabs for alignment.

3) Manually changed src/exp/parser/parser_test.go
   so that it doesn't try to parse the parser's
   source files using the old syntax (they have
   new syntax now).

4) gofmt -w src misc test/bench

5th and last set of files.

R=rsc
CC=golang-dev
https://golang.org/cl/180050
parent d65a5cce
......@@ -9,10 +9,10 @@
package syslog
import (
"fmt";
"log";
"net";
"os";
"fmt"
"log"
"net"
"os"
)
type Priority int
......@@ -20,21 +20,21 @@ type Priority int
const (
// From /usr/include/sys/syslog.h.
// These are the same on Linux, BSD, and OS X.
LOG_EMERG Priority = iota;
LOG_ALERT;
LOG_CRIT;
LOG_ERR;
LOG_WARNING;
LOG_NOTICE;
LOG_INFO;
LOG_DEBUG;
LOG_EMERG Priority = iota
LOG_ALERT
LOG_CRIT
LOG_ERR
LOG_WARNING
LOG_NOTICE
LOG_INFO
LOG_DEBUG
)
// A Writer is a connection to a syslog server.
type Writer struct {
priority Priority;
prefix string;
conn net.Conn;
priority Priority
prefix string
conn net.Conn
}
// New establishes a new connection to the system log daemon.
......@@ -52,23 +52,23 @@ func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, e
if prefix == "" {
prefix = os.Args[0]
}
var conn net.Conn;
var conn net.Conn
if network == "" {
conn, err = unixSyslog()
} else {
conn, err = net.Dial(network, "", raddr)
}
return &Writer{priority, prefix, conn}, err;
return &Writer{priority, prefix, conn}, err
}
func unixSyslog() (conn net.Conn, err os.Error) {
logTypes := []string{"unixgram", "unix"};
logPaths := []string{"/dev/log", "/var/run/syslog"};
var raddr string;
logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}
var raddr string
for _, network := range logTypes {
for _, path := range logPaths {
raddr = path;
conn, err := net.Dial(network, "", raddr);
raddr = path
conn, err := net.Dial(network, "", raddr)
if err != nil {
continue
} else {
......@@ -76,7 +76,7 @@ func unixSyslog() (conn net.Conn, err os.Error) {
}
}
}
return nil, os.ErrorString("Unix syslog delivery error");
return nil, os.ErrorString("Unix syslog delivery error")
}
// Write sends a log message to the syslog daemon.
......@@ -84,51 +84,51 @@ func (w *Writer) Write(b []byte) (int, os.Error) {
if w.priority > LOG_DEBUG || w.priority < LOG_EMERG {
return 0, os.EINVAL
}
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b);
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b)
}
func (w *Writer) writeString(p Priority, s string) (int, os.Error) {
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", p, w.prefix, s)
}
func (w *Writer) Close() os.Error { return w.conn.Close() }
func (w *Writer) Close() os.Error { return w.conn.Close() }
// Emerg logs a message using the LOG_EMERG priority.
func (w *Writer) Emerg(m string) (err os.Error) {
_, err = w.writeString(LOG_EMERG, m);
return err;
_, err = w.writeString(LOG_EMERG, m)
return err
}
// Crit logs a message using the LOG_CRIT priority.
func (w *Writer) Crit(m string) (err os.Error) {
_, err = w.writeString(LOG_CRIT, m);
return err;
_, err = w.writeString(LOG_CRIT, m)
return err
}
// ERR logs a message using the LOG_ERR priority.
func (w *Writer) Err(m string) (err os.Error) {
_, err = w.writeString(LOG_ERR, m);
return err;
_, err = w.writeString(LOG_ERR, m)
return err
}
// Warning logs a message using the LOG_WARNING priority.
func (w *Writer) Warning(m string) (err os.Error) {
_, err = w.writeString(LOG_WARNING, m);
return err;
_, err = w.writeString(LOG_WARNING, m)
return err
}
// Notice logs a message using the LOG_NOTICE priority.
func (w *Writer) Notice(m string) (err os.Error) {
_, err = w.writeString(LOG_NOTICE, m);
return err;
_, err = w.writeString(LOG_NOTICE, m)
return err
}
// Info logs a message using the LOG_INFO priority.
func (w *Writer) Info(m string) (err os.Error) {
_, err = w.writeString(LOG_INFO, m);
return err;
_, err = w.writeString(LOG_INFO, m)
return err
}
// Debug logs a message using the LOG_DEBUG priority.
func (w *Writer) Debug(m string) (err os.Error) {
_, err = w.writeString(LOG_DEBUG, m);
return err;
_, err = w.writeString(LOG_DEBUG, m)
return err
}
// NewLogger provides an object that implements the full log.Logger interface,
......@@ -136,9 +136,9 @@ func (w *Writer) Debug(m string) (err os.Error) {
// priority will be used for all messages sent using this interface.
// All messages are logged with priority p.
func NewLogger(p Priority, flag int) *log.Logger {
s, err := New(p, "");
s, err := New(p, "")
if err != nil {
return nil
}
return log.New(s, nil, "", flag);
return log.New(s, nil, "", flag)
}
......@@ -4,91 +4,91 @@
package syslog
import (
"io";
"log";
"net";
"testing";
"io"
"log"
"net"
"testing"
)
var serverAddr string
func runSyslog(c net.PacketConn, done chan<- string) {
var buf [4096]byte;
var rcvd string = "";
var buf [4096]byte
var rcvd string = ""
for {
n, _, err := c.ReadFrom(&buf);
n, _, err := c.ReadFrom(&buf)
if err != nil || n == 0 {
break
}
rcvd += string(buf[0:n]);
rcvd += string(buf[0:n])
}
done <- rcvd;
done <- rcvd
}
func startServer(done chan<- string) {
c, e := net.ListenPacket("udp", ":0");
c, e := net.ListenPacket("udp", ":0")
if e != nil {
log.Exitf("net.ListenPacket failed udp :0 %v", e)
}
serverAddr = c.LocalAddr().String();
c.SetReadTimeout(10e6); // 10ms
go runSyslog(c, done);
serverAddr = c.LocalAddr().String()
c.SetReadTimeout(10e6) // 10ms
go runSyslog(c, done)
}
func TestNew(t *testing.T) {
s, err := New(LOG_INFO, "");
s, err := New(LOG_INFO, "")
if err != nil {
t.Fatalf("New() failed: %s", err)
}
// Don't send any messages.
s.Close();
s.Close()
}
func TestNewLogger(t *testing.T) {
f := NewLogger(LOG_INFO, 0);
f := NewLogger(LOG_INFO, 0)
if f == nil {
t.Errorf("NewLogger() failed\n")
}
}
func TestDial(t *testing.T) {
l, err := Dial("", "", LOG_ERR, "syslog_test");
l, err := Dial("", "", LOG_ERR, "syslog_test")
if err != nil {
t.Fatalf("Dial() failed: %s", err)
}
l.Close();
l.Close()
}
func TestUDPDial(t *testing.T) {
done := make(chan string);
startServer(done);
l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test");
done := make(chan string)
startServer(done)
l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test")
if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err)
}
msg := "udp test";
l.Info(msg);
expected := "<6>syslog_test: udp test\n";
rcvd := <-done;
msg := "udp test"
l.Info(msg)
expected := "<6>syslog_test: udp test\n"
rcvd := <-done
if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
}
}
func TestWrite(t *testing.T) {
done := make(chan string);
startServer(done);
l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test");
done := make(chan string)
startServer(done)
l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test")
if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err)
}
msg := "write test";
_, err = io.WriteString(l, msg);
msg := "write test"
_, err = io.WriteString(l, msg)
if err != nil {
t.Fatalf("WriteString() failed: %s", err)
}
expected := "<3>syslog_test: write test\n";
rcvd := <-done;
expected := "<3>syslog_test: write test\n"
rcvd := <-done
if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
}
......
This diff is collapsed.
......@@ -5,43 +5,43 @@
package tabwriter
import (
"io";
"os";
"testing";
"io"
"os"
"testing"
)
type buffer struct {
a []byte;
a []byte
}
func (b *buffer) init(n int) { b.a = make([]byte, n)[0:0] }
func (b *buffer) init(n int) { b.a = make([]byte, n)[0:0] }
func (b *buffer) clear() { b.a = b.a[0:0] }
func (b *buffer) clear() { b.a = b.a[0:0] }
func (b *buffer) Write(buf []byte) (written int, err os.Error) {
n := len(b.a);
m := len(buf);
n := len(b.a)
m := len(buf)
if n+m <= cap(b.a) {
b.a = b.a[0 : n+m];
b.a = b.a[0 : n+m]
for i := 0; i < m; i++ {
b.a[n+i] = buf[i]
}
} else {
panicln("buffer.Write: buffer too small", n, m, cap(b.a))
}
return len(buf), nil;
return len(buf), nil
}
func (b *buffer) String() string { return string(b.a) }
func (b *buffer) String() string { return string(b.a) }
func write(t *testing.T, testname string, w *Writer, src string) {
written, err := io.WriteString(w, src);
written, err := io.WriteString(w, src)
if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- write error: %v\n", testname, src, err)
}
......@@ -52,12 +52,12 @@ func write(t *testing.T, testname string, w *Writer, src string) {
func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected string) {
err := w.Flush();
err := w.Flush()
if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- flush error: %v\n", testname, src, err)
}
res := b.String();
res := b.String()
if res != expected {
t.Errorf("--- test: %s\n--- src:\n%s\n--- found:\n%s\n--- expected:\n%s\n", testname, src, res, expected)
}
......@@ -65,43 +65,43 @@ func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected s
func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padchar byte, flags uint, src, expected string) {
var b buffer;
b.init(1000);
var b buffer
b.init(1000)
var w Writer;
w.Init(&b, minwidth, tabwidth, padding, padchar, flags);
var w Writer
w.Init(&b, minwidth, tabwidth, padding, padchar, flags)
// write all at once
b.clear();
write(t, testname, &w, src);
verify(t, testname, &w, &b, src, expected);
b.clear()
write(t, testname, &w, src)
verify(t, testname, &w, &b, src, expected)
// write byte-by-byte
b.clear();
b.clear()
for i := 0; i < len(src); i++ {
write(t, testname, &w, src[i:i+1])
}
verify(t, testname, &w, &b, src, expected);
verify(t, testname, &w, &b, src, expected)
// write using Fibonacci slice sizes
b.clear();
b.clear()
for i, d := 0, 0; i < len(src); {
write(t, testname, &w, src[i:i+d]);
i, d = i+d, d+1;
write(t, testname, &w, src[i:i+d])
i, d = i+d, d+1
if i+d > len(src) {
d = len(src) - i
}
}
verify(t, testname, &w, &b, src, expected);
verify(t, testname, &w, &b, src, expected)
}
type entry struct {
testname string;
minwidth, tabwidth, padding int;
padchar byte;
flags uint;
src, expected string;
testname string
minwidth, tabwidth, padding int
padchar byte
flags uint
src, expected string
}
......@@ -144,7 +144,7 @@ var tests = []entry{
entry{
"1e esc",
8, 0, 1, '.', 0,
"abc\xff\tdef", // unterminated escape
"abc\xff\tdef", // unterminated escape
"abc\tdef",
},
......@@ -165,14 +165,14 @@ var tests = []entry{
entry{
"4a",
8, 0, 1, '.', 0,
"\t", // '\t' terminates an empty cell on last line - nothing to print
"\t", // '\t' terminates an empty cell on last line - nothing to print
"",
},
entry{
"4b",
8, 0, 1, '.', AlignRight,
"\t", // '\t' terminates an empty cell on last line - nothing to print
"\t", // '\t' terminates an empty cell on last line - nothing to print
"",
},
......@@ -294,7 +294,7 @@ var tests = []entry{
entry{
"9b",
1, 0, 0, '.', FilterHTML,
"1\t2<!---\f--->\t3\t4\n" + // \f inside HTML is ignored
"1\t2<!---\f--->\t3\t4\n" + // \f inside HTML is ignored
"11\t222\t3333\t44444\n",
"1.2<!---\f--->..3...4\n" +
......@@ -304,7 +304,7 @@ var tests = []entry{
entry{
"9c",
1, 0, 0, '.', 0,
"1\t2\t3\t4\f" + // \f causes a newline and flush
"1\t2\t3\t4\f" + // \f causes a newline and flush
"11\t222\t3333\t44444\n",
"1234\n" +
......@@ -314,7 +314,7 @@ var tests = []entry{
entry{
"9c debug",
1, 0, 0, '.', Debug,
"1\t2\t3\t4\f" + // \f causes a newline and flush
"1\t2\t3\t4\f" + // \f causes a newline and flush
"11\t222\t3333\t44444\n",
"1|2|3|4\n" +
......@@ -489,7 +489,7 @@ var tests = []entry{
entry{
"15b",
4, 0, 0, '.', DiscardEmptyColumns,
"a\t\tb", // htabs - do not discard column
"a\t\tb", // htabs - do not discard column
"a.......b",
},
......@@ -558,7 +558,7 @@ var tests = []entry{
entry{
"16c",
100, 100, 0, '\t', DiscardEmptyColumns,
"a\tb\t\td\n" + // hard tabs - do not discard column
"a\tb\t\td\n" + // hard tabs - do not discard column
"a\tb\t\td\te\n" +
"a\n" +
"a\tb\tc\td\n" +
......@@ -574,7 +574,7 @@ var tests = []entry{
entry{
"16c debug",
100, 100, 0, '\t', DiscardEmptyColumns | Debug,
"a\tb\t\td\n" + // hard tabs - do not discard column
"a\tb\t\td\n" + // hard tabs - do not discard column
"a\tb\t\td\te\n" +
"a\n" +
"a\tb\tc\td\n" +
......
......@@ -7,10 +7,10 @@
package template
import (
"bytes";
"fmt";
"io";
"strings";
"bytes"
"fmt"
"io"
"strings"
)
// StringFormatter formats into the default string representation.
......@@ -19,25 +19,25 @@ import (
// under the name "" in your custom formatter map.
func StringFormatter(w io.Writer, value interface{}, format string) {
if b, ok := value.([]byte); ok {
w.Write(b);
return;
w.Write(b)
return
}
fmt.Fprint(w, value);
fmt.Fprint(w, value)
}
var (
esc_quot = strings.Bytes("&#34;"); // shorter than "&quot;"
esc_apos = strings.Bytes("&#39;"); // shorter than "&apos;"
esc_amp = strings.Bytes("&amp;");
esc_lt = strings.Bytes("&lt;");
esc_gt = strings.Bytes("&gt;");
esc_quot = strings.Bytes("&#34;") // shorter than "&quot;"
esc_apos = strings.Bytes("&#39;") // shorter than "&apos;"
esc_amp = strings.Bytes("&amp;")
esc_lt = strings.Bytes("&lt;")
esc_gt = strings.Bytes("&gt;")
)
// HTMLEscape writes to w the properly escaped HTML equivalent
// of the plain text data s.
func HTMLEscape(w io.Writer, s []byte) {
var esc []byte;
last := 0;
var esc []byte
last := 0
for i, c := range s {
switch c {
case '"':
......@@ -53,16 +53,16 @@ func HTMLEscape(w io.Writer, s []byte) {
default:
continue
}
w.Write(s[last:i]);
w.Write(esc);
last = i + 1;
w.Write(s[last:i])
w.Write(esc)
last = i + 1
}
w.Write(s[last:]);
w.Write(s[last:])
}
// HTMLFormatter formats arbitrary values for HTML
func HTMLFormatter(w io.Writer, value interface{}, format string) {
var b bytes.Buffer;
fmt.Fprint(&b, value);
HTMLEscape(w, b.Bytes());
var b bytes.Buffer
fmt.Fprint(&b, value)
HTMLEscape(w, b.Bytes())
}
This diff is collapsed.
......@@ -5,65 +5,65 @@
package template
import (
"bytes";
"container/vector";
"fmt";
"io";
"strings";
"testing";
"bytes"
"container/vector"
"fmt"
"io"
"strings"
"testing"
)
type Test struct {
in, out, err string;
in, out, err string
}
type T struct {
item string;
value string;
item string
value string
}
type U struct {
mp map[string]int;
mp map[string]int
}
type S struct {
header string;
integer int;
raw string;
innerT T;
innerPointerT *T;
data []T;
pdata []*T;
empty []*T;
emptystring string;
null []*T;
vec *vector.Vector;
true bool;
false bool;
mp map[string]string;
innermap U;
bytes []byte;
header string
integer int
raw string
innerT T
innerPointerT *T
data []T
pdata []*T
empty []*T
emptystring string
null []*T
vec *vector.Vector
true bool
false bool
mp map[string]string
innermap U
bytes []byte
}
var t1 = T{"ItemNumber1", "ValueNumber1"}
var t2 = T{"ItemNumber2", "ValueNumber2"}
func uppercase(v interface{}) string {
s := v.(string);
t := "";
s := v.(string)
t := ""
for i := 0; i < len(s); i++ {
c := s[i];
c := s[i]
if 'a' <= c && c <= 'z' {
c = c + 'A' - 'a'
}
t += string(c);
t += string(c)
}
return t;
return t
}
func plus1(v interface{}) string {
i := v.(int);
return fmt.Sprint(i + 1);
i := v.(int)
return fmt.Sprint(i + 1)
}
func writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) {
......@@ -306,36 +306,36 @@ var tests = []*Test{
}
func TestAll(t *testing.T) {
s := new(S);
s := new(S)
// initialized by hand for clarity.
s.header = "Header";
s.integer = 77;
s.raw = "&<>!@ #$%^";
s.innerT = t1;
s.data = []T{t1, t2};
s.pdata = []*T{&t1, &t2};
s.empty = []*T{};
s.null = nil;
s.vec = new(vector.Vector);
s.vec.Push("elt1");
s.vec.Push("elt2");
s.true = true;
s.false = false;
s.mp = make(map[string]string);
s.mp["mapkey"] = "Ahoy!";
s.innermap.mp = make(map[string]int);
s.innermap.mp["innerkey"] = 55;
s.bytes = strings.Bytes("hello");
var buf bytes.Buffer;
s.header = "Header"
s.integer = 77
s.raw = "&<>!@ #$%^"
s.innerT = t1
s.data = []T{t1, t2}
s.pdata = []*T{&t1, &t2}
s.empty = []*T{}
s.null = nil
s.vec = new(vector.Vector)
s.vec.Push("elt1")
s.vec.Push("elt2")
s.true = true
s.false = false
s.mp = make(map[string]string)
s.mp["mapkey"] = "Ahoy!"
s.innermap.mp = make(map[string]int)
s.innermap.mp["innerkey"] = 55
s.bytes = strings.Bytes("hello")
var buf bytes.Buffer
for _, test := range tests {
buf.Reset();
tmpl, err := Parse(test.in, formatters);
buf.Reset()
tmpl, err := Parse(test.in, formatters)
if err != nil {
t.Error("unexpected parse error:", err);
continue;
t.Error("unexpected parse error:", err)
continue
}
err = tmpl.Execute(s, &buf);
err = tmpl.Execute(s, &buf)
if test.err == "" {
if err != nil {
t.Error("unexpected execute error:", err)
......@@ -352,60 +352,60 @@ func TestAll(t *testing.T) {
}
func TestMapDriverType(t *testing.T) {
mp := map[string]string{"footer": "Ahoy!"};
tmpl, err := Parse("template: {footer}", nil);
mp := map[string]string{"footer": "Ahoy!"}
tmpl, err := Parse("template: {footer}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute(mp, &b);
var b bytes.Buffer
err = tmpl.Execute(mp, &b)
if err != nil {
t.Error("unexpected execute error:", err)
}
s := b.String();
expected := "template: Ahoy!";
s := b.String()
expected := "template: Ahoy!"
if s != expected {
t.Errorf("failed passing string as data: expected %q got %q", "template: Ahoy!", s)
}
}
func TestStringDriverType(t *testing.T) {
tmpl, err := Parse("template: {@}", nil);
tmpl, err := Parse("template: {@}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected execute error:", err)
}
s := b.String();
s := b.String()
if s != "template: hello" {
t.Errorf("failed passing string as data: expected %q got %q", "template: hello", s)
}
}
func TestTwice(t *testing.T) {
tmpl, err := Parse("template: {@}", nil);
tmpl, err := Parse("template: {@}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected parse error:", err)
}
s := b.String();
text := "template: hello";
s := b.String()
text := "template: hello"
if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s)
}
err = tmpl.Execute("hello", &b);
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected parse error:", err)
}
s = b.String();
text += text;
s = b.String()
text += text
if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s)
}
......@@ -415,29 +415,29 @@ func TestCustomDelims(t *testing.T) {
// try various lengths. zero should catch error.
for i := 0; i < 7; i++ {
for j := 0; j < 7; j++ {
tmpl := New(nil);
tmpl := New(nil)
// first two chars deliberately the same to test equal left and right delims
ldelim := "$!#$%^&"[0:i];
rdelim := "$*&^%$!"[0:j];
tmpl.SetDelims(ldelim, rdelim);
ldelim := "$!#$%^&"[0:i]
rdelim := "$*&^%$!"[0:j]
tmpl.SetDelims(ldelim, rdelim)
// if braces, this would be template: {@}{.meta-left}{.meta-right}
text := "template: " +
ldelim + "@" + rdelim +
ldelim + ".meta-left" + rdelim +
ldelim + ".meta-right" + rdelim;
err := tmpl.Parse(text);
ldelim + ".meta-right" + rdelim
err := tmpl.Parse(text)
if err != nil {
if i == 0 || j == 0 { // expected
if i == 0 || j == 0 { // expected
continue
}
t.Error("unexpected parse error:", err);
t.Error("unexpected parse error:", err)
} else if i == 0 || j == 0 {
t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim);
continue;
t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim)
continue
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
s := b.String();
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
s := b.String()
if s != "template: hello"+ldelim+rdelim {
t.Errorf("failed delim check(%q %q) %q got %q", ldelim, rdelim, text, s)
}
......@@ -447,21 +447,21 @@ func TestCustomDelims(t *testing.T) {
// Test that a variable evaluates to the field itself and does not further indirection
func TestVarIndirection(t *testing.T) {
s := new(S);
s := new(S)
// initialized by hand for clarity.
s.innerPointerT = &t1;
s.innerPointerT = &t1
var buf bytes.Buffer;
input := "{.section @}{innerPointerT}{.end}";
tmpl, err := Parse(input, nil);
var buf bytes.Buffer
input := "{.section @}{innerPointerT}{.end}"
tmpl, err := Parse(input, nil)
if err != nil {
t.Fatal("unexpected parse error:", err)
}
err = tmpl.Execute(s, &buf);
err = tmpl.Execute(s, &buf)
if err != nil {
t.Fatal("unexpected execute error:", err)
}
expect := fmt.Sprintf("%v", &t1); // output should be hex address of t1
expect := fmt.Sprintf("%v", &t1) // output should be hex address of t1
if buf.String() != expect {
t.Errorf("for %q: expected %q got %q", input, expect, buf.String())
}
......
......@@ -5,10 +5,10 @@
package testing
import (
"flag";
"fmt";
"os";
"time";
"flag"
"fmt"
"os"
"time"
)
var matchBenchmarks = flag.String("benchmarks", "", "regular expression to select benchmarks to run")
......@@ -16,24 +16,24 @@ var matchBenchmarks = flag.String("benchmarks", "", "regular expression to selec
// An internal type but exported because it is cross-package; part of the implementation
// of gotest.
type Benchmark struct {
Name string;
F func(b *B);
Name string
F func(b *B)
}
// B is a type passed to Benchmark functions to manage benchmark
// timing and to specify the number of iterations to run.
type B struct {
N int;
benchmark Benchmark;
ns int64;
bytes int64;
start int64;
N int
benchmark Benchmark
ns int64
bytes int64
start int64
}
// StartTimer starts timing a test. This function is called automatically
// before a benchmark starts, but it can also used to resume timing after
// a call to StopTimer.
func (b *B) StartTimer() { b.start = time.Nanoseconds() }
func (b *B) StartTimer() { b.start = time.Nanoseconds() }
// StopTimer stops timing a test. This can be used to pause the timer
// while performing complex initialization that you don't
......@@ -42,68 +42,68 @@ func (b *B) StopTimer() {
if b.start > 0 {
b.ns += time.Nanoseconds() - b.start
}
b.start = 0;
b.start = 0
}
// ResetTimer stops the timer and sets the elapsed benchmark time to zero.
func (b *B) ResetTimer() {
b.start = 0;
b.ns = 0;
b.start = 0
b.ns = 0
}
// SetBytes records the number of bytes processed in a single operation.
// If this is called, the benchmark will report ns/op and MB/s.
func (b *B) SetBytes(n int64) { b.bytes = n }
func (b *B) SetBytes(n int64) { b.bytes = n }
func (b *B) nsPerOp() int64 {
if b.N <= 0 {
return 0
}
return b.ns / int64(b.N);
return b.ns / int64(b.N)
}
// runN runs a single benchmark for the specified number of iterations.
func (b *B) runN(n int) {
b.N = n;
b.ResetTimer();
b.StartTimer();
b.benchmark.F(b);
b.StopTimer();
b.N = n
b.ResetTimer()
b.StartTimer()
b.benchmark.F(b)
b.StopTimer()
}
func min(x, y int) int {
if x > y {
return y
}
return x;
return x
}
// roundDown10 rounds a number down to the nearest power of 10.
func roundDown10(n int) int {
var tens = 0;
var tens = 0
// tens = floor(log_10(n))
for n > 10 {
n = n / 10;
tens++;
n = n / 10
tens++
}
// result = 10^tens
result := 1;
result := 1
for i := 0; i < tens; i++ {
result *= 10
}
return result;
return result
}
// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX].
func roundUp(n int) int {
base := roundDown10(n);
base := roundDown10(n)
if n < (2 * base) {
return 2 * base
}
if n < (5 * base) {
return 5 * base
}
return 10 * base;
return 10 * base
}
// run times the benchmark function. It gradually increases the number
......@@ -112,11 +112,11 @@ func roundUp(n int) int {
// testing.BenchmarkHello 100000 19 ns/op
func (b *B) run() {
// Run the benchmark for a single iteration in case it's expensive.
n := 1;
b.runN(n);
n := 1
b.runN(n)
// Run the benchmark for at least a second.
for b.ns < 1e9 && n < 1e9 {
last := n;
last := n
// Predict iterations/sec.
if b.nsPerOp() == 0 {
n = 1e9
......@@ -125,17 +125,17 @@ func (b *B) run() {
}
// Run more iterations than we think we'll need for a second (1.5x).
// Don't grow too fast in case we had timing errors previously.
n = min(int(1.5*float(n)), 100*last);
n = min(int(1.5*float(n)), 100*last)
// Round up to something easy to read.
n = roundUp(n);
b.runN(n);
n = roundUp(n)
b.runN(n)
}
ns := b.nsPerOp();
mb := "";
ns := b.nsPerOp()
mb := ""
if ns > 0 && b.bytes > 0 {
mb = fmt.Sprintf("\t%7.2f MB/s", (float64(b.bytes)/1e6)/(float64(ns)/1e9))
}
fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb);
fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb)
}
// An internal function but exported because it is cross-package; part of the implementation
......@@ -145,16 +145,16 @@ func RunBenchmarks(benchmarks []Benchmark) {
if len(*matchBenchmarks) == 0 {
return
}
re, err := CompileRegexp(*matchBenchmarks);
re, err := CompileRegexp(*matchBenchmarks)
if err != "" {
println("invalid regexp for -benchmarks:", err);
os.Exit(1);
println("invalid regexp for -benchmarks:", err)
os.Exit(1)
}
for _, Benchmark := range benchmarks {
if !re.MatchString(Benchmark.Name) {
continue
}
b := &B{benchmark: Benchmark};
b.run();
b := &B{benchmark: Benchmark}
b.run()
}
}
......@@ -5,24 +5,24 @@
package iotest
import (
"io";
"log";
"os";
"io"
"log"
"os"
)
type writeLogger struct {
prefix string;
w io.Writer;
prefix string
w io.Writer
}
func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
n, err = l.w.Write(p);
n, err = l.w.Write(p)
if err != nil {
log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
} else {
log.Stdoutf("%s %x", l.prefix, p[0:n])
}
return;
return
}
// NewWriteLogger returns a writer that behaves like w except
......@@ -33,18 +33,18 @@ func NewWriteLogger(prefix string, w io.Writer) io.Writer {
}
type readLogger struct {
prefix string;
r io.Reader;
prefix string
r io.Reader
}
func (l *readLogger) Read(p []byte) (n int, err os.Error) {
n, err = l.r.Read(p);
n, err = l.r.Read(p)
if err != nil {
log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
} else {
log.Stdoutf("%s %x", l.prefix, p[0:n])
}
return;
return
}
// NewReadLogger returns a reader that behaves like r except
......
......@@ -7,31 +7,31 @@
package iotest
import (
"io";
"os";
"io"
"os"
)
// OneByteReader returns a Reader that implements
// each non-empty Read by reading one byte from r.
func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} }
func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} }
type oneByteReader struct {
r io.Reader;
r io.Reader
}
func (r *oneByteReader) Read(p []byte) (int, os.Error) {
if len(p) == 0 {
return 0, nil
}
return r.r.Read(p[0:1]);
return r.r.Read(p[0:1])
}
// HalfReader returns a Reader that implements Read
// by reading half as many requested bytes from r.
func HalfReader(r io.Reader) io.Reader { return &halfReader{r} }
func HalfReader(r io.Reader) io.Reader { return &halfReader{r} }
type halfReader struct {
r io.Reader;
r io.Reader
}
func (r *halfReader) Read(p []byte) (int, os.Error) {
......@@ -42,12 +42,12 @@ func (r *halfReader) Read(p []byte) (int, os.Error) {
// DataErrReader returns a Reader that returns the final
// error with the last data read, instead of by itself with
// zero bytes of data.
func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} }
func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} }
type dataErrReader struct {
r io.Reader;
unread []byte;
data []byte;
r io.Reader
unread []byte
data []byte
}
func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
......@@ -55,15 +55,15 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
// one to get data and a second to look for an error.
for {
if len(r.unread) == 0 {
n1, err1 := r.r.Read(r.data);
r.unread = r.data[0:n1];
err = err1;
n1, err1 := r.r.Read(r.data)
r.unread = r.data[0:n1]
err = err1
}
if n > 0 {
break
}
n = copy(p, r.unread);
r.unread = r.unread[n:];
n = copy(p, r.unread)
r.unread = r.unread[n:]
}
return;
return
}
......@@ -5,8 +5,8 @@
package iotest
import (
"io";
"os";
"io"
"os"
)
// TruncateWriter returns a Writer that writes to w
......@@ -16,8 +16,8 @@ func TruncateWriter(w io.Writer, n int64) io.Writer {
}
type truncateWriter struct {
w io.Writer;
n int64;
w io.Writer
n int64
}
func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
......@@ -25,14 +25,14 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
return len(p), nil
}
// real write
n = len(p);
n = len(p)
if int64(n) > t.n {
n = int(t.n)
}
n, err = t.w.Write(p[0:n]);
t.n -= int64(n);
n, err = t.w.Write(p[0:n])
t.n -= int64(n)
if err == nil {
n = len(p)
}
return;
return
}
This diff is collapsed.
......@@ -5,60 +5,60 @@
package quick
import (
"rand";
"reflect";
"testing";
"os";
"rand"
"reflect"
"testing"
"os"
)
func fBool(a bool) bool { return a }
func fBool(a bool) bool { return a }
func fFloat32(a float32) float32 { return a }
func fFloat32(a float32) float32 { return a }
func fFloat64(a float64) float64 { return a }
func fFloat64(a float64) float64 { return a }
func fFloat(a float) float { return a }
func fFloat(a float) float { return a }
func fInt16(a int16) int16 { return a }
func fInt16(a int16) int16 { return a }
func fInt32(a int32) int32 { return a }
func fInt32(a int32) int32 { return a }
func fInt64(a int64) int64 { return a }
func fInt64(a int64) int64 { return a }
func fInt8(a int8) int8 { return a }
func fInt8(a int8) int8 { return a }
func fInt(a int) int { return a }
func fInt(a int) int { return a }
func fUInt8(a uint8) uint8 { return a }
func fUInt8(a uint8) uint8 { return a }
func fMap(a map[int]int) map[int]int { return a }
func fMap(a map[int]int) map[int]int { return a }
func fSlice(a []byte) []byte { return a }
func fSlice(a []byte) []byte { return a }
func fString(a string) string { return a }
func fString(a string) string { return a }
type TestStruct struct {
A int;
B string;
A int
B string
}
func fStruct(a TestStruct) TestStruct { return a }
func fStruct(a TestStruct) TestStruct { return a }
func fUint16(a uint16) uint16 { return a }
func fUint16(a uint16) uint16 { return a }
func fUint32(a uint32) uint32 { return a }
func fUint32(a uint32) uint32 { return a }
func fUint64(a uint64) uint64 { return a }
func fUint64(a uint64) uint64 { return a }
func fUint8(a uint8) uint8 { return a }
func fUint8(a uint8) uint8 { return a }
func fUint(a uint) uint { return a }
func fUint(a uint) uint { return a }
func fUintptr(a uintptr) uintptr { return a }
func fUintptr(a uintptr) uintptr { return a }
func fIntptr(a *int) *int {
b := *a;
return &b;
b := *a
return &b
}
func reportError(property string, err os.Error, t *testing.T) {
......@@ -68,49 +68,49 @@ func reportError(property string, err os.Error, t *testing.T) {
}
func TestCheckEqual(t *testing.T) {
reportError("fBool", CheckEqual(fBool, fBool, nil), t);
reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t);
reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t);
reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t);
reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t);
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t);
reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t);
reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t);
reportError("fInt", CheckEqual(fInt, fInt, nil), t);
reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t);
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t);
reportError("fMap", CheckEqual(fMap, fMap, nil), t);
reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t);
reportError("fString", CheckEqual(fString, fString, nil), t);
reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t);
reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t);
reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t);
reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t);
reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t);
reportError("fUint", CheckEqual(fUint, fUint, nil), t);
reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t);
reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t);
reportError("fBool", CheckEqual(fBool, fBool, nil), t)
reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t)
reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t)
reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t)
reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t)
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t)
reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t)
reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t)
reportError("fInt", CheckEqual(fInt, fInt, nil), t)
reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t)
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t)
reportError("fMap", CheckEqual(fMap, fMap, nil), t)
reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t)
reportError("fString", CheckEqual(fString, fString, nil), t)
reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t)
reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t)
reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t)
reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t)
reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t)
reportError("fUint", CheckEqual(fUint, fUint, nil), t)
reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t)
reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t)
}
// This tests that ArbitraryValue is working by checking that all the arbitrary
// values of type MyStruct have x = 42.
type myStruct struct {
x int;
x int
}
func (m myStruct) Generate(r *rand.Rand, _ int) reflect.Value {
return reflect.NewValue(myStruct{x: 42})
}
func myStructProperty(in myStruct) bool { return in.x == 42 }
func myStructProperty(in myStruct) bool { return in.x == 42 }
func TestCheckProperty(t *testing.T) {
reportError("myStructProperty", Check(myStructProperty, nil), t)
}
func TestFailure(t *testing.T) {
f := func(x int) bool { return false };
err := Check(f, nil);
f := func(x int) bool { return false }
err := Check(f, nil)
if err == nil {
t.Errorf("Check didn't return an error")
}
......@@ -118,7 +118,7 @@ func TestFailure(t *testing.T) {
t.Errorf("Error was not a CheckError: %s", err)
}
err = CheckEqual(fUint, fUint32, nil);
err = CheckEqual(fUint, fUint32, nil)
if err == nil {
t.Errorf("#1 CheckEqual didn't return an error")
}
......@@ -126,7 +126,7 @@ func TestFailure(t *testing.T) {
t.Errorf("#1 Error was not a SetupError: %s", err)
}
err = CheckEqual(func(x, y int) {}, func(x int) {}, nil);
err = CheckEqual(func(x, y int) {}, func(x int) {}, nil)
if err == nil {
t.Errorf("#2 CheckEqual didn't return an error")
}
......@@ -134,7 +134,7 @@ func TestFailure(t *testing.T) {
t.Errorf("#2 Error was not a SetupError: %s", err)
}
err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil);
err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil)
if err == nil {
t.Errorf("#3 CheckEqual didn't return an error")
}
......
This diff is collapsed.
......@@ -5,7 +5,7 @@
package testing
import (
"strings";
"strings"
)
var good_re = []string{
......@@ -30,8 +30,8 @@ var good_re = []string{
// TODO: nice to do this with a map
type stringError struct {
re string;
err string;
re string
err string
}
var bad_re = []stringError{
......@@ -52,9 +52,9 @@ var bad_re = []stringError{
type vec []int
type tester struct {
re string;
text string;
match vec;
re string
text string
match vec
}
var matches = []tester{
......@@ -87,15 +87,15 @@ var matches = []tester{
}
func compileTest(t *T, expr string, error string) *Regexp {
re, err := CompileRegexp(expr);
re, err := CompileRegexp(expr)
if err != error {
t.Error("compiling `", expr, "`; unexpected error: ", err)
}
return re;
return re
}
func printVec(t *T, m []int) {
l := len(m);
l := len(m)
if l == 0 {
t.Log("\t<no match>")
} else {
......@@ -106,7 +106,7 @@ func printVec(t *T, m []int) {
}
func printStrings(t *T, m []string) {
l := len(m);
l := len(m)
if l == 0 {
t.Log("\t<no match>")
} else {
......@@ -117,7 +117,7 @@ func printStrings(t *T, m []string) {
}
func printBytes(t *T, b [][]byte) {
l := len(b);
l := len(b)
if l == 0 {
t.Log("\t<no match>")
} else {
......@@ -128,7 +128,7 @@ func printBytes(t *T, b [][]byte) {
}
func equal(m1, m2 []int) bool {
l := len(m1);
l := len(m1)
if l != len(m2) {
return false
}
......@@ -137,11 +137,11 @@ func equal(m1, m2 []int) bool {
return false
}
}
return true;
return true
}
func equalStrings(m1, m2 []string) bool {
l := len(m1);
l := len(m1)
if l != len(m2) {
return false
}
......@@ -150,11 +150,11 @@ func equalStrings(m1, m2 []string) bool {
return false
}
}
return true;
return true
}
func equalBytes(m1 [][]byte, m2 []string) bool {
l := len(m1);
l := len(m1)
if l != len(m2) {
return false
}
......@@ -163,28 +163,28 @@ func equalBytes(m1 [][]byte, m2 []string) bool {
return false
}
}
return true;
return true
}
func executeTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, "");
re := compileTest(t, expr, "")
if re == nil {
return
}
m := re.ExecuteString(str);
m := re.ExecuteString(str)
if !equal(m, match) {
t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:");
printVec(t, m);
t.Log("should be:");
printVec(t, match);
t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:")
printVec(t, m)
t.Log("should be:")
printVec(t, match)
}
// now try bytes
m = re.Execute(strings.Bytes(str));
m = re.Execute(strings.Bytes(str))
if !equal(m, match) {
t.Error("Execute failure on `", expr, "` matching `", str, "`:");
printVec(t, m);
t.Log("should be:");
printVec(t, match);
t.Error("Execute failure on `", expr, "` matching `", str, "`:")
printVec(t, m)
t.Log("should be:")
printVec(t, match)
}
}
......@@ -202,22 +202,22 @@ func TestBadCompile(t *T) {
func TestExecute(t *T) {
for i := 0; i < len(matches); i++ {
test := &matches[i];
executeTest(t, test.re, test.text, test.match);
test := &matches[i]
executeTest(t, test.re, test.text, test.match)
}
}
func matchTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, "");
re := compileTest(t, expr, "")
if re == nil {
return
}
m := re.MatchString(str);
m := re.MatchString(str)
if m != (len(match) > 0) {
t.Error("MatchString failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0)
}
// now try bytes
m = re.Match(strings.Bytes(str));
m = re.Match(strings.Bytes(str))
if m != (len(match) > 0) {
t.Error("Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0)
}
......@@ -225,46 +225,46 @@ func matchTest(t *T, expr string, str string, match []int) {
func TestMatch(t *T) {
for i := 0; i < len(matches); i++ {
test := &matches[i];
matchTest(t, test.re, test.text, test.match);
test := &matches[i]
matchTest(t, test.re, test.text, test.match)
}
}
func matchStringsTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, "");
re := compileTest(t, expr, "")
if re == nil {
return
}
strs := make([]string, len(match)/2);
strs := make([]string, len(match)/2)
for i := 0; i < len(match); i++ {
strs[i/2] = str[match[i]:match[i+1]]
}
m := re.MatchStrings(str);
m := re.MatchStrings(str)
if !equalStrings(m, strs) {
t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:");
printStrings(t, m);
t.Log("should be:");
printStrings(t, strs);
t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:")
printStrings(t, m)
t.Log("should be:")
printStrings(t, strs)
}
// now try bytes
s := re.MatchSlices(strings.Bytes(str));
s := re.MatchSlices(strings.Bytes(str))
if !equalBytes(s, strs) {
t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:");
printBytes(t, s);
t.Log("should be:");
printStrings(t, strs);
t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:")
printBytes(t, s)
t.Log("should be:")
printStrings(t, strs)
}
}
func TestMatchStrings(t *T) {
for i := 0; i < len(matches); i++ {
test := &matches[i];
matchTest(t, test.re, test.text, test.match);
test := &matches[i]
matchTest(t, test.re, test.text, test.match)
}
}
func matchFunctionTest(t *T, expr string, str string, match []int) {
m, err := MatchString(expr, str);
m, err := MatchString(expr, str)
if err == "" {
return
}
......@@ -275,15 +275,15 @@ func matchFunctionTest(t *T, expr string, str string, match []int) {
func TestMatchFunction(t *T) {
for i := 0; i < len(matches); i++ {
test := &matches[i];
matchFunctionTest(t, test.re, test.text, test.match);
test := &matches[i]
matchFunctionTest(t, test.re, test.text, test.match)
}
}
func BenchmarkSimpleMatch(b *B) {
b.StopTimer();
re, _ := CompileRegexp("a");
b.StartTimer();
b.StopTimer()
re, _ := CompileRegexp("a")
b.StartTimer()
for i := 0; i < b.N; i++ {
re.MatchString("a")
......@@ -291,9 +291,9 @@ func BenchmarkSimpleMatch(b *B) {
}
func BenchmarkUngroupedMatch(b *B) {
b.StopTimer();
re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+");
b.StartTimer();
b.StopTimer()
re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+")
b.StartTimer()
for i := 0; i < b.N; i++ {
re.MatchString("word 123 other")
......@@ -301,9 +301,9 @@ func BenchmarkUngroupedMatch(b *B) {
}
func BenchmarkGroupedMatch(b *B) {
b.StopTimer();
re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)");
b.StartTimer();
b.StopTimer()
re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)")
b.StartTimer()
for i := 0; i < b.N; i++ {
re.MatchString("word 123 other")
......
This diff is collapsed.
......@@ -5,37 +5,37 @@
package script
import (
"testing";
"testing"
)
func TestNoop(t *testing.T) {
err := Perform(0, nil);
err := Perform(0, nil)
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestSimple(t *testing.T) {
c := make(chan int);
defer close(c);
c := make(chan int)
defer close(c)
a := NewEvent("send", nil, Send{c, 1});
b := NewEvent("recv", []*Event{a}, Recv{c, 1});
a := NewEvent("send", nil, Send{c, 1})
b := NewEvent("recv", []*Event{a}, Recv{c, 1})
err := Perform(0, []*Event{a, b});
err := Perform(0, []*Event{a, b})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestFail(t *testing.T) {
c := make(chan int);
defer close(c);
c := make(chan int)
defer close(c)
a := NewEvent("send", nil, Send{c, 2});
b := NewEvent("recv", []*Event{a}, Recv{c, 1});
a := NewEvent("send", nil, Send{c, 2})
b := NewEvent("recv", []*Event{a}, Recv{c, 1})
err := Perform(0, []*Event{a, b});
err := Perform(0, []*Event{a, b})
if err == nil {
t.Errorf("Failed to get expected error")
} else if _, ok := err.(ReceivedUnexpected); !ok {
......@@ -44,12 +44,12 @@ func TestFail(t *testing.T) {
}
func TestClose(t *testing.T) {
c := make(chan int);
c := make(chan int)
a := NewEvent("close", nil, Close{c});
b := NewEvent("closed", []*Event{a}, Closed{c});
a := NewEvent("close", nil, Close{c})
b := NewEvent("closed", []*Event{a}, Closed{c})
err := Perform(0, []*Event{a, b});
err := Perform(0, []*Event{a, b})
if err != nil {
t.Errorf("Got error: %s", err)
}
......@@ -59,16 +59,16 @@ func matchOne(v interface{}) bool {
if i, ok := v.(int); ok && i == 1 {
return true
}
return false;
return false
}
func TestRecvMatch(t *testing.T) {
c := make(chan int);
c := make(chan int)
a := NewEvent("send", nil, Send{c, 1});
b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne});
a := NewEvent("send", nil, Send{c, 1})
b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne})
err := Perform(0, []*Event{a, b});
err := Perform(0, []*Event{a, b})
if err != nil {
t.Errorf("Got error: %s", err)
}
......
......@@ -39,10 +39,10 @@
package testing
import (
"flag";
"fmt";
"os";
"runtime";
"flag"
"fmt"
"os"
"runtime"
)
// Report as tests are run; default is silent for success.
......@@ -52,44 +52,44 @@ var match = flag.String("match", "", "regular expression to select tests to run"
// Insert final newline if needed and tabs after internal newlines.
func tabify(s string) string {
n := len(s);
n := len(s)
if n > 0 && s[n-1] != '\n' {
s += "\n";
n++;
s += "\n"
n++
}
for i := 0; i < n-1; i++ { // -1 to avoid final newline
for i := 0; i < n-1; i++ { // -1 to avoid final newline
if s[i] == '\n' {
return s[0:i+1] + "\t" + tabify(s[i+1:n])
}
}
return s;
return s
}
// T is a type passed to Test functions to manage test state and support formatted test logs.
// Logs are accumulated during execution and dumped to standard error when done.
type T struct {
errors string;
failed bool;
ch chan *T;
errors string
failed bool
ch chan *T
}
// Fail marks the Test function as having failed but continues execution.
func (t *T) Fail() { t.failed = true }
func (t *T) Fail() { t.failed = true }
// Failed returns whether the Test function has failed.
func (t *T) Failed() bool { return t.failed }
func (t *T) Failed() bool { return t.failed }
// FailNow marks the Test function as having failed and stops its execution.
// Execution will continue at the next Test.
func (t *T) FailNow() {
t.Fail();
t.ch <- t;
runtime.Goexit();
t.Fail()
t.ch <- t
runtime.Goexit()
}
// Log formats its arguments using default formatting, analogous to Print(),
// and records the text in the error log.
func (t *T) Log(args ...) { t.errors += "\t" + tabify(fmt.Sprintln(args)) }
func (t *T) Log(args ...) { t.errors += "\t" + tabify(fmt.Sprintln(args)) }
// Log formats its arguments according to the format, analogous to Printf(),
// and records the text in the error log.
......@@ -99,52 +99,52 @@ func (t *T) Logf(format string, args ...) {
// Error is equivalent to Log() followed by Fail().
func (t *T) Error(args ...) {
t.Log(args);
t.Fail();
t.Log(args)
t.Fail()
}
// Errorf is equivalent to Logf() followed by Fail().
func (t *T) Errorf(format string, args ...) {
t.Logf(format, args);
t.Fail();
t.Logf(format, args)
t.Fail()
}
// Fatal is equivalent to Log() followed by FailNow().
func (t *T) Fatal(args ...) {
t.Log(args);
t.FailNow();
t.Log(args)
t.FailNow()
}
// Fatalf is equivalent to Logf() followed by FailNow().
func (t *T) Fatalf(format string, args ...) {
t.Logf(format, args);
t.FailNow();
t.Logf(format, args)
t.FailNow()
}
// An internal type but exported because it is cross-package; part of the implementation
// of gotest.
type Test struct {
Name string;
F func(*T);
Name string
F func(*T)
}
func tRunner(t *T, test *Test) {
test.F(t);
t.ch <- t;
test.F(t)
t.ch <- t
}
// An internal function but exported because it is cross-package; part of the implementation
// of gotest.
func Main(tests []Test) {
flag.Parse();
ok := true;
flag.Parse()
ok := true
if len(tests) == 0 {
println("testing: warning: no tests to run")
}
re, err := CompileRegexp(*match);
re, err := CompileRegexp(*match)
if err != "" {
println("invalid regexp for -match:", err);
os.Exit(1);
println("invalid regexp for -match:", err)
os.Exit(1)
}
for i := 0; i < len(tests); i++ {
if !re.MatchString(tests[i].Name) {
......@@ -153,22 +153,22 @@ func Main(tests []Test) {
if *chatty {
println("=== RUN ", tests[i].Name)
}
t := new(T);
t.ch = make(chan *T);
go tRunner(t, &tests[i]);
<-t.ch;
t := new(T)
t.ch = make(chan *T)
go tRunner(t, &tests[i])
<-t.ch
if t.failed {
println("--- FAIL:", tests[i].Name);
print(t.errors);
ok = false;
println("--- FAIL:", tests[i].Name)
print(t.errors)
ok = false
} else if *chatty {
println("--- PASS:", tests[i].Name);
print(t.errors);
println("--- PASS:", tests[i].Name)
print(t.errors)
}
}
if !ok {
println("FAIL");
os.Exit(1);
println("FAIL")
os.Exit(1)
}
println("PASS");
println("PASS")
}
......@@ -5,10 +5,10 @@
package time
import (
"os";
"syscall";
"os"
"syscall"
)
// Sleep pauses the current goroutine for ns nanoseconds.
// It returns os.EINTR if interrupted.
func Sleep(ns int64) os.Error { return os.NewSyscallError("sleep", syscall.Sleep(ns)) }
func Sleep(ns int64) os.Error { return os.NewSyscallError("sleep", syscall.Sleep(ns)) }
......@@ -23,19 +23,19 @@ package time
// A Ticker holds a synchronous channel that delivers `ticks' of a clock
// at intervals.
type Ticker struct {
C <-chan int64; // The channel on which the ticks are delivered.
ns int64;
shutdown bool;
C <-chan int64 // The channel on which the ticks are delivered.
ns int64
shutdown bool
}
// Stop turns off a ticker. After Stop, no more ticks will be delivered.
func (t *Ticker) Stop() { t.shutdown = true }
func (t *Ticker) Stop() { t.shutdown = true }
func (t *Ticker) ticker(c chan<- int64) {
now := Nanoseconds();
when := now;
now := Nanoseconds()
when := now
for !t.shutdown {
when += t.ns; // next alarm
when += t.ns // next alarm
// if c <- now took too long, skip ahead
if when < now {
......@@ -47,12 +47,12 @@ func (t *Ticker) ticker(c chan<- int64) {
when += t.ns
}
Sleep(when - now);
now = Nanoseconds();
Sleep(when - now)
now = Nanoseconds()
if t.shutdown {
return
}
c <- now;
c <- now
}
}
......@@ -62,7 +62,7 @@ func Tick(ns int64) <-chan int64 {
if ns <= 0 {
return nil
}
return NewTicker(ns).C;
return NewTicker(ns).C
}
// Ticker returns a new Ticker containing a synchronous channel that will
......@@ -72,8 +72,8 @@ func NewTicker(ns int64) *Ticker {
if ns <= 0 {
return nil
}
c := make(chan int64);
t := &Ticker{c, ns, false};
go t.ticker(c);
return t;
c := make(chan int64)
t := &Ticker{c, ns, false}
go t.ticker(c)
return t
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -6,8 +6,8 @@ package unicode
// IsDigit reports whether the rune is a decimal digit.
func IsDigit(rune int) bool {
if rune < 0x100 { // quick ASCII (Latin-1, really) check
if rune < 0x100 { // quick ASCII (Latin-1, really) check
return '0' <= rune && rune <= '9'
}
return Is(Digit, rune);
return Is(Digit, rune)
}
......@@ -5,8 +5,8 @@
package unicode_test
import (
"testing";
. "unicode";
"testing"
. "unicode"
)
var testDigit = []int{
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment