Commit 91549438 authored by Russ Cox's avatar Russ Cox

apply gofmt to rand reflect regexp rpc runtime sort strconv strings sync...

apply gofmt to rand reflect regexp rpc runtime sort strconv strings sync syscall testing time unicode unsafe utf8

R=gri
DELTA=1409  (79 added, 24 deleted, 1306 changed)
OCL=35415
CL=35437
parent f77b255c
...@@ -29,7 +29,7 @@ var ( ...@@ -29,7 +29,7 @@ var (
// cooked random numbers // cooked random numbers
// the state of the rng // the state of the rng
// after 780e10 iterations // after 780e10 iterations
rng_cooked [_LEN]int64 = [...]int64 { rng_cooked [_LEN]int64 = [...]int64{
5041579894721019882, 4646389086726545243, 1395769623340756751, 5333664234075297259, 5041579894721019882, 4646389086726545243, 1395769623340756751, 5333664234075297259,
2875692520355975054, 9033628115061424579, 7143218595135194537, 4812947590706362721, 2875692520355975054, 9033628115061424579, 7143218595135194537, 4812947590706362721,
7937252194349799378, 5307299880338848416, 8209348851763925077, 2115741599318814044, 7937252194349799378, 5307299880338848416, 8209348851763925077, 2115741599318814044,
...@@ -181,13 +181,14 @@ var ( ...@@ -181,13 +181,14 @@ var (
4133292154170828382, 2918308698224194548, 1519461397937144458, 5293934712616591764, 4133292154170828382, 2918308698224194548, 1519461397937144458, 5293934712616591764,
4922828954023452664, 2879211533496425641, 5896236396443472108, 8465043815351752425, 4922828954023452664, 2879211533496425641, 5896236396443472108, 8465043815351752425,
7329020396871624740, 8915471717014488588, 2944902635677463047, 7052079073493465134, 7329020396871624740, 8915471717014488588, 2944902635677463047, 7052079073493465134,
8382142935188824023, 9103922860780351547, 4152330101494654406 }; 8382142935188824023, 9103922860780351547, 4152330101494654406,
};
) )
// seed rng x[n+1] = 48271 * x[n] mod (2**31 - 1) // seed rng x[n+1] = 48271 * x[n] mod (2**31 - 1)
func seedrand(x int32) int32 { func seedrand(x int32) int32 {
hi := x / _Q; hi := x/_Q;
lo := x % _Q; lo := x%_Q;
x = _A*lo - _R*hi; x = _A*lo - _R*hi;
if x < 0 { if x < 0 {
x += _M; x += _M;
...@@ -213,13 +214,13 @@ func Seed(seed int32) { ...@@ -213,13 +214,13 @@ func Seed(seed int32) {
x = seedrand(x); x = seedrand(x);
if i >= 0 { if i >= 0 {
var u int64; var u int64;
u = int64(x) << 40; u = int64(x)<<40;
x = seedrand(x); x = seedrand(x);
u ^= int64(x) << 20; u ^= int64(x)<<20;
x = seedrand(x); x = seedrand(x);
u ^= int64(x); u ^= int64(x);
u ^= rng_cooked[i]; u ^= rng_cooked[i];
rng_vec[i] = u & _MASK; rng_vec[i] = u&_MASK;
} }
} }
} }
...@@ -236,79 +237,78 @@ func Int63() int64 { ...@@ -236,79 +237,78 @@ func Int63() int64 {
rng_feed += _LEN; rng_feed += _LEN;
} }
x := (rng_vec[rng_feed] + rng_vec[rng_tap]) & _MASK; x := (rng_vec[rng_feed]+rng_vec[rng_tap])&_MASK;
rng_vec[rng_feed] = x; rng_vec[rng_feed] = x;
return x; return x;
} }
// Uint32 returns a pseudo-random 32-bit value as a uint32. // Uint32 returns a pseudo-random 32-bit value as a uint32.
func Uint32() uint32 { func Uint32() uint32 {
return uint32(Int63() >> 31); return uint32(Int63()>>31);
} }
// Int31 returns a non-negative pseudo-random 31-bit integer as an int32. // Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
func Int31() int32 { func Int31() int32 {
return int32(Int63() >> 32); return int32(Int63()>>32);
} }
// Int returns a non-negative pseudo-random int. All bits but the top bit are random. // Int returns a non-negative pseudo-random int. All bits but the top bit are random.
func Int() int { func Int() int {
u := uint(Int63()); u := uint(Int63());
return int(u << 1 >> 1); // clear sign bit if int == int32 return int(u<<1>>1); // clear sign bit if int == int32
} }
// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
func Int63n(n int64) int64 { func Int63n(n int64) int64 {
if n <= 0 { if n <= 0 {
return 0 return 0;
} }
max := int64((1<<63)-1 - (1<<63) % uint64(n)); max := int64((1<<63) - 1 - (1<<63)%uint64(n));
v := Int63(); v := Int63();
for v > max { for v > max {
v = Int63() v = Int63();
} }
return v % n return v%n;
} }
// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
func Int31n(n int32) int32 { func Int31n(n int32) int32 {
return int32(Int63n(int64(n))) return int32(Int63n(int64(n)));
} }
// Intn returns, as an int, a non-negative pseudo-random number in [0,n). // Intn returns, as an int, a non-negative pseudo-random number in [0,n).
func Intn(n int) int { func Intn(n int) int {
return int(Int63n(int64(n))) return int(Int63n(int64(n)));
} }
// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
func Float64() float64 { func Float64() float64 {
x := float64(Int63()) / float64(_MAX); x := float64(Int63())/float64(_MAX);
for x >= 1 { for x >= 1 {
x = float64(Int63()) / float64(_MAX); x = float64(Int63())/float64(_MAX);
} }
return x; return x;
} }
// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
func Float32() float32 { func Float32() float32 {
return float32(Float64()) return float32(Float64());
} }
// Float returns, as a float, a pseudo-random number in [0.0,1.0). // Float returns, as a float, a pseudo-random number in [0.0,1.0).
func Float() float func Float() float {
{ return float(Float64());
return float(Float64())
} }
// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
func Perm(n int) []int { func Perm(n int) []int {
m := make([]int, n); m := make([]int, n);
for i:=0; i<n; i++ { for i := 0; i < n; i++ {
m[i] = i; m[i] = i;
} }
for i:=0; i<n; i++ { for i := 0; i < n; i++ {
j := Intn(n); j := Intn(n);
m[i],m[j] = m[j],m[i]; m[i], m[j] = m[j], m[i];
} }
return m; return m;
} }
......
...@@ -23,7 +23,7 @@ type visit struct { ...@@ -23,7 +23,7 @@ type visit struct {
// recursive types. // recursive types.
func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool { func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool {
if v1 == nil || v2 == nil { if v1 == nil || v2 == nil {
return v1 == v2 return v1 == v2;
} }
if v1.Type() != v2.Type() { if v1.Type() != v2.Type() {
return false; return false;
...@@ -44,7 +44,7 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool { ...@@ -44,7 +44,7 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool {
} }
// ... or already seen // ... or already seen
h := 17 * addr1 + addr2; h := 17*addr1 + addr2;
seen, _ := visited[h]; seen, _ := visited[h];
typ := v1.Type(); typ := v1.Type();
for p := seen; p != nil; p = p.next { for p := seen; p != nil; p = p.next {
...@@ -93,7 +93,7 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool { ...@@ -93,7 +93,7 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool {
case *StructValue: case *StructValue:
struct1 := v; struct1 := v;
struct2 := v2.(*StructValue); struct2 := v2.(*StructValue);
for i, n:= 0, v.NumField(); i < n; i++ { for i, n := 0, v.NumField(); i < n; i++ {
if !deepValueEqual(struct1.Field(i), struct2.Field(i), visited, depth+1) { if !deepValueEqual(struct1.Field(i), struct2.Field(i), visited, depth+1) {
return false; return false;
} }
......
...@@ -56,9 +56,9 @@ func valueToString(val Value) string { ...@@ -56,9 +56,9 @@ func valueToString(val Value) string {
return val.Get(); return val.Get();
case *BoolValue: case *BoolValue:
if val.Get() { if val.Get() {
return "true" return "true";
} else { } else {
return "false" return "false";
} }
case *PtrValue: case *PtrValue:
v := val; v := val;
...@@ -76,7 +76,7 @@ func valueToString(val Value) string { ...@@ -76,7 +76,7 @@ func valueToString(val Value) string {
str += "{"; str += "{";
for i := 0; i < v.Len(); i++ { for i := 0; i < v.Len(); i++ {
if i > 0 { if i > 0 {
str += ", " str += ", ";
} }
str += valueToString(v.Elem(i)); str += valueToString(v.Elem(i));
} }
...@@ -99,7 +99,7 @@ func valueToString(val Value) string { ...@@ -99,7 +99,7 @@ func valueToString(val Value) string {
str += "{"; str += "{";
for i, n := 0, v.NumField(); i < n; i++ { for i, n := 0, v.NumField(); i < n; i++ {
if i > 0 { if i > 0 {
str += ", " str += ", ";
} }
str += valueToString(v.Field(i)); str += valueToString(v.Field(i));
} }
......
...@@ -50,93 +50,93 @@ type uncommonType struct { ...@@ -50,93 +50,93 @@ type uncommonType struct {
// BoolType represents a boolean type. // BoolType represents a boolean type.
type BoolType struct { type BoolType struct {
commonType commonType;
} }
// Float32Type represents a float32 type. // Float32Type represents a float32 type.
type Float32Type struct { type Float32Type struct {
commonType commonType;
} }
// Float64Type represents a float64 type. // Float64Type represents a float64 type.
type Float64Type struct { type Float64Type struct {
commonType commonType;
} }
// FloatType represents a float type. // FloatType represents a float type.
type FloatType struct { type FloatType struct {
commonType commonType;
} }
// Int16Type represents an int16 type. // Int16Type represents an int16 type.
type Int16Type struct { type Int16Type struct {
commonType commonType;
} }
// Int32Type represents an int32 type. // Int32Type represents an int32 type.
type Int32Type struct { type Int32Type struct {
commonType commonType;
} }
// Int64Type represents an int64 type. // Int64Type represents an int64 type.
type Int64Type struct { type Int64Type struct {
commonType commonType;
} }
// Int8Type represents an int8 type. // Int8Type represents an int8 type.
type Int8Type struct { type Int8Type struct {
commonType commonType;
} }
// IntType represents an int type. // IntType represents an int type.
type IntType struct { type IntType struct {
commonType commonType;
} }
// Uint16Type represents a uint16 type. // Uint16Type represents a uint16 type.
type Uint16Type struct { type Uint16Type struct {
commonType commonType;
} }
// Uint32Type represents a uint32 type. // Uint32Type represents a uint32 type.
type Uint32Type struct { type Uint32Type struct {
commonType commonType;
} }
// Uint64Type represents a uint64 type. // Uint64Type represents a uint64 type.
type Uint64Type struct { type Uint64Type struct {
commonType commonType;
} }
// Uint8Type represents a uint8 type. // Uint8Type represents a uint8 type.
type Uint8Type struct { type Uint8Type struct {
commonType commonType;
} }
// UintType represents a uint type. // UintType represents a uint type.
type UintType struct { type UintType struct {
commonType commonType;
} }
// StringType represents a string type. // StringType represents a string type.
type StringType struct { type StringType struct {
commonType commonType;
} }
// UintptrType represents a uintptr type. // UintptrType represents a uintptr type.
type UintptrType struct { type UintptrType struct {
commonType commonType;
} }
// DotDotDotType represents the ... that can // DotDotDotType represents the ... that can
// be used as the type of the final function parameter. // be used as the type of the final function parameter.
type DotDotDotType struct { type DotDotDotType struct {
commonType commonType;
} }
// UnsafePointerType represents an unsafe.Pointer type. // UnsafePointerType represents an unsafe.Pointer type.
type UnsafePointerType struct { type UnsafePointerType struct {
commonType commonType;
} }
// ArrayType represents a fixed array type. // ArrayType represents a fixed array type.
...@@ -148,10 +148,11 @@ type ArrayType struct { ...@@ -148,10 +148,11 @@ type ArrayType struct {
// ChanDir represents a channel type's direction. // ChanDir represents a channel type's direction.
type ChanDir int type ChanDir int
const ( const (
RecvDir ChanDir = 1<<iota; RecvDir ChanDir = 1<<iota;
SendDir; SendDir;
BothDir = RecvDir | SendDir; BothDir = RecvDir|SendDir;
) )
// ChanType represents a channel type. // ChanType represents a channel type.
...@@ -269,7 +270,6 @@ type Type interface { ...@@ -269,7 +270,6 @@ type Type interface {
// NumMethod returns the number of such methods. // NumMethod returns the number of such methods.
Method(int) Method; Method(int) Method;
NumMethod() int; NumMethod() int;
uncommon() *uncommonType; uncommon() *uncommonType;
} }
...@@ -279,7 +279,7 @@ func (t *uncommonType) uncommon() *uncommonType { ...@@ -279,7 +279,7 @@ func (t *uncommonType) uncommon() *uncommonType {
func (t *uncommonType) PkgPath() string { func (t *uncommonType) PkgPath() string {
if t == nil || t.pkgPath == nil { if t == nil || t.pkgPath == nil {
return "" return "";
} }
return *t.pkgPath; return *t.pkgPath;
} }
...@@ -509,7 +509,7 @@ func (t *StructType) FieldByIndex(index []int) (f StructField) { ...@@ -509,7 +509,7 @@ func (t *StructType) FieldByIndex(index []int) (f StructField) {
return; return;
} }
const inf = 1 << 30; // infinity - no struct has that many nesting levels const inf = 1<<30 // infinity - no struct has that many nesting levels
func (t *StructType) fieldByName(name string, mark map[*StructType]bool, depth int) (ff StructField, fd int) { func (t *StructType) fieldByName(name string, mark map[*StructType]bool, depth int) (ff StructField, fd int) {
fd = inf; // field depth fd = inf; // field depth
...@@ -584,7 +584,7 @@ func (t *StructType) FieldByName(name string) (f StructField, present bool) { ...@@ -584,7 +584,7 @@ func (t *StructType) FieldByName(name string) (f StructField, present bool) {
ff.Index = ff.Index[0 : fd+1]; ff.Index = ff.Index[0 : fd+1];
f, present = ff, true; f, present = ff, true;
} }
return return;
} }
// NumField returns the number of struct fields. // NumField returns the number of struct fields.
...@@ -663,5 +663,3 @@ type ArrayOrSliceType interface { ...@@ -663,5 +663,3 @@ type ArrayOrSliceType interface {
func Typeof(i interface{}) Type { func Typeof(i interface{}) Type {
return toType(unsafe.Typeof(i)); return toType(unsafe.Typeof(i));
} }
...@@ -35,22 +35,23 @@ type stringError struct { ...@@ -35,22 +35,23 @@ type stringError struct {
re string; re string;
err os.Error; err os.Error;
} }
var bad_re = []stringError{ var bad_re = []stringError{
stringError{ `*`, ErrBareClosure }, stringError{`*`, ErrBareClosure},
stringError{ `(abc`, ErrUnmatchedLpar }, stringError{`(abc`, ErrUnmatchedLpar},
stringError{ `abc)`, ErrUnmatchedRpar }, stringError{`abc)`, ErrUnmatchedRpar},
stringError{ `x[a-z`, ErrUnmatchedLbkt }, stringError{`x[a-z`, ErrUnmatchedLbkt},
stringError{ `abc]`, ErrUnmatchedRbkt }, stringError{`abc]`, ErrUnmatchedRbkt},
stringError{ `[z-a]`, ErrBadRange }, stringError{`[z-a]`, ErrBadRange},
stringError{ `abc\`, ErrExtraneousBackslash }, stringError{`abc\`, ErrExtraneousBackslash},
stringError{ `a**`, ErrBadClosure }, stringError{`a**`, ErrBadClosure},
stringError{ `a*+`, ErrBadClosure }, stringError{`a*+`, ErrBadClosure},
stringError{ `a??`, ErrBadClosure }, stringError{`a??`, ErrBadClosure},
stringError{ `*`, ErrBareClosure }, stringError{`*`, ErrBareClosure},
stringError{ `\x`, ErrBadBackslash }, stringError{`\x`, ErrBadBackslash},
} }
type vec []int; type vec []int
type tester struct { type tester struct {
re string; re string;
...@@ -58,33 +59,33 @@ type tester struct { ...@@ -58,33 +59,33 @@ type tester struct {
match vec; match vec;
} }
var matches = []tester { var matches = []tester{
tester{ ``, "", vec{0,0} }, tester{``, "", vec{0, 0}},
tester{ `a`, "a", vec{0,1} }, tester{`a`, "a", vec{0, 1}},
tester{ `x`, "y", vec{} }, tester{`x`, "y", vec{}},
tester{ `b`, "abc", vec{1,2} }, tester{`b`, "abc", vec{1, 2}},
tester{ `.`, "a", vec{0,1} }, tester{`.`, "a", vec{0, 1}},
tester{ `.*`, "abcdef", vec{0,6} }, tester{`.*`, "abcdef", vec{0, 6}},
tester{ `^abcd$`, "abcd", vec{0,4} }, tester{`^abcd$`, "abcd", vec{0, 4}},
tester{ `^bcd'`, "abcdef", vec{} }, tester{`^bcd'`, "abcdef", vec{}},
tester{ `^abcd$`, "abcde", vec{} }, tester{`^abcd$`, "abcde", vec{}},
tester{ `a+`, "baaab", vec{1,4} }, tester{`a+`, "baaab", vec{1, 4}},
tester{ `a*`, "baaab", vec{0,0} }, tester{`a*`, "baaab", vec{0, 0}},
tester{ `[a-z]+`, "abcd", vec{0,4} }, tester{`[a-z]+`, "abcd", vec{0, 4}},
tester{ `[^a-z]+`, "ab1234cd", vec{2,6} }, tester{`[^a-z]+`, "ab1234cd", vec{2, 6}},
tester{ `[a\-\]z]+`, "az]-bcz", vec{0,4} }, tester{`[a\-\]z]+`, "az]-bcz", vec{0, 4}},
tester{ `[^\n]+`, "abcd\n", vec{0,4} }, tester{`[^\n]+`, "abcd\n", vec{0, 4}},
tester{ `[日本語]+`, "日本語日本語", vec{0,18} }, tester{`[日本語]+`, "日本語日本語", vec{0, 18}},
tester{ `()`, "", vec{0,0, 0,0} }, tester{`()`, "", vec{0, 0, 0, 0}},
tester{ `(a)`, "a", vec{0,1, 0,1} }, tester{`(a)`, "a", vec{0, 1, 0, 1}},
tester{ `(.)(.)`, "日a", vec{0,4, 0,3, 3,4} }, tester{`(.)(.)`, "日a", vec{0, 4, 0, 3, 3, 4}},
tester{ `(.*)`, "", vec{0,0, 0,0} }, tester{`(.*)`, "", vec{0, 0, 0, 0}},
tester{ `(.*)`, "abcd", vec{0,4, 0,4} }, tester{`(.*)`, "abcd", vec{0, 4, 0, 4}},
tester{ `(..)(..)`, "abcd", vec{0,4, 0,2, 2,4} }, tester{`(..)(..)`, "abcd", vec{0, 4, 0, 2, 2, 4}},
tester{ `(([^xyz]*)(d))`, "abcd", vec{0,4, 0,4, 0,3, 3,4} }, tester{`(([^xyz]*)(d))`, "abcd", vec{0, 4, 0, 4, 0, 3, 3, 4}},
tester{ `((a|b|c)*(d))`, "abcd", vec{0,4, 0,4, 2,3, 3,4} }, tester{`((a|b|c)*(d))`, "abcd", vec{0, 4, 0, 4, 2, 3, 3, 4}},
tester{ `(((a|b|c)*)(d))`, "abcd", vec{0,4, 0,4, 0,3, 2,3, 3,4} }, tester{`(((a|b|c)*)(d))`, "abcd", vec{0, 4, 0, 4, 0, 3, 2, 3, 3, 4}},
tester{ `a*(|(b))c*`, "aacc", vec{0,4, 2,2, -1,-1} }, tester{`a*(|(b))c*`, "aacc", vec{0, 4, 2, 2, -1, -1}},
} }
func compileTest(t *testing.T, expr string, error os.Error) *Regexp { func compileTest(t *testing.T, expr string, error os.Error) *Regexp {
...@@ -92,7 +93,7 @@ func compileTest(t *testing.T, expr string, error os.Error) *Regexp { ...@@ -92,7 +93,7 @@ func compileTest(t *testing.T, expr string, error os.Error) *Regexp {
if err != error { if err != error {
t.Error("compiling `", expr, "`; unexpected error: ", err.String()); t.Error("compiling `", expr, "`; unexpected error: ", err.String());
} }
return re return re;
} }
func printVec(t *testing.T, m []int) { func printVec(t *testing.T, m []int) {
...@@ -101,7 +102,7 @@ func printVec(t *testing.T, m []int) { ...@@ -101,7 +102,7 @@ func printVec(t *testing.T, m []int) {
t.Log("\t<no match>"); t.Log("\t<no match>");
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i+2 {
t.Log("\t", m[i], ",", m[i+1]) t.Log("\t", m[i], ",", m[i+1]);
} }
} }
} }
...@@ -112,7 +113,7 @@ func printStrings(t *testing.T, m []string) { ...@@ -112,7 +113,7 @@ func printStrings(t *testing.T, m []string) {
t.Log("\t<no match>"); t.Log("\t<no match>");
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i+2 {
t.Logf("\t%q", m[i]) t.Logf("\t%q", m[i]);
} }
} }
} }
...@@ -123,7 +124,7 @@ func printBytes(t *testing.T, b [][]byte) { ...@@ -123,7 +124,7 @@ func printBytes(t *testing.T, b [][]byte) {
t.Log("\t<no match>"); t.Log("\t<no match>");
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i+2 {
t.Logf("\t%q", b[i]) t.Logf("\t%q", b[i]);
} }
} }
} }
...@@ -131,46 +132,46 @@ func printBytes(t *testing.T, b [][]byte) { ...@@ -131,46 +132,46 @@ func printBytes(t *testing.T, b [][]byte) {
func equal(m1, m2 []int) bool { func equal(m1, m2 []int) bool {
l := len(m1); l := len(m1);
if l != len(m2) { if l != len(m2) {
return false return false;
} }
for i := 0; i < l; i++ { for i := 0; i < l; i++ {
if m1[i] != m2[i] { if m1[i] != m2[i] {
return false return false;
} }
} }
return true return true;
} }
func equalStrings(m1, m2 []string) bool { func equalStrings(m1, m2 []string) bool {
l := len(m1); l := len(m1);
if l != len(m2) { if l != len(m2) {
return false return false;
} }
for i := 0; i < l; i++ { for i := 0; i < l; i++ {
if m1[i] != m2[i] { if m1[i] != m2[i] {
return false return false;
} }
} }
return true return true;
} }
func equalBytes(m1 [][]byte, m2 []string) bool { func equalBytes(m1 [][]byte, m2 []string) bool {
l := len(m1); l := len(m1);
if l != len(m2) { if l != len(m2) {
return false return false;
} }
for i := 0; i < l; i++ { for i := 0; i < l; i++ {
if string(m1[i]) != m2[i] { if string(m1[i]) != m2[i] {
return false return false;
} }
} }
return true return true;
} }
func executeTest(t *testing.T, expr string, str string, match []int) { func executeTest(t *testing.T, expr string, str string, match []int) {
re := compileTest(t, expr, nil); re := compileTest(t, expr, nil);
if re == nil { if re == nil {
return return;
} }
m := re.ExecuteString(str); m := re.ExecuteString(str);
if !equal(m, match) { if !equal(m, match) {
...@@ -197,21 +198,21 @@ func TestGoodCompile(t *testing.T) { ...@@ -197,21 +198,21 @@ func TestGoodCompile(t *testing.T) {
func TestBadCompile(t *testing.T) { func TestBadCompile(t *testing.T) {
for i := 0; i < len(bad_re); i++ { for i := 0; i < len(bad_re); i++ {
compileTest(t, bad_re[i].re, bad_re[i].err) compileTest(t, bad_re[i].re, bad_re[i].err);
} }
} }
func TestExecute(t *testing.T) { func TestExecute(t *testing.T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i];
executeTest(t, test.re, test.text, test.match) executeTest(t, test.re, test.text, test.match);
} }
} }
func matchTest(t *testing.T, expr string, str string, match []int) { func matchTest(t *testing.T, expr string, str string, match []int) {
re := compileTest(t, expr, nil); re := compileTest(t, expr, nil);
if re == nil { if re == nil {
return return;
} }
m := re.MatchString(str); m := re.MatchString(str);
if m != (len(match) > 0) { if m != (len(match) > 0) {
...@@ -227,18 +228,18 @@ func matchTest(t *testing.T, expr string, str string, match []int) { ...@@ -227,18 +228,18 @@ func matchTest(t *testing.T, expr string, str string, match []int) {
func TestMatch(t *testing.T) { func TestMatch(t *testing.T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i];
matchTest(t, test.re, test.text, test.match) matchTest(t, test.re, test.text, test.match);
} }
} }
func matchStringsTest(t *testing.T, expr string, str string, match []int) { func matchStringsTest(t *testing.T, expr string, str string, match []int) {
re := compileTest(t, expr, nil); re := compileTest(t, expr, nil);
if re == nil { if re == nil {
return return;
} }
strs := make([]string, len(match)/2); strs := make([]string, len(match)/2);
for i := 0; i < len(match); i++ { for i := 0; i < len(match); i++ {
strs[i/2] = str[match[i] : match[i+1]] strs[i/2] = str[match[i]:match[i+1]];
} }
m := re.MatchStrings(str); m := re.MatchStrings(str);
if !equalStrings(m, strs) { if !equalStrings(m, strs) {
...@@ -260,14 +261,14 @@ func matchStringsTest(t *testing.T, expr string, str string, match []int) { ...@@ -260,14 +261,14 @@ func matchStringsTest(t *testing.T, expr string, str string, match []int) {
func TestMatchStrings(t *testing.T) { func TestMatchStrings(t *testing.T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i];
matchTest(t, test.re, test.text, test.match) matchTest(t, test.re, test.text, test.match);
} }
} }
func matchFunctionTest(t *testing.T, expr string, str string, match []int) { func matchFunctionTest(t *testing.T, expr string, str string, match []int) {
m, err := MatchString(expr, str); m, err := MatchString(expr, str);
if err == nil { if err == nil {
return return;
} }
if m != (len(match) > 0) { if m != (len(match) > 0) {
t.Error("function Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0); t.Error("function Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0);
...@@ -277,7 +278,7 @@ func matchFunctionTest(t *testing.T, expr string, str string, match []int) { ...@@ -277,7 +278,7 @@ func matchFunctionTest(t *testing.T, expr string, str string, match []int) {
func TestMatchFunction(t *testing.T) { func TestMatchFunction(t *testing.T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i];
matchFunctionTest(t, test.re, test.text, test.match) matchFunctionTest(t, test.re, test.text, test.match);
} }
} }
...@@ -285,7 +286,7 @@ type ReplaceTest struct { ...@@ -285,7 +286,7 @@ type ReplaceTest struct {
pattern, replacement, input, output string; pattern, replacement, input, output string;
} }
var replaceTests = []ReplaceTest { var replaceTests = []ReplaceTest{
// Test empty input and/or replacement, with pattern that matches the empty string. // Test empty input and/or replacement, with pattern that matches the empty string.
ReplaceTest{"", "", "", ""}, ReplaceTest{"", "", "", ""},
ReplaceTest{"", "x", "", "x"}, ReplaceTest{"", "x", "", "x"},
...@@ -372,7 +373,7 @@ type QuoteMetaTest struct { ...@@ -372,7 +373,7 @@ type QuoteMetaTest struct {
pattern, output string; pattern, output string;
} }
var quoteMetaTests = []QuoteMetaTest { var quoteMetaTests = []QuoteMetaTest{
QuoteMetaTest{``, ``}, QuoteMetaTest{``, ``},
QuoteMetaTest{`foo`, `foo`}, QuoteMetaTest{`foo`, `foo`},
QuoteMetaTest{`!@#$%^&*()_+-=[{]}\|,<.>/?~`, `!@#\$%\^&\*\(\)_\+-=\[{\]}\\\|,<\.>/\?~`}, QuoteMetaTest{`!@#$%^&*()_+-=[{]}\|,<.>/?~`, `!@#\$%\^&\*\(\)_\+-=\[{\]}\\\|,<\.>/\?~`},
...@@ -416,23 +417,23 @@ type matchCase struct { ...@@ -416,23 +417,23 @@ type matchCase struct {
expected []string; expected []string;
} }
var matchCases = []matchCase { var matchCases = []matchCase{
matchCase{"match", " aa b", 0, "[^ ]+", []string { "aa", "b" }}, matchCase{"match", " aa b", 0, "[^ ]+", []string{"aa", "b"}},
matchCase{"match", " aa b", 0, "[^ ]*", []string { "", "aa", "b" }}, matchCase{"match", " aa b", 0, "[^ ]*", []string{"", "aa", "b"}},
matchCase{"match", "a b c", 0, "[^ ]*", []string { "a", "b", "c" }}, matchCase{"match", "a b c", 0, "[^ ]*", []string{"a", "b", "c"}},
matchCase{"match", "a:a: a:", 0, "^.:", []string { "a:" }}, matchCase{"match", "a:a: a:", 0, "^.:", []string{"a:"}},
matchCase{"match", "", 0, "[^ ]*", []string { "" }}, matchCase{"match", "", 0, "[^ ]*", []string{""}},
matchCase{"match", "", 0, "", []string { "" }}, matchCase{"match", "", 0, "", []string{""}},
matchCase{"match", "a", 0, "", []string { "", "" }}, matchCase{"match", "a", 0, "", []string{"", ""}},
matchCase{"match", "ab", 0, "^", []string { "", }}, matchCase{"match", "ab", 0, "^", []string{""}},
matchCase{"match", "ab", 0, "$", []string { "", }}, matchCase{"match", "ab", 0, "$", []string{""}},
matchCase{"match", "ab", 0, "X*", []string { "", "", "" }}, matchCase{"match", "ab", 0, "X*", []string{"", "", ""}},
matchCase{"match", "aX", 0, "X*", []string { "", "X" }}, matchCase{"match", "aX", 0, "X*", []string{"", "X"}},
matchCase{"match", "XabX", 0, "X*", []string { "X", "", "X" }}, matchCase{"match", "XabX", 0, "X*", []string{"X", "", "X"}},
matchCase{"matchit", "", 0, ".", []string {}}, matchCase{"matchit", "", 0, ".", []string{}},
matchCase{"matchit", "abc", 2, ".", []string { "a", "b" }}, matchCase{"matchit", "abc", 2, ".", []string{"a", "b"}},
matchCase{"matchit", "abc", 0, ".", []string { "a", "b", "c" }}, matchCase{"matchit", "abc", 0, ".", []string{"a", "b", "c"}},
} }
func printStringSlice(t *testing.T, s []string) { func printStringSlice(t *testing.T, s []string) {
...@@ -441,7 +442,7 @@ func printStringSlice(t *testing.T, s []string) { ...@@ -441,7 +442,7 @@ func printStringSlice(t *testing.T, s []string) {
t.Log("\t<empty>"); t.Log("\t<empty>");
} else { } else {
for i := 0; i < l; i++ { for i := 0; i < l; i++ {
t.Logf("\t%q", s[i]) t.Logf("\t%q", s[i]);
} }
} }
} }
...@@ -456,7 +457,8 @@ func TestAllMatches(t *testing.T) { ...@@ -456,7 +457,8 @@ func TestAllMatches(t *testing.T) {
c.input, c.input,
c.n, c.n,
c.regexp, c.regexp,
c.expected }; c.expected,
};
ch <- stringCase; ch <- stringCase;
} }
close(ch); close(ch);
......
...@@ -17,8 +17,7 @@ import ( ...@@ -17,8 +17,7 @@ import (
"template"; "template";
) )
const debugText = const debugText = `<html>
`<html>
<body> <body>
<title>Services</title> <title>Services</title>
{.repeated section @} {.repeated section @}
...@@ -55,13 +54,25 @@ type debugService struct { ...@@ -55,13 +54,25 @@ type debugService struct {
type serviceArray []debugService type serviceArray []debugService
func (s serviceArray) Len() int { return len(s) } func (s serviceArray) Len() int {
func (s serviceArray) Less(i, j int) bool { return s[i].name < s[j].name } return len(s);
func (s serviceArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] } }
func (s serviceArray) Less(i, j int) bool {
return s[i].name < s[j].name;
}
func (s serviceArray) Swap(i, j int) {
s[i], s[j] = s[j], s[i];
}
func (m methodArray) Len() int { return len(m) } func (m methodArray) Len() int {
func (m methodArray) Less(i, j int) bool { return m[i].name < m[j].name } return len(m);
func (m methodArray) Swap(i, j int) { m[i], m[j] = m[j], m[i] } }
func (m methodArray) Less(i, j int) bool {
return m[i].name < m[j].name;
}
func (m methodArray) Swap(i, j int) {
m[i], m[j] = m[j], m[i];
}
// Runs at /debug/rpc // Runs at /debug/rpc
func debugHTTP(c *http.Conn, req *http.Request) { func debugHTTP(c *http.Conn, req *http.Request) {
......
...@@ -123,7 +123,7 @@ import ( ...@@ -123,7 +123,7 @@ import (
// Precompute the reflect type for os.Error. Can't use os.Error directly // Precompute the reflect type for os.Error. Can't use os.Error directly
// because Typeof takes an empty interface value. This is annoying. // because Typeof takes an empty interface value. This is annoying.
var unusedError *os.Error; var unusedError *os.Error
var typeOfOsError = reflect.Typeof(unusedError).(*reflect.PtrType).Elem() var typeOfOsError = reflect.Typeof(unusedError).(*reflect.PtrType).Elem()
type methodType struct { type methodType struct {
...@@ -138,7 +138,7 @@ type service struct { ...@@ -138,7 +138,7 @@ type service struct {
name string; // name of service name string; // name of service
rcvr reflect.Value; // receiver of methods for the service rcvr reflect.Value; // receiver of methods for the service
typ reflect.Type; // type of the receiver typ reflect.Type; // type of the receiver
method map[string] *methodType; // registered methods method map[string]*methodType; // registered methods
} }
// Request is a header written before every RPC call. It is used internally // Request is a header written before every RPC call. It is used internally
...@@ -160,32 +160,32 @@ type Response struct { ...@@ -160,32 +160,32 @@ type Response struct {
type serverType struct { type serverType struct {
sync.Mutex; // protects the serviceMap sync.Mutex; // protects the serviceMap
serviceMap map[string] *service; serviceMap map[string]*service;
} }
// This variable is a global whose "public" methods are really private methods // This variable is a global whose "public" methods are really private methods
// called from the global functions of this package: rpc.Register, rpc.ServeConn, etc. // called from the global functions of this package: rpc.Register, rpc.ServeConn, etc.
// For example, rpc.Register() calls server.add(). // For example, rpc.Register() calls server.add().
var server = &serverType{ serviceMap: make(map[string] *service) } var server = &serverType{serviceMap: make(map[string]*service)}
// Is this a publicly vislble - upper case - name? // Is this a publicly vislble - upper case - name?
func isPublic(name string) bool { func isPublic(name string) bool {
rune, _ := utf8.DecodeRuneInString(name); rune, _ := utf8.DecodeRuneInString(name);
return unicode.IsUpper(rune) return unicode.IsUpper(rune);
} }
func (server *serverType) register(rcvr interface{}) os.Error { func (server *serverType) register(rcvr interface{}) os.Error {
server.Lock(); server.Lock();
defer server.Unlock(); defer server.Unlock();
if server.serviceMap == nil { if server.serviceMap == nil {
server.serviceMap = make(map[string] *service); server.serviceMap = make(map[string]*service);
} }
s := new(service); s := new(service);
s.typ = reflect.Typeof(rcvr); s.typ = reflect.Typeof(rcvr);
s.rcvr = reflect.NewValue(rcvr); s.rcvr = reflect.NewValue(rcvr);
sname := reflect.Indirect(s.rcvr).Type().Name(); sname := reflect.Indirect(s.rcvr).Type().Name();
if sname == "" { if sname == "" {
log.Exit("rpc: no service name for type", s.typ.String()) log.Exit("rpc: no service name for type", s.typ.String());
} }
if !isPublic(sname) { if !isPublic(sname) {
s := "rpc Register: type " + sname + " is not public"; s := "rpc Register: type " + sname + " is not public";
...@@ -196,7 +196,7 @@ func (server *serverType) register(rcvr interface{}) os.Error { ...@@ -196,7 +196,7 @@ func (server *serverType) register(rcvr interface{}) os.Error {
return os.ErrorString("rpc: service already defined: " + sname); return os.ErrorString("rpc: service already defined: " + sname);
} }
s.name = sname; s.name = sname;
s.method = make(map[string] *methodType); s.method = make(map[string]*methodType);
// Install the methods // Install the methods
for m := 0; m < s.typ.NumMethod(); m++ { for m := 0; m < s.typ.NumMethod(); m++ {
...@@ -204,7 +204,7 @@ func (server *serverType) register(rcvr interface{}) os.Error { ...@@ -204,7 +204,7 @@ func (server *serverType) register(rcvr interface{}) os.Error {
mtype := method.Type; mtype := method.Type;
mname := method.Name; mname := method.Name;
if !isPublic(mname) { if !isPublic(mname) {
continue continue;
} }
// Method needs three ins: receiver, *args, *reply. // Method needs three ins: receiver, *args, *reply.
// The args and reply must be structs until gobs are more general. // The args and reply must be structs until gobs are more general.
...@@ -261,8 +261,9 @@ func (server *serverType) register(rcvr interface{}) os.Error { ...@@ -261,8 +261,9 @@ func (server *serverType) register(rcvr interface{}) os.Error {
// A value sent as a placeholder for the response when the server receives an invalid request. // A value sent as a placeholder for the response when the server receives an invalid request.
type InvalidRequest struct { type InvalidRequest struct {
marker int marker int;
} }
var invalidRequest = InvalidRequest{1} var invalidRequest = InvalidRequest{1}
func _new(t *reflect.PtrType) *reflect.PtrValue { func _new(t *reflect.PtrType) *reflect.PtrValue {
...@@ -370,21 +371,21 @@ func (server *serverType) accept(lis net.Listener) { ...@@ -370,21 +371,21 @@ func (server *serverType) accept(lis net.Listener) {
// It returns an error if the receiver is not public or has no // It returns an error if the receiver is not public or has no
// suitable methods. // suitable methods.
func Register(rcvr interface{}) os.Error { func Register(rcvr interface{}) os.Error {
return server.register(rcvr) return server.register(rcvr);
} }
// ServeConn runs the server on a single connection. When the connection // ServeConn runs the server on a single connection. When the connection
// completes, service terminates. ServeConn blocks; the caller typically // completes, service terminates. ServeConn blocks; the caller typically
// invokes it in a go statement. // invokes it in a go statement.
func ServeConn(conn io.ReadWriteCloser) { func ServeConn(conn io.ReadWriteCloser) {
go server.input(conn) go server.input(conn);
} }
// Accept accepts connections on the listener and serves requests // Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks; the caller typically // for each incoming connection. Accept blocks; the caller typically
// invokes it in a go statement. // invokes it in a go statement.
func Accept(lis net.Listener) { func Accept(lis net.Listener) {
server.accept(lis) server.accept(lis);
} }
// Can connect to RPC service using HTTP CONNECT to rpcPath. // Can connect to RPC service using HTTP CONNECT to rpcPath.
......
...@@ -21,23 +21,23 @@ const second = 1e9 ...@@ -21,23 +21,23 @@ const second = 1e9
type Args struct { type Args struct {
A, B int A, B int;
} }
type Reply struct { type Reply struct {
C int C int;
} }
type Arith int type Arith int
func (t *Arith) Add(args *Args, reply *Reply) os.Error { func (t *Arith) Add(args *Args, reply *Reply) os.Error {
reply.C = args.A + args.B; reply.C = args.A + args.B;
return nil return nil;
} }
func (t *Arith) Mul(args *Args, reply *Reply) os.Error { func (t *Arith) Mul(args *Args, reply *Reply) os.Error {
reply.C = args.A * args.B; reply.C = args.A * args.B;
return nil return nil;
} }
func (t *Arith) Div(args *Args, reply *Reply) os.Error { func (t *Arith) Div(args *Args, reply *Reply) os.Error {
...@@ -45,7 +45,7 @@ func (t *Arith) Div(args *Args, reply *Reply) os.Error { ...@@ -45,7 +45,7 @@ func (t *Arith) Div(args *Args, reply *Reply) os.Error {
return os.ErrorString("divide by zero"); return os.ErrorString("divide by zero");
} }
reply.C = args.A / args.B; reply.C = args.A / args.B;
return nil return nil;
} }
func (t *Arith) Error(args *Args, reply *Reply) os.Error { func (t *Arith) Error(args *Args, reply *Reply) os.Error {
...@@ -83,14 +83,14 @@ func TestRPC(t *testing.T) { ...@@ -83,14 +83,14 @@ func TestRPC(t *testing.T) {
} }
// Synchronous calls // Synchronous calls
args := &Args{7,8}; args := &Args{7, 8};
reply := new(Reply); reply := new(Reply);
err = client.Call("Arith.Add", args, reply); err = client.Call("Arith.Add", args, reply);
if reply.C != args.A + args.B { if reply.C != args.A + args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A + args.B); t.Errorf("Add: expected %d got %d", reply.C, args.A + args.B);
} }
args = &Args{7,8}; args = &Args{7, 8};
reply = new(Reply); reply = new(Reply);
err = client.Call("Arith.Mul", args, reply); err = client.Call("Arith.Mul", args, reply);
if reply.C != args.A * args.B { if reply.C != args.A * args.B {
...@@ -98,7 +98,7 @@ func TestRPC(t *testing.T) { ...@@ -98,7 +98,7 @@ func TestRPC(t *testing.T) {
} }
// Out of order. // Out of order.
args = &Args{7,8}; args = &Args{7, 8};
mulReply := new(Reply); mulReply := new(Reply);
mulCall := client.Go("Arith.Mul", args, mulReply, nil); mulCall := client.Go("Arith.Mul", args, mulReply, nil);
addReply := new(Reply); addReply := new(Reply);
...@@ -115,7 +115,7 @@ func TestRPC(t *testing.T) { ...@@ -115,7 +115,7 @@ func TestRPC(t *testing.T) {
} }
// Error test // Error test
args = &Args{7,0}; args = &Args{7, 0};
reply = new(Reply); reply = new(Reply);
err = client.Call("Arith.Div", args, reply); err = client.Call("Arith.Div", args, reply);
// expect an error: zero divide // expect an error: zero divide
...@@ -135,7 +135,7 @@ func TestHTTPRPC(t *testing.T) { ...@@ -135,7 +135,7 @@ func TestHTTPRPC(t *testing.T) {
} }
// Synchronous calls // Synchronous calls
args := &Args{7,8}; args := &Args{7, 8};
reply := new(Reply); reply := new(Reply);
err = client.Call("Arith.Add", args, reply); err = client.Call("Arith.Add", args, reply);
if reply.C != args.A + args.B { if reply.C != args.A + args.B {
...@@ -148,12 +148,12 @@ func TestCheckUnknownService(t *testing.T) { ...@@ -148,12 +148,12 @@ func TestCheckUnknownService(t *testing.T) {
conn, err := net.Dial("tcp", "", serverAddr); conn, err := net.Dial("tcp", "", serverAddr);
if err != nil { if err != nil {
t.Fatal("dialing:", err) t.Fatal("dialing:", err);
} }
client := NewClient(conn); client := NewClient(conn);
args := &Args{7,8}; args := &Args{7, 8};
reply := new(Reply); reply := new(Reply);
err = client.Call("Unknown.Add", args, reply); err = client.Call("Unknown.Add", args, reply);
if err == nil { if err == nil {
...@@ -168,12 +168,12 @@ func TestCheckUnknownMethod(t *testing.T) { ...@@ -168,12 +168,12 @@ func TestCheckUnknownMethod(t *testing.T) {
conn, err := net.Dial("tcp", "", serverAddr); conn, err := net.Dial("tcp", "", serverAddr);
if err != nil { if err != nil {
t.Fatal("dialing:", err) t.Fatal("dialing:", err);
} }
client := NewClient(conn); client := NewClient(conn);
args := &Args{7,8}; args := &Args{7, 8};
reply := new(Reply); reply := new(Reply);
err = client.Call("Arith.Unknown", args, reply); err = client.Call("Arith.Unknown", args, reply);
if err == nil { if err == nil {
...@@ -188,7 +188,7 @@ func TestCheckBadType(t *testing.T) { ...@@ -188,7 +188,7 @@ func TestCheckBadType(t *testing.T) {
conn, err := net.Dial("tcp", "", serverAddr); conn, err := net.Dial("tcp", "", serverAddr);
if err != nil { if err != nil {
t.Fatal("dialing:", err) t.Fatal("dialing:", err);
} }
client := NewClient(conn); client := NewClient(conn);
......
...@@ -46,10 +46,16 @@ func medianOfThree(data SortInterface, a, b, c int) { ...@@ -46,10 +46,16 @@ func medianOfThree(data SortInterface, a, b, c int) {
m1 := a; m1 := a;
m2 := c; m2 := c;
// bubble sort on 3 elements // bubble sort on 3 elements
if data.Less(m1, m0) { data.Swap(m1, m0); } if data.Less(m1, m0) {
if data.Less(m2, m1) { data.Swap(m2, m1); } data.Swap(m1, m0);
if data.Less(m1, m0) { data.Swap(m1, m0); } }
// now data[m0] <= data[m1] <= data[m2] if data.Less(m2, m1) {
data.Swap(m2, m1);
}
if data.Less(m1, m0) {
data.Swap(m1, m0);
}
// now data[m0] <= data[m1] <= data[m2]
} }
func swapRange(data SortInterface, a, b, n int) { func swapRange(data SortInterface, a, b, n int) {
...@@ -60,12 +66,12 @@ func swapRange(data SortInterface, a, b, n int) { ...@@ -60,12 +66,12 @@ func swapRange(data SortInterface, a, b, n int) {
func doPivot(data SortInterface, lo, hi int) (midlo, midhi int) { func doPivot(data SortInterface, lo, hi int) (midlo, midhi int) {
m := (lo+hi)/2; m := (lo+hi)/2;
if hi - lo > 40 { if hi-lo > 40 {
// Tukey's ``Ninther,'' median of three medians of three. // Tukey's ``Ninther,'' median of three medians of three.
s := (hi - lo) / 8; s := (hi-lo)/8;
medianOfThree(data, lo, lo+s, lo+2*s); medianOfThree(data, lo, lo+s, lo + 2*s);
medianOfThree(data, m, m-s, m+s); medianOfThree(data, m, m-s, m+s);
medianOfThree(data, hi-1, hi-1-s, hi-1-2*s); medianOfThree(data, hi-1, hi-1-s, hi - 1 - 2*s);
} }
medianOfThree(data, lo, m, hi-1); medianOfThree(data, lo, m, hi-1);
...@@ -118,11 +124,11 @@ func doPivot(data SortInterface, lo, hi int) (midlo, midhi int) { ...@@ -118,11 +124,11 @@ func doPivot(data SortInterface, lo, hi int) (midlo, midhi int) {
} }
func quickSort(data SortInterface, a, b int) { func quickSort(data SortInterface, a, b int) {
if b - a > 7 { if b-a > 7 {
mlo, mhi := doPivot(data, a, b); mlo, mhi := doPivot(data, a, b);
quickSort(data, a, mlo); quickSort(data, a, mlo);
quickSort(data, mhi, b); quickSort(data, mhi, b);
} else if b - a > 1 { } else if b-a > 1 {
insertionSort(data, a, b); insertionSort(data, a, b);
} }
} }
...@@ -134,8 +140,8 @@ func Sort(data SortInterface) { ...@@ -134,8 +140,8 @@ func Sort(data SortInterface) {
func IsSorted(data SortInterface) bool { func IsSorted(data SortInterface) bool {
n := data.Len(); n := data.Len();
for i := n - 1; i > 0; i-- { for i := n-1; i > 0; i-- {
if data.Less(i, i - 1) { if data.Less(i, i-1) {
return false; return false;
} }
} }
...@@ -148,49 +154,85 @@ func IsSorted(data SortInterface) bool { ...@@ -148,49 +154,85 @@ func IsSorted(data SortInterface) bool {
// IntArray attaches the methods of SortInterface to []int, sorting in increasing order. // IntArray attaches the methods of SortInterface to []int, sorting in increasing order.
type IntArray []int type IntArray []int
func (p IntArray) Len() int { return len(p); } func (p IntArray) Len() int {
func (p IntArray) Less(i, j int) bool { return p[i] < p[j]; } return len(p);
func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } }
func (p IntArray) Less(i, j int) bool {
return p[i] < p[j];
}
func (p IntArray) Swap(i, j int) {
p[i], p[j] = p[j], p[i];
}
// Sort is a convenience method. // Sort is a convenience method.
func (p IntArray) Sort() { Sort(p); } func (p IntArray) Sort() {
Sort(p);
}
// FloatArray attaches the methods of SortInterface to []float, sorting in increasing order. // FloatArray attaches the methods of SortInterface to []float, sorting in increasing order.
type FloatArray []float type FloatArray []float
func (p FloatArray) Len() int { return len(p); } func (p FloatArray) Len() int {
func (p FloatArray) Less(i, j int) bool { return p[i] < p[j]; } return len(p);
func (p FloatArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } }
func (p FloatArray) Less(i, j int) bool {
return p[i] < p[j];
}
func (p FloatArray) Swap(i, j int) {
p[i], p[j] = p[j], p[i];
}
// Sort is a convenience method. // Sort is a convenience method.
func (p FloatArray) Sort() { Sort(p); } func (p FloatArray) Sort() {
Sort(p);
}
// StringArray attaches the methods of SortInterface to []string, sorting in increasing order. // StringArray attaches the methods of SortInterface to []string, sorting in increasing order.
type StringArray []string type StringArray []string
func (p StringArray) Len() int { return len(p); } func (p StringArray) Len() int {
func (p StringArray) Less(i, j int) bool { return p[i] < p[j]; } return len(p);
func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } }
func (p StringArray) Less(i, j int) bool {
return p[i] < p[j];
}
func (p StringArray) Swap(i, j int) {
p[i], p[j] = p[j], p[i];
}
// Sort is a convenience method. // Sort is a convenience method.
func (p StringArray) Sort() { Sort(p); } func (p StringArray) Sort() {
Sort(p);
}
// Convenience wrappers for common cases // Convenience wrappers for common cases
// SortInts sorts an array of ints in increasing order. // SortInts sorts an array of ints in increasing order.
func SortInts(a []int) { Sort(IntArray(a)); } func SortInts(a []int) {
Sort(IntArray(a));
}
// SortFloats sorts an array of floats in increasing order. // SortFloats sorts an array of floats in increasing order.
func SortFloats(a []float) { Sort(FloatArray(a)); } func SortFloats(a []float) {
Sort(FloatArray(a));
}
// SortStrings sorts an array of strings in increasing order. // SortStrings sorts an array of strings in increasing order.
func SortStrings(a []string) { Sort(StringArray(a)); } func SortStrings(a []string) {
Sort(StringArray(a));
}
// IntsAreSorted tests whether an array of ints is sorted in increasing order. // IntsAreSorted tests whether an array of ints is sorted in increasing order.
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)); } func IntsAreSorted(a []int) bool {
return IsSorted(IntArray(a));
}
// FloatsAreSorted tests whether an array of floats is sorted in increasing order. // FloatsAreSorted tests whether an array of floats is sorted in increasing order.
func FloatsAreSorted(a []float) bool { return IsSorted(FloatArray(a)); } func FloatsAreSorted(a []float) bool {
return IsSorted(FloatArray(a));
}
// StringsAreSorted tests whether an array of strings is sorted in increasing order. // StringsAreSorted tests whether an array of strings is sorted in increasing order.
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)); } func StringsAreSorted(a []string) bool {
return IsSorted(StringArray(a));
}
...@@ -113,8 +113,12 @@ type testingData struct { ...@@ -113,8 +113,12 @@ type testingData struct {
nswap int; nswap int;
} }
func (d *testingData) Len() int { return len(d.data); } func (d *testingData) Len() int {
func (d *testingData) Less(i, j int) bool { return d.data[i] < d.data[j]; } return len(d.data);
}
func (d *testingData) Less(i, j int) bool {
return d.data[i] < d.data[j];
}
func (d *testingData) Swap(i, j int) { func (d *testingData) Swap(i, j int) {
if d.nswap >= d.maxswap { if d.nswap >= d.maxswap {
d.t.Errorf("%s: used %d swaps sorting array of %d", d.desc, d.nswap, len(d.data)); d.t.Errorf("%s: used %d swaps sorting array of %d", d.desc, d.nswap, len(d.data));
...@@ -147,11 +151,11 @@ func TestBentleyMcIlroy(t *testing.T) { ...@@ -147,11 +151,11 @@ func TestBentleyMcIlroy(t *testing.T) {
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
switch dist { switch dist {
case _Sawtooth: case _Sawtooth:
data[i] = i % m; data[i] = i%m;
case _Rand: case _Rand:
data[i] = rand.Intn(m); data[i] = rand.Intn(m);
case _Stagger: case _Stagger:
data[i] = (i*m + i) % n; data[i] = (i*m + i)%n;
case _Plateau: case _Plateau:
data[i] = min(i, m); data[i] = min(i, m);
case _Shuffle: case _Shuffle:
...@@ -178,7 +182,7 @@ func TestBentleyMcIlroy(t *testing.T) { ...@@ -178,7 +182,7 @@ func TestBentleyMcIlroy(t *testing.T) {
} }
case _ReverseFirstHalf: case _ReverseFirstHalf:
for i := 0; i < n/2; i++ { for i := 0; i < n/2; i++ {
mdata[i] = data[n/2-i-1]; mdata[i] = data[n/2 - i - 1];
} }
for i := n/2; i < n; i++ { for i := n/2; i < n; i++ {
mdata[i] = data[i]; mdata[i] = data[i];
...@@ -188,7 +192,7 @@ func TestBentleyMcIlroy(t *testing.T) { ...@@ -188,7 +192,7 @@ func TestBentleyMcIlroy(t *testing.T) {
mdata[i] = data[i]; mdata[i] = data[i];
} }
for i := n/2; i < n; i++ { for i := n/2; i < n; i++ {
mdata[i] = data[n-(i-n/2)-1]; mdata[i] = data[n-(i - n/2)-1];
} }
case _Sorted: case _Sorted:
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
...@@ -225,4 +229,3 @@ func TestBentleyMcIlroy(t *testing.T) { ...@@ -225,4 +229,3 @@ func TestBentleyMcIlroy(t *testing.T) {
} }
} }
} }
...@@ -107,9 +107,7 @@ func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) { ...@@ -107,9 +107,7 @@ func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) {
} }
// decimal power of ten to binary power of two. // decimal power of ten to binary power of two.
var powtab = []int{ var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
1, 3, 6, 9, 13, 16, 19, 23, 26
}
func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uint64, overflow bool) { func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uint64, overflow bool) {
var exp int; var exp int;
...@@ -164,30 +162,30 @@ func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uin ...@@ -164,30 +162,30 @@ func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uin
// Minimum representable exponent is flt.bias+1. // Minimum representable exponent is flt.bias+1.
// If the exponent is smaller, move it up and // If the exponent is smaller, move it up and
// adjust d accordingly. // adjust d accordingly.
if exp < flt.bias+1 { if exp < flt.bias + 1 {
n := flt.bias+1 - exp; n := flt.bias + 1 - exp;
d.Shift(-n); d.Shift(-n);
exp += n; exp += n;
} }
if exp-flt.bias >= 1<<flt.expbits - 1 { if exp - flt.bias >= 1 << flt.expbits - 1 {
goto overflow; goto overflow;
} }
// Extract 1+flt.mantbits bits. // Extract 1+flt.mantbits bits.
mant = d.Shift(int(1+flt.mantbits)).RoundedInteger(); mant = d.Shift(int(1 + flt.mantbits)).RoundedInteger();
// Rounding might have added a bit; shift down. // Rounding might have added a bit; shift down.
if mant == 2<<flt.mantbits { if mant == 2 << flt.mantbits {
mant >>= 1; mant >>= 1;
exp++; exp++;
if exp-flt.bias >= 1<<flt.expbits - 1 { if exp - flt.bias >= 1 << flt.expbits - 1 {
goto overflow; goto overflow;
} }
} }
// Denormalized? // Denormalized?
if mant&(1<<flt.mantbits) == 0 { if mant&(1 << flt.mantbits) == 0 {
exp = flt.bias; exp = flt.bias;
} }
goto out; goto out;
...@@ -195,15 +193,15 @@ func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uin ...@@ -195,15 +193,15 @@ func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uin
overflow: overflow:
// ±Inf // ±Inf
mant = 0; mant = 0;
exp = 1<<flt.expbits - 1 + flt.bias; exp = 1 << flt.expbits - 1 + flt.bias;
overflow = true; overflow = true;
out: out:
// Assemble bits. // Assemble bits.
bits := mant & (uint64(1)<<flt.mantbits - 1); bits := mant&(uint64(1) << flt.mantbits - 1);
bits |= uint64((exp-flt.bias)&(1<<flt.expbits - 1)) << flt.mantbits; bits |= uint64((exp - flt.bias)&(1 << flt.expbits - 1)) << flt.mantbits;
if neg { if neg {
bits |= 1<<flt.mantbits<<flt.expbits; bits |= 1 << flt.mantbits << flt.expbits;
} }
return bits, overflow; return bits, overflow;
} }
...@@ -233,14 +231,12 @@ func decimalAtof32Int(neg bool, d *decimal) float32 { ...@@ -233,14 +231,12 @@ func decimalAtof32Int(neg bool, d *decimal) float32 {
} }
// Exact powers of 10. // Exact powers of 10.
var float64pow10 = []float64 { var float64pow10 = []float64{
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1e20, 1e21, 1e22 1e20, 1e21, 1e22,
}
var float32pow10 = []float32 {
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10
} }
var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
// If possible to convert decimal d to 64-bit float f exactly, // If possible to convert decimal d to 64-bit float f exactly,
// entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits. // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
...@@ -338,7 +334,7 @@ func Atof32(s string) (f float32, err os.Error) { ...@@ -338,7 +334,7 @@ func Atof32(s string) (f float32, err os.Error) {
if ovf { if ovf {
err = &NumError{s, os.ERANGE}; err = &NumError{s, os.ERANGE};
} }
return f, err return f, err;
} }
// Atof64 converts the string s to a 64-bit floating-point number. // Atof64 converts the string s to a 64-bit floating-point number.
...@@ -359,7 +355,7 @@ func Atof64(s string) (f float64, err os.Error) { ...@@ -359,7 +355,7 @@ func Atof64(s string) (f float64, err os.Error) {
if ovf { if ovf {
err = &NumError{s, os.ERANGE}; err = &NumError{s, os.ERANGE};
} }
return f, err return f, err;
} }
// Atof is like Atof32 or Atof64, depending on the size of float. // Atof is like Atof32 or Atof64, depending on the size of float.
...@@ -371,4 +367,3 @@ func Atof(s string) (f float, err os.Error) { ...@@ -371,4 +367,3 @@ func Atof(s string) (f float, err os.Error) {
f1, err1 := Atof64(s); f1, err1 := Atof64(s);
return float(f1), err1; return float(f1), err1;
} }
...@@ -17,79 +17,79 @@ type atofTest struct { ...@@ -17,79 +17,79 @@ type atofTest struct {
err os.Error; err os.Error;
} }
var atoftests = []atofTest { var atoftests = []atofTest{
atofTest{ "", "0", os.EINVAL }, atofTest{"", "0", os.EINVAL},
atofTest{ "1", "1", nil }, atofTest{"1", "1", nil},
atofTest{ "+1", "1", nil }, atofTest{"+1", "1", nil},
atofTest{ "1x", "0", os.EINVAL }, atofTest{"1x", "0", os.EINVAL},
atofTest{ "1.1.", "0", os.EINVAL }, atofTest{"1.1.", "0", os.EINVAL},
atofTest{ "1e23", "1e+23", nil }, atofTest{"1e23", "1e+23", nil},
atofTest{ "100000000000000000000000", "1e+23", nil }, atofTest{"100000000000000000000000", "1e+23", nil},
atofTest{ "1e-100", "1e-100", nil }, atofTest{"1e-100", "1e-100", nil},
atofTest{ "123456700", "1.234567e+08", nil }, atofTest{"123456700", "1.234567e+08", nil},
atofTest{ "99999999999999974834176", "9.999999999999997e+22", nil }, atofTest{"99999999999999974834176", "9.999999999999997e+22", nil},
atofTest{ "100000000000000000000001", "1.0000000000000001e+23", nil }, atofTest{"100000000000000000000001", "1.0000000000000001e+23", nil},
atofTest{ "100000000000000008388608", "1.0000000000000001e+23", nil }, atofTest{"100000000000000008388608", "1.0000000000000001e+23", nil},
atofTest{ "100000000000000016777215", "1.0000000000000001e+23", nil }, atofTest{"100000000000000016777215", "1.0000000000000001e+23", nil},
atofTest{ "100000000000000016777216", "1.0000000000000003e+23", nil }, atofTest{"100000000000000016777216", "1.0000000000000003e+23", nil},
atofTest{ "-1", "-1", nil }, atofTest{"-1", "-1", nil},
atofTest{ "-0", "-0", nil }, atofTest{"-0", "-0", nil},
atofTest{ "1e-20", "1e-20", nil }, atofTest{"1e-20", "1e-20", nil},
atofTest{ "625e-3", "0.625", nil }, atofTest{"625e-3", "0.625", nil},
// largest float64 // largest float64
atofTest{ "1.7976931348623157e308", "1.7976931348623157e+308", nil }, atofTest{"1.7976931348623157e308", "1.7976931348623157e+308", nil},
atofTest{ "-1.7976931348623157e308", "-1.7976931348623157e+308", nil }, atofTest{"-1.7976931348623157e308", "-1.7976931348623157e+308", nil},
// next float64 - too large // next float64 - too large
atofTest{ "1.7976931348623159e308", "+Inf", os.ERANGE }, atofTest{"1.7976931348623159e308", "+Inf", os.ERANGE},
atofTest{ "-1.7976931348623159e308", "-Inf", os.ERANGE }, atofTest{"-1.7976931348623159e308", "-Inf", os.ERANGE},
// the border is ...158079 // the border is ...158079
// borderline - okay // borderline - okay
atofTest{ "1.7976931348623158e308", "1.7976931348623157e+308", nil }, atofTest{"1.7976931348623158e308", "1.7976931348623157e+308", nil},
atofTest{ "-1.7976931348623158e308", "-1.7976931348623157e+308", nil }, atofTest{"-1.7976931348623158e308", "-1.7976931348623157e+308", nil},
// borderline - too large // borderline - too large
atofTest{ "1.797693134862315808e308", "+Inf", os.ERANGE }, atofTest{"1.797693134862315808e308", "+Inf", os.ERANGE},
atofTest{ "-1.797693134862315808e308", "-Inf", os.ERANGE }, atofTest{"-1.797693134862315808e308", "-Inf", os.ERANGE},
// a little too large // a little too large
atofTest{ "1e308", "1e+308", nil }, atofTest{"1e308", "1e+308", nil},
atofTest{ "2e308", "+Inf", os.ERANGE }, atofTest{"2e308", "+Inf", os.ERANGE},
atofTest{ "1e309", "+Inf", os.ERANGE }, atofTest{"1e309", "+Inf", os.ERANGE},
// way too large // way too large
atofTest{ "1e310", "+Inf", os.ERANGE }, atofTest{"1e310", "+Inf", os.ERANGE},
atofTest{ "-1e310", "-Inf", os.ERANGE }, atofTest{"-1e310", "-Inf", os.ERANGE},
atofTest{ "1e400", "+Inf", os.ERANGE }, atofTest{"1e400", "+Inf", os.ERANGE},
atofTest{ "-1e400", "-Inf", os.ERANGE }, atofTest{"-1e400", "-Inf", os.ERANGE},
atofTest{ "1e400000", "+Inf", os.ERANGE }, atofTest{"1e400000", "+Inf", os.ERANGE},
atofTest{ "-1e400000", "-Inf", os.ERANGE }, atofTest{"-1e400000", "-Inf", os.ERANGE},
// denormalized // denormalized
atofTest{ "1e-305", "1e-305", nil }, atofTest{"1e-305", "1e-305", nil},
atofTest{ "1e-306", "1e-306", nil }, atofTest{"1e-306", "1e-306", nil},
atofTest{ "1e-307", "1e-307", nil }, atofTest{"1e-307", "1e-307", nil},
atofTest{ "1e-308", "1e-308", nil }, atofTest{"1e-308", "1e-308", nil},
atofTest{ "1e-309", "1e-309", nil }, atofTest{"1e-309", "1e-309", nil},
atofTest{ "1e-310", "1e-310", nil }, atofTest{"1e-310", "1e-310", nil},
atofTest{ "1e-322", "1e-322", nil }, atofTest{"1e-322", "1e-322", nil},
// smallest denormal // smallest denormal
atofTest{ "5e-324", "5e-324", nil }, atofTest{"5e-324", "5e-324", nil},
// too small // too small
atofTest{ "4e-324", "0", nil }, atofTest{"4e-324", "0", nil},
// way too small // way too small
atofTest{ "1e-350", "0", nil }, atofTest{"1e-350", "0", nil},
atofTest{ "1e-400000", "0", nil }, atofTest{"1e-400000", "0", nil},
// try to overflow exponent // try to overflow exponent
atofTest{ "1e-4294967296", "0", nil }, atofTest{"1e-4294967296", "0", nil},
atofTest{ "1e+4294967296", "+Inf", os.ERANGE }, atofTest{"1e+4294967296", "+Inf", os.ERANGE},
atofTest{ "1e-18446744073709551616", "0", nil }, atofTest{"1e-18446744073709551616", "0", nil},
atofTest{ "1e+18446744073709551616", "+Inf", os.ERANGE }, atofTest{"1e+18446744073709551616", "+Inf", os.ERANGE},
// Parse errors // Parse errors
atofTest{ "1e", "0", os.EINVAL }, atofTest{"1e", "0", os.EINVAL},
atofTest{ "1e-", "0", os.EINVAL }, atofTest{"1e-", "0", os.EINVAL},
atofTest{ ".e-1", "0", os.EINVAL }, atofTest{".e-1", "0", os.EINVAL},
} }
func init() { func init() {
...@@ -98,7 +98,7 @@ func init() { ...@@ -98,7 +98,7 @@ func init() {
for i := range atoftests { for i := range atoftests {
test := &atoftests[i]; test := &atoftests[i];
if test.err != nil { if test.err != nil {
test.err = &NumError{test.in, test.err} test.err = &NumError{test.in, test.err};
} }
} }
} }
......
...@@ -19,18 +19,19 @@ func (e *NumError) String() string { ...@@ -19,18 +19,19 @@ func (e *NumError) String() string {
func computeIntsize() uint { func computeIntsize() uint {
siz := uint(8); siz := uint(8);
for 1<<siz != 0 { for 1<<siz != 0 {
siz *= 2 siz *= 2;
} }
return siz return siz;
} }
var IntSize = computeIntsize();
var IntSize = computeIntsize()
// Return the first number n such that n*base >= 1<<64. // Return the first number n such that n*base >= 1<<64.
func cutoff64(base int) uint64 { func cutoff64(base int) uint64 {
if base < 2 { if base < 2 {
return 0; return 0;
} }
return (1<<64 - 1) / uint64(base) + 1; return (1<<64 - 1)/uint64(base) + 1;
} }
// Btoui64 interprets a string s in an arbitrary base b (2 to 36) // Btoui64 interprets a string s in an arbitrary base b (2 to 36)
...@@ -57,11 +58,11 @@ func Btoui64(s string, b int) (n uint64, err os.Error) { ...@@ -57,11 +58,11 @@ func Btoui64(s string, b int) (n uint64, err os.Error) {
var v byte; var v byte;
switch { switch {
case '0' <= s[i] && s[i] <= '9': case '0' <= s[i] && s[i] <= '9':
v = s[i] - '0'; v = s[i]-'0';
case 'a' <= s[i] && s[i] <= 'z': case 'a' <= s[i] && s[i] <= 'z':
v = s[i] - 'a' + 10; v = s[i]-'a'+10;
case 'A' <= s[i] && s[i] <= 'Z': case 'A' <= s[i] && s[i] <= 'Z':
v = s[i] - 'A' + 10; v = s[i]-'A'+10;
default: default:
n = 0; n = 0;
err = os.EINVAL; err = os.EINVAL;
...@@ -75,7 +76,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) { ...@@ -75,7 +76,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) {
if n >= cutoff { if n >= cutoff {
// n*b overflows // n*b overflows
n = 1<<64-1; n = 1<<64 - 1;
err = os.ERANGE; err = os.ERANGE;
goto Error; goto Error;
} }
...@@ -84,7 +85,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) { ...@@ -84,7 +85,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) {
n1 := n+uint64(v); n1 := n+uint64(v);
if n1 < n { if n1 < n {
// n+v overflows // n+v overflows
n = 1<<64-1; n = 1<<64 - 1;
err = os.ERANGE; err = os.ERANGE;
goto Error; goto Error;
} }
...@@ -107,7 +108,7 @@ Error: ...@@ -107,7 +108,7 @@ Error:
func Atoui64(s string) (n uint64, err os.Error) { func Atoui64(s string) (n uint64, err os.Error) {
// Empty string bad. // Empty string bad.
if len(s) == 0 { if len(s) == 0 {
return 0, &NumError{s, os.EINVAL} return 0, &NumError{s, os.EINVAL};
} }
// Look for octal, hex prefix. // Look for octal, hex prefix.
...@@ -132,17 +133,17 @@ func Atoui64(s string) (n uint64, err os.Error) { ...@@ -132,17 +133,17 @@ func Atoui64(s string) (n uint64, err os.Error) {
func Atoi64(s string) (i int64, err os.Error) { func Atoi64(s string) (i int64, err os.Error) {
// Empty string bad. // Empty string bad.
if len(s) == 0 { if len(s) == 0 {
return 0, &NumError{s, os.EINVAL} return 0, &NumError{s, os.EINVAL};
} }
// Pick off leading sign. // Pick off leading sign.
s0 := s; s0 := s;
neg := false; neg := false;
if s[0] == '+' { if s[0] == '+' {
s = s[1:len(s)] s = s[1:len(s)];
} else if s[0] == '-' { } else if s[0] == '-' {
neg = true; neg = true;
s = s[1:len(s)] s = s[1:len(s)];
} }
// Convert unsigned and check range. // Convert unsigned and check range.
...@@ -150,47 +151,46 @@ func Atoi64(s string) (i int64, err os.Error) { ...@@ -150,47 +151,46 @@ func Atoi64(s string) (i int64, err os.Error) {
un, err = Atoui64(s); un, err = Atoui64(s);
if err != nil && err.(*NumError).Error != os.ERANGE { if err != nil && err.(*NumError).Error != os.ERANGE {
err.(*NumError).Num = s0; err.(*NumError).Num = s0;
return 0, err return 0, err;
} }
if !neg && un >= 1<<63 { if !neg && un >= 1<<63 {
return 1<<63-1, &NumError{s0, os.ERANGE} return 1<<63 - 1, &NumError{s0, os.ERANGE};
} }
if neg && un > 1<<63 { if neg && un > 1<<63 {
return -1<<63, &NumError{s0, os.ERANGE} return -1 << 63, &NumError{s0, os.ERANGE};
} }
n := int64(un); n := int64(un);
if neg { if neg {
n = -n n = -n;
} }
return n, nil return n, nil;
} }
// Atoui is like Atoui64 but returns its result as a uint. // Atoui is like Atoui64 but returns its result as a uint.
func Atoui(s string) (i uint, err os.Error) { func Atoui(s string) (i uint, err os.Error) {
i1, e1 := Atoui64(s); i1, e1 := Atoui64(s);
if e1 != nil && e1.(*NumError).Error != os.ERANGE { if e1 != nil && e1.(*NumError).Error != os.ERANGE {
return 0, e1 return 0, e1;
} }
i = uint(i1); i = uint(i1);
if uint64(i) != i1 { if uint64(i) != i1 {
return ^uint(0), &NumError{s, os.ERANGE} return ^uint(0), &NumError{s, os.ERANGE};
} }
return i, nil return i, nil;
} }
// Atoi is like Atoi64 but returns its result as an int. // Atoi is like Atoi64 but returns its result as an int.
func Atoi(s string) (i int, err os.Error) { func Atoi(s string) (i int, err os.Error) {
i1, e1 := Atoi64(s); i1, e1 := Atoi64(s);
if e1 != nil && e1.(*NumError).Error != os.ERANGE { if e1 != nil && e1.(*NumError).Error != os.ERANGE {
return 0, e1 return 0, e1;
} }
i = int(i1); i = int(i1);
if int64(i) != i1 { if int64(i) != i1 {
if i1 < 0 { if i1 < 0 {
return -1<<(IntSize-1), &NumError{s, os.ERANGE} return -1 << (IntSize-1), &NumError{s, os.ERANGE};
} }
return 1<<(IntSize-1) - 1, &NumError{s, os.ERANGE} return 1<<(IntSize-1) - 1, &NumError{s, os.ERANGE};
} }
return i, nil return i, nil;
} }
...@@ -17,7 +17,7 @@ type atoui64Test struct { ...@@ -17,7 +17,7 @@ type atoui64Test struct {
err os.Error; err os.Error;
} }
var atoui64tests = []atoui64Test { var atoui64tests = []atoui64Test{
atoui64Test{"", 0, os.EINVAL}, atoui64Test{"", 0, os.EINVAL},
atoui64Test{"0", 0, nil}, atoui64Test{"0", 0, nil},
atoui64Test{"1", 1, nil}, atoui64Test{"1", 1, nil},
...@@ -27,14 +27,14 @@ var atoui64tests = []atoui64Test { ...@@ -27,14 +27,14 @@ var atoui64tests = []atoui64Test {
atoui64Test{"0X12345", 0x12345, nil}, atoui64Test{"0X12345", 0x12345, nil},
atoui64Test{"12345x", 0, os.EINVAL}, atoui64Test{"12345x", 0, os.EINVAL},
atoui64Test{"98765432100", 98765432100, nil}, atoui64Test{"98765432100", 98765432100, nil},
atoui64Test{"18446744073709551615", 1<<64-1, nil}, atoui64Test{"18446744073709551615", 1<<64 - 1, nil},
atoui64Test{"18446744073709551616", 1<<64-1, os.ERANGE}, atoui64Test{"18446744073709551616", 1<<64 - 1, os.ERANGE},
atoui64Test{"18446744073709551620", 1<<64-1, os.ERANGE}, atoui64Test{"18446744073709551620", 1<<64 - 1, os.ERANGE},
atoui64Test{"0xFFFFFFFFFFFFFFFF", 1<<64-1, nil}, atoui64Test{"0xFFFFFFFFFFFFFFFF", 1<<64 - 1, nil},
atoui64Test{"0x10000000000000000", 1<<64-1, os.ERANGE}, atoui64Test{"0x10000000000000000", 1<<64 - 1, os.ERANGE},
atoui64Test{"01777777777777777777777", 1<<64-1, nil}, atoui64Test{"01777777777777777777777", 1<<64 - 1, nil},
atoui64Test{"01777777777777777777778", 0, os.EINVAL}, atoui64Test{"01777777777777777777778", 0, os.EINVAL},
atoui64Test{"02000000000000000000000", 1<<64-1, os.ERANGE}, atoui64Test{"02000000000000000000000", 1<<64 - 1, os.ERANGE},
atoui64Test{"0200000000000000000000", 1<<61, nil}, atoui64Test{"0200000000000000000000", 1<<61, nil},
} }
...@@ -44,7 +44,7 @@ type atoi64Test struct { ...@@ -44,7 +44,7 @@ type atoi64Test struct {
err os.Error; err os.Error;
} }
var atoi64tests = []atoi64Test { var atoi64tests = []atoi64Test{
atoi64Test{"", 0, os.EINVAL}, atoi64Test{"", 0, os.EINVAL},
atoi64Test{"0", 0, nil}, atoi64Test{"0", 0, nil},
atoi64Test{"-0", 0, nil}, atoi64Test{"-0", 0, nil},
...@@ -60,12 +60,12 @@ var atoi64tests = []atoi64Test { ...@@ -60,12 +60,12 @@ var atoi64tests = []atoi64Test {
atoi64Test{"-12345x", 0, os.EINVAL}, atoi64Test{"-12345x", 0, os.EINVAL},
atoi64Test{"98765432100", 98765432100, nil}, atoi64Test{"98765432100", 98765432100, nil},
atoi64Test{"-98765432100", -98765432100, nil}, atoi64Test{"-98765432100", -98765432100, nil},
atoi64Test{"9223372036854775807", 1<<63-1, nil}, atoi64Test{"9223372036854775807", 1<<63 - 1, nil},
atoi64Test{"-9223372036854775807", -(1<<63-1), nil}, atoi64Test{"-9223372036854775807", -(1<<63 - 1), nil},
atoi64Test{"9223372036854775808", 1<<63-1, os.ERANGE}, atoi64Test{"9223372036854775808", 1<<63 - 1, os.ERANGE},
atoi64Test{"-9223372036854775808", -1<<63, nil}, atoi64Test{"-9223372036854775808", -1 << 63, nil},
atoi64Test{"9223372036854775809", 1<<63-1, os.ERANGE}, atoi64Test{"9223372036854775809", 1<<63 - 1, os.ERANGE},
atoi64Test{"-9223372036854775809", -1<<63, os.ERANGE}, atoi64Test{"-9223372036854775809", -1 << 63, os.ERANGE},
} }
type atoui32Test struct { type atoui32Test struct {
...@@ -74,7 +74,7 @@ type atoui32Test struct { ...@@ -74,7 +74,7 @@ type atoui32Test struct {
err os.Error; err os.Error;
} }
var atoui32tests = []atoui32Test { var atoui32tests = []atoui32Test{
atoui32Test{"", 0, os.EINVAL}, atoui32Test{"", 0, os.EINVAL},
atoui32Test{"0", 0, nil}, atoui32Test{"0", 0, nil},
atoui32Test{"1", 1, nil}, atoui32Test{"1", 1, nil},
...@@ -84,8 +84,8 @@ var atoui32tests = []atoui32Test { ...@@ -84,8 +84,8 @@ var atoui32tests = []atoui32Test {
atoui32Test{"0X12345", 0x12345, nil}, atoui32Test{"0X12345", 0x12345, nil},
atoui32Test{"12345x", 0, os.EINVAL}, atoui32Test{"12345x", 0, os.EINVAL},
atoui32Test{"987654321", 987654321, nil}, atoui32Test{"987654321", 987654321, nil},
atoui32Test{"4294967295", 1<<32-1, nil}, atoui32Test{"4294967295", 1<<32 - 1, nil},
atoui32Test{"4294967296", 1<<32-1, os.ERANGE}, atoui32Test{"4294967296", 1<<32 - 1, os.ERANGE},
} }
type atoi32Test struct { type atoi32Test struct {
...@@ -94,7 +94,7 @@ type atoi32Test struct { ...@@ -94,7 +94,7 @@ type atoi32Test struct {
err os.Error; err os.Error;
} }
var atoi32tests = []atoi32Test { var atoi32tests = []atoi32Test{
atoi32Test{"", 0, os.EINVAL}, atoi32Test{"", 0, os.EINVAL},
atoi32Test{"0", 0, nil}, atoi32Test{"0", 0, nil},
atoi32Test{"-0", 0, nil}, atoi32Test{"-0", 0, nil},
...@@ -110,12 +110,12 @@ var atoi32tests = []atoi32Test { ...@@ -110,12 +110,12 @@ var atoi32tests = []atoi32Test {
atoi32Test{"-12345x", 0, os.EINVAL}, atoi32Test{"-12345x", 0, os.EINVAL},
atoi32Test{"987654321", 987654321, nil}, atoi32Test{"987654321", 987654321, nil},
atoi32Test{"-987654321", -987654321, nil}, atoi32Test{"-987654321", -987654321, nil},
atoi32Test{"2147483647", 1<<31-1, nil}, atoi32Test{"2147483647", 1<<31 - 1, nil},
atoi32Test{"-2147483647", -(1<<31-1), nil}, atoi32Test{"-2147483647", -(1<<31 - 1), nil},
atoi32Test{"2147483648", 1<<31-1, os.ERANGE}, atoi32Test{"2147483648", 1<<31 - 1, os.ERANGE},
atoi32Test{"-2147483648", -1<<31, nil}, atoi32Test{"-2147483648", -1 << 31, nil},
atoi32Test{"2147483649", 1<<31-1, os.ERANGE}, atoi32Test{"2147483649", 1<<31 - 1, os.ERANGE},
atoi32Test{"-2147483649", -1<<31, os.ERANGE}, atoi32Test{"-2147483649", -1 << 31, os.ERANGE},
} }
func init() { func init() {
...@@ -124,25 +124,25 @@ func init() { ...@@ -124,25 +124,25 @@ func init() {
for i := range atoui64tests { for i := range atoui64tests {
test := &atoui64tests[i]; test := &atoui64tests[i];
if test.err != nil { if test.err != nil {
test.err = &NumError{test.in, test.err} test.err = &NumError{test.in, test.err};
} }
} }
for i := range atoi64tests { for i := range atoi64tests {
test := &atoi64tests[i]; test := &atoi64tests[i];
if test.err != nil { if test.err != nil {
test.err = &NumError{test.in, test.err} test.err = &NumError{test.in, test.err};
} }
} }
for i := range atoui32tests { for i := range atoui32tests {
test := &atoui32tests[i]; test := &atoui32tests[i];
if test.err != nil { if test.err != nil {
test.err = &NumError{test.in, test.err} test.err = &NumError{test.in, test.err};
} }
} }
for i := range atoi32tests { for i := range atoi32tests {
test := &atoi32tests[i]; test := &atoi32tests[i];
if test.err != nil { if test.err != nil {
test.err = &NumError{test.in, test.err} test.err = &NumError{test.in, test.err};
} }
} }
} }
...@@ -214,4 +214,3 @@ func TestAtoi(t *testing.T) { ...@@ -214,4 +214,3 @@ func TestAtoi(t *testing.T) {
} }
} }
} }
...@@ -15,17 +15,18 @@ type shiftTest struct { ...@@ -15,17 +15,18 @@ type shiftTest struct {
out string; out string;
} }
var shifttests = []shiftTest { var shifttests = []shiftTest{
shiftTest{ 0, -100, "0" }, shiftTest{0, -100, "0"},
shiftTest{ 0, 100, "0" }, shiftTest{0, 100, "0"},
shiftTest{ 1, 100, "1267650600228229401496703205376" }, shiftTest{1, 100, "1267650600228229401496703205376"},
shiftTest{ 1, -100, shiftTest{1, -100,
"0.00000000000000000000000000000078886090522101180541" "0.00000000000000000000000000000078886090522101180541"
"17285652827862296732064351090230047702789306640625" }, "17285652827862296732064351090230047702789306640625",
shiftTest{ 12345678, 8, "3160493568" }, },
shiftTest{ 12345678, -8, "48225.3046875" }, shiftTest{12345678, 8, "3160493568"},
shiftTest{ 195312, 9, "99999744" }, shiftTest{12345678, -8, "48225.3046875"},
shiftTest{ 1953125, 9, "1000000000" }, shiftTest{195312, 9, "99999744"},
shiftTest{1953125, 9, "1000000000"},
} }
func TestDecimalShift(t *testing.T) { func TestDecimalShift(t *testing.T) {
...@@ -46,22 +47,22 @@ type roundTest struct { ...@@ -46,22 +47,22 @@ type roundTest struct {
int uint64; int uint64;
} }
var roundtests = []roundTest { var roundtests = []roundTest{
roundTest{ 0, 4, "0", "0", "0", 0 }, roundTest{0, 4, "0", "0", "0", 0},
roundTest{ 12344999, 4, "12340000", "12340000", "12350000", 12340000 }, roundTest{12344999, 4, "12340000", "12340000", "12350000", 12340000},
roundTest{ 12345000, 4, "12340000", "12340000", "12350000", 12340000 }, roundTest{12345000, 4, "12340000", "12340000", "12350000", 12340000},
roundTest{ 12345001, 4, "12340000", "12350000", "12350000", 12350000 }, roundTest{12345001, 4, "12340000", "12350000", "12350000", 12350000},
roundTest{ 23454999, 4, "23450000", "23450000", "23460000", 23450000 }, roundTest{23454999, 4, "23450000", "23450000", "23460000", 23450000},
roundTest{ 23455000, 4, "23450000", "23460000", "23460000", 23460000 }, roundTest{23455000, 4, "23450000", "23460000", "23460000", 23460000},
roundTest{ 23455001, 4, "23450000", "23460000", "23460000", 23460000 }, roundTest{23455001, 4, "23450000", "23460000", "23460000", 23460000},
roundTest{ 99994999, 4, "99990000", "99990000", "100000000", 99990000 }, roundTest{99994999, 4, "99990000", "99990000", "100000000", 99990000},
roundTest{ 99995000, 4, "99990000", "100000000", "100000000", 100000000 }, roundTest{99995000, 4, "99990000", "100000000", "100000000", 100000000},
roundTest{ 99999999, 4, "99990000", "100000000", "100000000", 100000000 }, roundTest{99999999, 4, "99990000", "100000000", "100000000", 100000000},
roundTest{ 12994999, 4, "12990000", "12990000", "13000000", 12990000 }, roundTest{12994999, 4, "12990000", "12990000", "13000000", 12990000},
roundTest{ 12995000, 4, "12990000", "13000000", "13000000", 13000000 }, roundTest{12995000, 4, "12990000", "13000000", "13000000", 13000000},
roundTest{ 12999999, 4, "12990000", "13000000", "13000000", 13000000 }, roundTest{12999999, 4, "12990000", "13000000", "13000000", 13000000},
} }
func TestDecimalRound(t *testing.T) { func TestDecimalRound(t *testing.T) {
...@@ -91,17 +92,17 @@ type roundIntTest struct { ...@@ -91,17 +92,17 @@ type roundIntTest struct {
int uint64; int uint64;
} }
var roundinttests = []roundIntTest { var roundinttests = []roundIntTest{
roundIntTest{ 0, 100, 0 }, roundIntTest{0, 100, 0},
roundIntTest{ 512, -8, 2 }, roundIntTest{512, -8, 2},
roundIntTest{ 513, -8, 2 }, roundIntTest{513, -8, 2},
roundIntTest{ 640, -8, 2 }, roundIntTest{640, -8, 2},
roundIntTest{ 641, -8, 3 }, roundIntTest{641, -8, 3},
roundIntTest{ 384, -8, 2 }, roundIntTest{384, -8, 2},
roundIntTest{ 385, -8, 2 }, roundIntTest{385, -8, 2},
roundIntTest{ 383, -8, 1 }, roundIntTest{383, -8, 1},
roundIntTest{ 1, 100, 1<<64-1 }, roundIntTest{1, 100, 1<<64 - 1},
roundIntTest{ 1000, 0, 1000 }, roundIntTest{1000, 0, 1000},
} }
func TestDecimalRoundedInteger(t *testing.T) { func TestDecimalRoundedInteger(t *testing.T) {
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package strconv_test package strconv_test
import ( import (
"bufio"; "bufio";
"fmt"; "fmt";
...@@ -21,7 +22,7 @@ func pow2(i int) float64 { ...@@ -21,7 +22,7 @@ func pow2(i int) float64 {
case i == 1: case i == 1:
return 2; return 2;
} }
return pow2(i/2) * pow2(i-i/2); return pow2(i/2) * pow2(i - i/2);
} }
// Wrapper around strconv.Atof64. Handles dddddp+ddd (binary exponent) // Wrapper around strconv.Atof64. Handles dddddp+ddd (binary exponent)
...@@ -110,10 +111,10 @@ func TestFp(t *testing.T) { ...@@ -110,10 +111,10 @@ func TestFp(t *testing.T) {
if err2 != nil { if err2 != nil {
panicln("testfp: read testfp.txt:", err2.String()); panicln("testfp: read testfp.txt:", err2.String());
} }
line = line[0:len(line)-1]; line = line[0 : len(line)-1];
lineno++; lineno++;
if len(line) == 0 || line[0] == '#' { if len(line) == 0 || line[0] == '#' {
continue continue;
} }
a := strings.Split(line, " ", 0); a := strings.Split(line, " ", 0);
if len(a) != 4 { if len(a) != 4 {
......
...@@ -17,86 +17,88 @@ type ftoaTest struct { ...@@ -17,86 +17,88 @@ type ftoaTest struct {
s string; s string;
} }
func fdiv(a, b float64) float64 { return a / b } // keep compiler in the dark func fdiv(a, b float64) float64 {
return a/b;
} // keep compiler in the dark
const ( const (
below1e23 = 99999999999999974834176; below1e23 = 99999999999999974834176;
above1e23 = 100000000000000008388608; above1e23 = 100000000000000008388608;
) )
var ftoatests = []ftoaTest { var ftoatests = []ftoaTest{
ftoaTest{ 1, 'e', 5, "1.00000e+00" }, ftoaTest{1, 'e', 5, "1.00000e+00"},
ftoaTest{ 1, 'f', 5, "1.00000" }, ftoaTest{1, 'f', 5, "1.00000"},
ftoaTest{ 1, 'g', 5, "1" }, ftoaTest{1, 'g', 5, "1"},
ftoaTest{ 1, 'g', -1, "1" }, ftoaTest{1, 'g', -1, "1"},
ftoaTest{ 20, 'g', -1, "20" }, ftoaTest{20, 'g', -1, "20"},
ftoaTest{ 1234567.8, 'g', -1, "1.2345678e+06" }, ftoaTest{1234567.8, 'g', -1, "1.2345678e+06"},
ftoaTest{ 200000, 'g', -1, "200000" }, ftoaTest{200000, 'g', -1, "200000"},
ftoaTest{ 2000000, 'g', -1, "2e+06" }, ftoaTest{2000000, 'g', -1, "2e+06"},
ftoaTest{ 0, 'e', 5, "0.00000e+00" }, ftoaTest{0, 'e', 5, "0.00000e+00"},
ftoaTest{ 0, 'f', 5, "0.00000" }, ftoaTest{0, 'f', 5, "0.00000"},
ftoaTest{ 0, 'g', 5, "0" }, ftoaTest{0, 'g', 5, "0"},
ftoaTest{ 0, 'g', -1, "0" }, ftoaTest{0, 'g', -1, "0"},
ftoaTest{ -1, 'e', 5, "-1.00000e+00" }, ftoaTest{-1, 'e', 5, "-1.00000e+00"},
ftoaTest{ -1, 'f', 5, "-1.00000" }, ftoaTest{-1, 'f', 5, "-1.00000"},
ftoaTest{ -1, 'g', 5, "-1" }, ftoaTest{-1, 'g', 5, "-1"},
ftoaTest{ -1, 'g', -1, "-1" }, ftoaTest{-1, 'g', -1, "-1"},
ftoaTest{ 12, 'e', 5, "1.20000e+01" }, ftoaTest{12, 'e', 5, "1.20000e+01"},
ftoaTest{ 12, 'f', 5, "12.00000" }, ftoaTest{12, 'f', 5, "12.00000"},
ftoaTest{ 12, 'g', 5, "12" }, ftoaTest{12, 'g', 5, "12"},
ftoaTest{ 12, 'g', -1, "12" }, ftoaTest{12, 'g', -1, "12"},
ftoaTest{ 123456700, 'e', 5, "1.23457e+08" }, ftoaTest{123456700, 'e', 5, "1.23457e+08"},
ftoaTest{ 123456700, 'f', 5, "123456700.00000" }, ftoaTest{123456700, 'f', 5, "123456700.00000"},
ftoaTest{ 123456700, 'g', 5, "1.2346e+08" }, ftoaTest{123456700, 'g', 5, "1.2346e+08"},
ftoaTest{ 123456700, 'g', -1, "1.234567e+08" }, ftoaTest{123456700, 'g', -1, "1.234567e+08"},
ftoaTest{ 1.2345e6, 'e', 5, "1.23450e+06" }, ftoaTest{1.2345e6, 'e', 5, "1.23450e+06"},
ftoaTest{ 1.2345e6, 'f', 5, "1234500.00000" }, ftoaTest{1.2345e6, 'f', 5, "1234500.00000"},
ftoaTest{ 1.2345e6, 'g', 5, "1.2345e+06" }, ftoaTest{1.2345e6, 'g', 5, "1.2345e+06"},
ftoaTest{ 1e23, 'e', 17, "9.99999999999999916e+22" }, ftoaTest{1e23, 'e', 17, "9.99999999999999916e+22"},
ftoaTest{ 1e23, 'f', 17, "99999999999999991611392.00000000000000000" }, ftoaTest{1e23, 'f', 17, "99999999999999991611392.00000000000000000"},
ftoaTest{ 1e23, 'g', 17, "9.9999999999999992e+22" }, ftoaTest{1e23, 'g', 17, "9.9999999999999992e+22"},
ftoaTest{ 1e23, 'e', -1, "1e+23" }, ftoaTest{1e23, 'e', -1, "1e+23"},
ftoaTest{ 1e23, 'f', -1, "100000000000000000000000" }, ftoaTest{1e23, 'f', -1, "100000000000000000000000"},
ftoaTest{ 1e23, 'g', -1, "1e+23" }, ftoaTest{1e23, 'g', -1, "1e+23"},
ftoaTest{ below1e23, 'e', 17, "9.99999999999999748e+22" }, ftoaTest{below1e23, 'e', 17, "9.99999999999999748e+22"},
ftoaTest{ below1e23, 'f', 17, "99999999999999974834176.00000000000000000" }, ftoaTest{below1e23, 'f', 17, "99999999999999974834176.00000000000000000"},
ftoaTest{ below1e23, 'g', 17, "9.9999999999999975e+22" }, ftoaTest{below1e23, 'g', 17, "9.9999999999999975e+22"},
ftoaTest{ below1e23, 'e', -1, "9.999999999999997e+22" }, ftoaTest{below1e23, 'e', -1, "9.999999999999997e+22"},
ftoaTest{ below1e23, 'f', -1, "99999999999999970000000" }, ftoaTest{below1e23, 'f', -1, "99999999999999970000000"},
ftoaTest{ below1e23, 'g', -1, "9.999999999999997e+22" }, ftoaTest{below1e23, 'g', -1, "9.999999999999997e+22"},
ftoaTest{ above1e23, 'e', 17, "1.00000000000000008e+23" }, ftoaTest{above1e23, 'e', 17, "1.00000000000000008e+23"},
ftoaTest{ above1e23, 'f', 17, "100000000000000008388608.00000000000000000" }, ftoaTest{above1e23, 'f', 17, "100000000000000008388608.00000000000000000"},
ftoaTest{ above1e23, 'g', 17, "1.0000000000000001e+23" }, ftoaTest{above1e23, 'g', 17, "1.0000000000000001e+23"},
ftoaTest{ above1e23, 'e', -1, "1.0000000000000001e+23" }, ftoaTest{above1e23, 'e', -1, "1.0000000000000001e+23"},
ftoaTest{ above1e23, 'f', -1, "100000000000000010000000" }, ftoaTest{above1e23, 'f', -1, "100000000000000010000000"},
ftoaTest{ above1e23, 'g', -1, "1.0000000000000001e+23" }, ftoaTest{above1e23, 'g', -1, "1.0000000000000001e+23"},
ftoaTest{ fdiv(5e-304, 1e20), 'g', -1, "5e-324" }, ftoaTest{fdiv(5e-304, 1e20), 'g', -1, "5e-324"},
ftoaTest{ fdiv(-5e-304, 1e20), 'g', -1, "-5e-324" }, ftoaTest{fdiv(-5e-304, 1e20), 'g', -1, "-5e-324"},
ftoaTest{ 32, 'g', -1, "32" }, ftoaTest{32, 'g', -1, "32"},
ftoaTest{ 32, 'g', 0, "3e+01" }, ftoaTest{32, 'g', 0, "3e+01"},
ftoaTest{ 100, 'x', -1, "%x" }, ftoaTest{100, 'x', -1, "%x"},
ftoaTest{ math.NaN(), 'g', -1, "NaN" }, ftoaTest{math.NaN(), 'g', -1, "NaN"},
ftoaTest{ -math.NaN(), 'g', -1, "NaN" }, ftoaTest{-math.NaN(), 'g', -1, "NaN"},
ftoaTest{ math.Inf(0), 'g', -1, "+Inf" }, ftoaTest{math.Inf(0), 'g', -1, "+Inf"},
ftoaTest{ math.Inf(-1), 'g', -1, "-Inf" }, ftoaTest{math.Inf(-1), 'g', -1, "-Inf"},
ftoaTest{ -math.Inf(0), 'g', -1, "-Inf" }, ftoaTest{-math.Inf(0), 'g', -1, "-Inf"},
ftoaTest{ -1, 'b', -1, "-4503599627370496p-52" }, ftoaTest{-1, 'b', -1, "-4503599627370496p-52"},
} }
func TestFtoa(t *testing.T) { func TestFtoa(t *testing.T) {
......
...@@ -15,4 +15,3 @@ func SetOptimize(b bool) bool { ...@@ -15,4 +15,3 @@ func SetOptimize(b bool) bool {
optimize = b; optimize = b;
return old; return old;
} }
...@@ -7,7 +7,7 @@ package strconv ...@@ -7,7 +7,7 @@ package strconv
// Uitob64 returns the string representation of i in the given base. // Uitob64 returns the string representation of i in the given base.
func Uitob64(u uint64, base uint) string { func Uitob64(u uint64, base uint) string {
if u == 0 { if u == 0 {
return "0" return "0";
} }
// Assemble decimal in reverse order. // Assemble decimal in reverse order.
...@@ -20,13 +20,13 @@ func Uitob64(u uint64, base uint) string { ...@@ -20,13 +20,13 @@ func Uitob64(u uint64, base uint) string {
u /= b; u /= b;
} }
return string(buf[j:len(buf)]) return string(buf[j:len(buf)]);
} }
// Itob64 returns the string representation of i in the given base. // Itob64 returns the string representation of i in the given base.
func Itob64(i int64, base uint) string { func Itob64(i int64, base uint) string {
if i == 0 { if i == 0 {
return "0" return "0";
} }
if i < 0 { if i < 0 {
......
...@@ -15,46 +15,46 @@ type itob64Test struct { ...@@ -15,46 +15,46 @@ type itob64Test struct {
out string; out string;
} }
var itob64tests = []itob64Test { var itob64tests = []itob64Test{
itob64Test{ 0, 10, "0" }, itob64Test{0, 10, "0"},
itob64Test{ 1, 10, "1" }, itob64Test{1, 10, "1"},
itob64Test{ -1, 10, "-1" }, itob64Test{-1, 10, "-1"},
itob64Test{ 12345678, 10, "12345678" }, itob64Test{12345678, 10, "12345678"},
itob64Test{ -987654321, 10, "-987654321" }, itob64Test{-987654321, 10, "-987654321"},
itob64Test{ 1<<31-1, 10, "2147483647" }, itob64Test{1<<31 - 1, 10, "2147483647"},
itob64Test{ -1<<31+1, 10, "-2147483647" }, itob64Test{-1 << 31 + 1, 10, "-2147483647"},
itob64Test{ 1<<31, 10, "2147483648" }, itob64Test{1<<31, 10, "2147483648"},
itob64Test{ -1<<31, 10, "-2147483648" }, itob64Test{-1 << 31, 10, "-2147483648"},
itob64Test{ 1<<31+1, 10, "2147483649" }, itob64Test{1<<31 + 1, 10, "2147483649"},
itob64Test{ -1<<31-1, 10, "-2147483649" }, itob64Test{-1 << 31 - 1, 10, "-2147483649"},
itob64Test{ 1<<32-1, 10, "4294967295" }, itob64Test{1<<32 - 1, 10, "4294967295"},
itob64Test{ -1<<32+1, 10, "-4294967295" }, itob64Test{-1 << 32 + 1, 10, "-4294967295"},
itob64Test{ 1<<32, 10, "4294967296" }, itob64Test{1<<32, 10, "4294967296"},
itob64Test{ -1<<32, 10, "-4294967296" }, itob64Test{-1 << 32, 10, "-4294967296"},
itob64Test{ 1<<32+1, 10, "4294967297" }, itob64Test{1<<32 + 1, 10, "4294967297"},
itob64Test{ -1<<32-1, 10, "-4294967297" }, itob64Test{-1 << 32 - 1, 10, "-4294967297"},
itob64Test{ 1<<50, 10, "1125899906842624" }, itob64Test{1<<50, 10, "1125899906842624"},
itob64Test{ 1<<63-1, 10, "9223372036854775807" }, itob64Test{1<<63 - 1, 10, "9223372036854775807"},
itob64Test{ -1<<63+1, 10, "-9223372036854775807" }, itob64Test{-1 << 63 + 1, 10, "-9223372036854775807"},
itob64Test{ -1<<63, 10, "-9223372036854775808" }, itob64Test{-1 << 63, 10, "-9223372036854775808"},
itob64Test{ 0, 2, "0" }, itob64Test{0, 2, "0"},
itob64Test{ 10, 2, "1010" }, itob64Test{10, 2, "1010"},
itob64Test{ -1, 2, "-1" }, itob64Test{-1, 2, "-1"},
itob64Test{ 1<<15, 2, "1000000000000000" }, itob64Test{1<<15, 2, "1000000000000000"},
itob64Test{ -8, 8, "-10" }, itob64Test{-8, 8, "-10"},
itob64Test{ 057635436545, 8, "57635436545" }, itob64Test{057635436545, 8, "57635436545"},
itob64Test{ 1<<24, 8, "100000000" }, itob64Test{1<<24, 8, "100000000"},
itob64Test{ 16, 16, "10" }, itob64Test{16, 16, "10"},
itob64Test{ -0x123456789abcdef, 16, "-123456789abcdef" }, itob64Test{-0x123456789abcdef, 16, "-123456789abcdef"},
itob64Test{ 1<<63-1, 16, "7fffffffffffffff" }, itob64Test{1<<63 - 1, 16, "7fffffffffffffff"},
itob64Test{ 16, 17, "g" }, itob64Test{16, 17, "g"},
itob64Test{ 25, 25, "10" }, itob64Test{25, 25, "10"},
itob64Test{ (((((17*35+24)*35+21)*35+34)*35+12)*35+24)*35+32, 35, "holycow" }, itob64Test{(((((17*35 + 24)*35 + 21)*35 + 34)*35 + 12)*35 + 24)*35 + 32, 35, "holycow"},
itob64Test{ (((((17*36+24)*36+21)*36+34)*36+12)*36+24)*36+32, 36, "holycow" }, itob64Test{(((((17*36 + 24)*36 + 21)*36 + 34)*36 + 12)*36 + 24)*36 + 32, 36, "holycow"},
} }
func TestItoa(t *testing.T) { func TestItoa(t *testing.T) {
...@@ -129,12 +129,12 @@ type uitob64Test struct { ...@@ -129,12 +129,12 @@ type uitob64Test struct {
out string; out string;
} }
var uitob64tests = []uitob64Test { var uitob64tests = []uitob64Test{
uitob64Test{ 1<<63-1, 10, "9223372036854775807" }, uitob64Test{1<<63 - 1, 10, "9223372036854775807"},
uitob64Test{ 1<<63, 10, "9223372036854775808" }, uitob64Test{1<<63, 10, "9223372036854775808"},
uitob64Test{ 1<<63+1, 10, "9223372036854775809" }, uitob64Test{1<<63 + 1, 10, "9223372036854775809"},
uitob64Test{ 1<<64-2, 10, "18446744073709551614" }, uitob64Test{1<<64 - 2, 10, "18446744073709551614"},
uitob64Test{ 1<<64-1, 10, "18446744073709551615" }, uitob64Test{1<<64 - 1, 10, "18446744073709551615"},
} }
func TestUitoa(t *testing.T) { func TestUitoa(t *testing.T) {
......
...@@ -43,23 +43,23 @@ func Quote(s string) string { ...@@ -43,23 +43,23 @@ func Quote(s string) string {
t += `\v`; t += `\v`;
case c < utf8.RuneSelf: case c < utf8.RuneSelf:
t += `\x` + string(lowerhex[c>>4]) + string(lowerhex[c&0xF]); t += `\x`+string(lowerhex[c>>4])+string(lowerhex[c&0xF]);
case utf8.FullRuneInString(s): case utf8.FullRuneInString(s):
r, size := utf8.DecodeRuneInString(s); r, size := utf8.DecodeRuneInString(s);
if r == utf8.RuneError && size == 1 { if r == utf8.RuneError && size == 1 {
goto EscX; goto EscX;
} }
s = s[size-1:len(s)]; // next iteration will slice off 1 more s = s[size-1 : len(s)]; // next iteration will slice off 1 more
if r < 0x10000 { if r < 0x10000 {
t += `\u`; t += `\u`;
for j:=uint(0); j<4; j++ { for j := uint(0); j < 4; j++ {
t += string(lowerhex[(r>>(12-4*j))&0xF]); t += string(lowerhex[(r>>(12 - 4*j))&0xF]);
} }
} else { } else {
t += `\U`; t += `\U`;
for j:=uint(0); j<8; j++ { for j := uint(0); j < 8; j++ {
t += string(lowerhex[(r>>(28-4*j))&0xF]); t += string(lowerhex[(r>>(28 - 4*j))&0xF]);
} }
} }
...@@ -89,11 +89,11 @@ func unhex(b byte) (v int, ok bool) { ...@@ -89,11 +89,11 @@ func unhex(b byte) (v int, ok bool) {
c := int(b); c := int(b);
switch { switch {
case '0' <= c && c <= '9': case '0' <= c && c <= '9':
return c - '0', true; return c-'0', true;
case 'a' <= c && c <= 'f': case 'a' <= c && c <= 'f':
return c - 'a' + 10, true; return c-'a'+10, true;
case 'A' <= c && c <= 'F': case 'A' <= c && c <= 'F':
return c - 'A' + 10, true; return c-'A'+10, true;
} }
return; return;
} }
...@@ -183,17 +183,17 @@ func UnquoteChar(s string, quote byte) (value int, multibyte bool, tail string, ...@@ -183,17 +183,17 @@ func UnquoteChar(s string, quote byte) (value int, multibyte bool, tail string,
value = v; value = v;
multibyte = true; multibyte = true;
case '0', '1', '2', '3', '4', '5', '6', '7': case '0', '1', '2', '3', '4', '5', '6', '7':
v := int(c) - '0'; v := int(c)-'0';
if len(s) < 2 { if len(s) < 2 {
err = os.EINVAL; err = os.EINVAL;
return; return;
} }
for j := 0; j < 2; j++ { // one digit already; two more for j := 0; j < 2; j++ { // one digit already; two more
x := int(s[j]) - '0'; x := int(s[j])-'0';
if x < 0 || x > 7 { if x < 0 || x > 7 {
return; return;
} }
v = (v<<3) | x; v = (v<<3)|x;
} }
s = s[2:len(s)]; s = s[2:len(s)];
if v > 255 { if v > 255 {
...@@ -232,7 +232,7 @@ func Unquote(s string) (t string, err os.Error) { ...@@ -232,7 +232,7 @@ func Unquote(s string) (t string, err os.Error) {
if quote != s[n-1] { if quote != s[n-1] {
return; return;
} }
s = s[1:n-1]; s = s[1 : n-1];
if quote == '`' { if quote == '`' {
return s, nil; return s, nil;
...@@ -260,5 +260,5 @@ func Unquote(s string) (t string, err os.Error) { ...@@ -260,5 +260,5 @@ func Unquote(s string) (t string, err os.Error) {
return; return;
} }
} }
return tt, nil return tt, nil;
} }
...@@ -15,13 +15,13 @@ type quoteTest struct { ...@@ -15,13 +15,13 @@ type quoteTest struct {
out string; out string;
} }
var quotetests = []quoteTest { var quotetests = []quoteTest{
quoteTest{ "\a\b\f\r\n\t\v", `"\a\b\f\r\n\t\v"` }, quoteTest{"\a\b\f\r\n\t\v", `"\a\b\f\r\n\t\v"`},
quoteTest{ "\\", `"\\"` }, quoteTest{"\\", `"\\"`},
quoteTest{ "abc\xffdef", `"abc\xffdef"` }, quoteTest{"abc\xffdef", `"abc\xffdef"`},
quoteTest{ "\u263a", `"\u263a"` }, quoteTest{"\u263a", `"\u263a"`},
quoteTest{ "\U0010ffff", `"\U0010ffff"` }, quoteTest{"\U0010ffff", `"\U0010ffff"`},
quoteTest{ "\x04", `"\x04"` }, quoteTest{"\x04", `"\x04"`},
} }
func TestQuote(t *testing.T) { func TestQuote(t *testing.T) {
...@@ -38,45 +38,45 @@ type canBackquoteTest struct { ...@@ -38,45 +38,45 @@ type canBackquoteTest struct {
out bool; out bool;
} }
var canbackquotetests = []canBackquoteTest { var canbackquotetests = []canBackquoteTest{
canBackquoteTest{ "`", false }, canBackquoteTest{"`", false},
canBackquoteTest{ string(0), false }, canBackquoteTest{string(0), false},
canBackquoteTest{ string(1), false }, canBackquoteTest{string(1), false},
canBackquoteTest{ string(2), false }, canBackquoteTest{string(2), false},
canBackquoteTest{ string(3), false }, canBackquoteTest{string(3), false},
canBackquoteTest{ string(4), false }, canBackquoteTest{string(4), false},
canBackquoteTest{ string(5), false }, canBackquoteTest{string(5), false},
canBackquoteTest{ string(6), false }, canBackquoteTest{string(6), false},
canBackquoteTest{ string(7), false }, canBackquoteTest{string(7), false},
canBackquoteTest{ string(8), false }, canBackquoteTest{string(8), false},
canBackquoteTest{ string(9), true }, // \t canBackquoteTest{string(9), true}, // \t
canBackquoteTest{ string(10), false }, canBackquoteTest{string(10), false},
canBackquoteTest{ string(11), false }, canBackquoteTest{string(11), false},
canBackquoteTest{ string(12), false }, canBackquoteTest{string(12), false},
canBackquoteTest{ string(13), false }, canBackquoteTest{string(13), false},
canBackquoteTest{ string(14), false }, canBackquoteTest{string(14), false},
canBackquoteTest{ string(15), false }, canBackquoteTest{string(15), false},
canBackquoteTest{ string(16), false }, canBackquoteTest{string(16), false},
canBackquoteTest{ string(17), false }, canBackquoteTest{string(17), false},
canBackquoteTest{ string(18), false }, canBackquoteTest{string(18), false},
canBackquoteTest{ string(19), false }, canBackquoteTest{string(19), false},
canBackquoteTest{ string(20), false }, canBackquoteTest{string(20), false},
canBackquoteTest{ string(21), false }, canBackquoteTest{string(21), false},
canBackquoteTest{ string(22), false }, canBackquoteTest{string(22), false},
canBackquoteTest{ string(23), false }, canBackquoteTest{string(23), false},
canBackquoteTest{ string(24), false }, canBackquoteTest{string(24), false},
canBackquoteTest{ string(25), false }, canBackquoteTest{string(25), false},
canBackquoteTest{ string(26), false }, canBackquoteTest{string(26), false},
canBackquoteTest{ string(27), false }, canBackquoteTest{string(27), false},
canBackquoteTest{ string(28), false }, canBackquoteTest{string(28), false},
canBackquoteTest{ string(29), false }, canBackquoteTest{string(29), false},
canBackquoteTest{ string(30), false }, canBackquoteTest{string(30), false},
canBackquoteTest{ string(31), false }, canBackquoteTest{string(31), false},
canBackquoteTest{ `' !"#$%&'()*+,-./:;<=>?@[\]^_{|}~`, true }, canBackquoteTest{`' !"#$%&'()*+,-./:;<=>?@[\]^_{|}~`, true},
canBackquoteTest{ `0123456789`, true }, canBackquoteTest{`0123456789`, true},
canBackquoteTest{ `ABCDEFGHIJKLMNOPQRSTUVWXYZ`, true }, canBackquoteTest{`ABCDEFGHIJKLMNOPQRSTUVWXYZ`, true},
canBackquoteTest{ `abcdefghijklmnopqrstuvwxyz`, true }, canBackquoteTest{`abcdefghijklmnopqrstuvwxyz`, true},
canBackquoteTest{ `☺`, true }, canBackquoteTest{`☺`, true},
} }
func TestCanBackquote(t *testing.T) { func TestCanBackquote(t *testing.T) {
...@@ -88,45 +88,45 @@ func TestCanBackquote(t *testing.T) { ...@@ -88,45 +88,45 @@ func TestCanBackquote(t *testing.T) {
} }
} }
var unquotetests = []quoteTest { var unquotetests = []quoteTest{
quoteTest{ `""`, "" }, quoteTest{`""`, ""},
quoteTest{ `"a"`, "a" }, quoteTest{`"a"`, "a"},
quoteTest{ `"abc"`, "abc" }, quoteTest{`"abc"`, "abc"},
quoteTest{ `"☺"`, "☺" }, quoteTest{`"☺"`, "☺"},
quoteTest{ `"hello world"`, "hello world" }, quoteTest{`"hello world"`, "hello world"},
quoteTest{ `"\xFF"`, "\xFF" }, quoteTest{`"\xFF"`, "\xFF"},
quoteTest{ `"\377"`, "\377" }, quoteTest{`"\377"`, "\377"},
quoteTest{ `"\u1234"`, "\u1234" }, quoteTest{`"\u1234"`, "\u1234"},
quoteTest{ `"\U00010111"`, "\U00010111" }, quoteTest{`"\U00010111"`, "\U00010111"},
quoteTest{ `"\U0001011111"`, "\U0001011111" }, quoteTest{`"\U0001011111"`, "\U0001011111"},
quoteTest{ `"\a\b\f\n\r\t\v\\\""`, "\a\b\f\n\r\t\v\\\"" }, quoteTest{`"\a\b\f\n\r\t\v\\\""`, "\a\b\f\n\r\t\v\\\""},
quoteTest{ `"'"`, "'" }, quoteTest{`"'"`, "'"},
quoteTest{ `'a'`, "a" }, quoteTest{`'a'`, "a"},
quoteTest{ `'☹'`, "☹" }, quoteTest{`'☹'`, "☹"},
quoteTest{ `'\a'`, "\a" }, quoteTest{`'\a'`, "\a"},
quoteTest{ `'\x10'`, "\x10" }, quoteTest{`'\x10'`, "\x10"},
quoteTest{ `'\377'`, "\377" }, quoteTest{`'\377'`, "\377"},
quoteTest{ `'\u1234'`, "\u1234" }, quoteTest{`'\u1234'`, "\u1234"},
quoteTest{ `'\U00010111'`, "\U00010111" }, quoteTest{`'\U00010111'`, "\U00010111"},
quoteTest{ `'\t'`, "\t" }, quoteTest{`'\t'`, "\t"},
quoteTest{ `' '`, " " }, quoteTest{`' '`, " "},
quoteTest{ `'\''`, "'" }, quoteTest{`'\''`, "'"},
quoteTest{ `'"'`, "\"" }, quoteTest{`'"'`, "\""},
quoteTest{ "``", `` }, quoteTest{"``", ``},
quoteTest{ "`a`", `a` }, quoteTest{"`a`", `a`},
quoteTest{ "`abc`", `abc` }, quoteTest{"`abc`", `abc`},
quoteTest{ "`☺`", `☺` }, quoteTest{"`☺`", `☺`},
quoteTest{ "`hello world`", `hello world` }, quoteTest{"`hello world`", `hello world`},
quoteTest{ "`\\xFF`", `\xFF` }, quoteTest{"`\\xFF`", `\xFF`},
quoteTest{ "`\\377`", `\377` }, quoteTest{"`\\377`", `\377`},
quoteTest{ "`\\`", `\` }, quoteTest{"`\\`", `\`},
quoteTest{ "` `", ` ` }, quoteTest{"` `", ` `},
quoteTest{ "` `", ` ` }, quoteTest{"` `", ` `},
} }
var misquoted = []string { var misquoted = []string{
``, ``,
`"`, `"`,
`"a`, `"a`,
......
...@@ -23,10 +23,10 @@ func eq(a, b []string) bool { ...@@ -23,10 +23,10 @@ func eq(a, b []string) bool {
return true; return true;
} }
var abcd = "abcd"; var abcd = "abcd"
var faces = "☺☻☹"; var faces = "☺☻☹"
var commas = "1,2,3,4"; var commas = "1,2,3,4"
var dots = "1....2....3....4"; var dots = "1....2....3....4"
type IndexTest struct { type IndexTest struct {
s string; s string;
...@@ -34,7 +34,7 @@ type IndexTest struct { ...@@ -34,7 +34,7 @@ type IndexTest struct {
out int; out int;
} }
var indexTests = []IndexTest { var indexTests = []IndexTest{
IndexTest{"", "", 0}, IndexTest{"", "", 0},
IndexTest{"", "a", -1}, IndexTest{"", "a", -1},
IndexTest{"", "foo", -1}, IndexTest{"", "foo", -1},
...@@ -48,7 +48,7 @@ var indexTests = []IndexTest { ...@@ -48,7 +48,7 @@ var indexTests = []IndexTest {
IndexTest{"abcABCabc", "A", 3}, IndexTest{"abcABCabc", "A", 3},
} }
var lastIndexTests = []IndexTest { var lastIndexTests = []IndexTest{
IndexTest{"", "", 0}, IndexTest{"", "", 0},
IndexTest{"", "a", -1}, IndexTest{"", "a", -1},
IndexTest{"", "foo", -1}, IndexTest{"", "foo", -1},
...@@ -88,11 +88,13 @@ type ExplodeTest struct { ...@@ -88,11 +88,13 @@ type ExplodeTest struct {
n int; n int;
a []string; a []string;
} }
var explodetests = []ExplodeTest {
ExplodeTest{ abcd, 4, []string{"a", "b", "c", "d"} }, var explodetests = []ExplodeTest{
ExplodeTest{ faces, 3, []string{"☺", "☻", "☹"} }, ExplodeTest{abcd, 4, []string{"a", "b", "c", "d"}},
ExplodeTest{ abcd, 2, []string{"a", "bcd"} }, ExplodeTest{faces, 3, []string{"☺", "☻", "☹"}},
ExplodeTest{abcd, 2, []string{"a", "bcd"}},
} }
func TestExplode(t *testing.T) { func TestExplode(t *testing.T) {
for _, tt := range explodetests { for _, tt := range explodetests {
a := Split(tt.s, "", tt.n); a := Split(tt.s, "", tt.n);
...@@ -113,20 +115,22 @@ type SplitTest struct { ...@@ -113,20 +115,22 @@ type SplitTest struct {
n int; n int;
a []string; a []string;
} }
var splittests = []SplitTest {
SplitTest{ abcd, "a", 0, []string{"", "bcd"} }, var splittests = []SplitTest{
SplitTest{ abcd, "z", 0, []string{"abcd"} }, SplitTest{abcd, "a", 0, []string{"", "bcd"}},
SplitTest{ abcd, "", 0, []string{"a", "b", "c", "d"} }, SplitTest{abcd, "z", 0, []string{"abcd"}},
SplitTest{ commas, ",", 0, []string{"1", "2", "3", "4"} }, SplitTest{abcd, "", 0, []string{"a", "b", "c", "d"}},
SplitTest{ dots, "...", 0, []string{"1", ".2", ".3", ".4"} }, SplitTest{commas, ",", 0, []string{"1", "2", "3", "4"}},
SplitTest{ faces, "☹", 0, []string{"☺☻", ""} }, SplitTest{dots, "...", 0, []string{"1", ".2", ".3", ".4"}},
SplitTest{ faces, "~", 0, []string{faces} }, SplitTest{faces, "☹", 0, []string{"☺☻", ""}},
SplitTest{ faces, "", 0, []string{"☺", "☻", "☹"} }, SplitTest{faces, "~", 0, []string{faces}},
SplitTest{ "1 2 3 4", " ", 3, []string{"1", "2", "3 4"} }, SplitTest{faces, "", 0, []string{"☺", "☻", "☹"}},
SplitTest{ "1 2", " ", 3, []string{"1", "2"} }, SplitTest{"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
SplitTest{ "123", "", 2, []string{"1", "23"} }, SplitTest{"1 2", " ", 3, []string{"1", "2"}},
SplitTest{ "123", "", 17, []string{"1", "2", "3"} }, SplitTest{"123", "", 2, []string{"1", "23"}},
SplitTest{"123", "", 17, []string{"1", "2", "3"}},
} }
func TestSplit(t *testing.T) { func TestSplit(t *testing.T) {
for _, tt := range splittests { for _, tt := range splittests {
a := Split(tt.s, tt.sep, tt.n); a := Split(tt.s, tt.sep, tt.n);
...@@ -157,7 +161,7 @@ func runStringTests(t *testing.T, f func(string) string, funcName string, testCa ...@@ -157,7 +161,7 @@ func runStringTests(t *testing.T, f func(string) string, funcName string, testCa
} }
} }
var upperTests = []StringTest { var upperTests = []StringTest{
StringTest{"", ""}, StringTest{"", ""},
StringTest{"abc", "ABC"}, StringTest{"abc", "ABC"},
StringTest{"AbC123", "ABC123"}, StringTest{"AbC123", "ABC123"},
...@@ -165,7 +169,7 @@ var upperTests = []StringTest { ...@@ -165,7 +169,7 @@ var upperTests = []StringTest {
StringTest{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char StringTest{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char
} }
var lowerTests = []StringTest { var lowerTests = []StringTest{
StringTest{"", ""}, StringTest{"", ""},
StringTest{"abc", "abc"}, StringTest{"abc", "abc"},
StringTest{"AbC123", "abc123"}, StringTest{"AbC123", "abc123"},
...@@ -175,10 +179,10 @@ var lowerTests = []StringTest { ...@@ -175,10 +179,10 @@ var lowerTests = []StringTest {
const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000" const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
var trimSpaceTests = []StringTest { var trimSpaceTests = []StringTest{
StringTest{"", ""}, StringTest{"", ""},
StringTest{"abc", "abc"}, StringTest{"abc", "abc"},
StringTest{space + "abc" + space, "abc"}, StringTest{space+"abc"+space, "abc"},
StringTest{" ", ""}, StringTest{" ", ""},
StringTest{" \t\r\n \t\t\r\r\n\n ", ""}, StringTest{" \t\r\n \t\t\r\r\n\n ", ""},
StringTest{" \t\r\n x\t\t\r\r\n\n ", "x"}, StringTest{" \t\r\n x\t\t\r\r\n\n ", "x"},
...@@ -191,23 +195,27 @@ var trimSpaceTests = []StringTest { ...@@ -191,23 +195,27 @@ var trimSpaceTests = []StringTest {
func tenRunes(rune int) string { func tenRunes(rune int) string {
r := make([]int, 10); r := make([]int, 10);
for i := range r { for i := range r {
r[i] = rune r[i] = rune;
} }
return string(r) return string(r);
} }
func TestMap(t *testing.T) { func TestMap(t *testing.T) {
// Run a couple of awful growth/shrinkage tests // Run a couple of awful growth/shrinkage tests
a := tenRunes('a'); a := tenRunes('a');
// 1. Grow. This triggers two reallocations in Map. // 1. Grow. This triggers two reallocations in Map.
maxRune := func(rune int) int { return unicode.MaxRune }; maxRune := func(rune int) int {
return unicode.MaxRune;
};
m := Map(maxRune, a); m := Map(maxRune, a);
expect := tenRunes(unicode.MaxRune); expect := tenRunes(unicode.MaxRune);
if m != expect { if m != expect {
t.Errorf("growing: expected %q got %q", expect, m); t.Errorf("growing: expected %q got %q", expect, m);
} }
// 2. Shrink // 2. Shrink
minRune := func(rune int) int { return 'a' }; minRune := func(rune int) int {
return 'a';
};
m = Map(minRune, tenRunes(unicode.MaxRune)); m = Map(minRune, tenRunes(unicode.MaxRune));
expect = a; expect = a;
if m != expect { if m != expect {
...@@ -229,18 +237,18 @@ func TestTrimSpace(t *testing.T) { ...@@ -229,18 +237,18 @@ func TestTrimSpace(t *testing.T) {
func equal(m string, s1, s2 string, t *testing.T) bool { func equal(m string, s1, s2 string, t *testing.T) bool {
if s1 == s2 { if s1 == s2 {
return true return true;
} }
e1 := Split(s1, "", 0); e1 := Split(s1, "", 0);
e2 := Split(s2, "", 0); e2 := Split(s2, "", 0);
for i, c1 := range e1 { for i, c1 := range e1 {
if i > len(e2) { if i > len(e2) {
break break;
} }
r1, _ := utf8.DecodeRuneInString(c1); r1, _ := utf8.DecodeRuneInString(c1);
r2, _ := utf8.DecodeRuneInString(e2[i]); r2, _ := utf8.DecodeRuneInString(e2[i]);
if r1 != r2 { if r1 != r2 {
t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2) t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2);
} }
} }
return false; return false;
...@@ -248,9 +256,9 @@ func equal(m string, s1, s2 string, t *testing.T) bool { ...@@ -248,9 +256,9 @@ func equal(m string, s1, s2 string, t *testing.T) bool {
func TestCaseConsistency(t *testing.T) { func TestCaseConsistency(t *testing.T) {
// Make a string of all the runes. // Make a string of all the runes.
a := make([]int, unicode.MaxRune+1); a := make([]int, unicode.MaxRune + 1);
for i := range a { for i := range a {
a[i] = i a[i] = i;
} }
s := string(a); s := string(a);
// convert the cases. // convert the cases.
...@@ -258,10 +266,10 @@ func TestCaseConsistency(t *testing.T) { ...@@ -258,10 +266,10 @@ func TestCaseConsistency(t *testing.T) {
lower := ToLower(s); lower := ToLower(s);
// Consistency checks // Consistency checks
if n := utf8.RuneCountInString(upper); n != unicode.MaxRune+1 { if n := utf8.RuneCountInString(upper); n != unicode.MaxRune + 1 {
t.Error("rune count wrong in upper:", n); t.Error("rune count wrong in upper:", n);
} }
if n := utf8.RuneCountInString(lower); n != unicode.MaxRune+1 { if n := utf8.RuneCountInString(lower); n != unicode.MaxRune + 1 {
t.Error("rune count wrong in lower:", n); t.Error("rune count wrong in lower:", n);
} }
if !equal("ToUpper(upper)", ToUpper(upper), upper, t) { if !equal("ToUpper(upper)", ToUpper(upper), upper, t) {
...@@ -270,7 +278,7 @@ func TestCaseConsistency(t *testing.T) { ...@@ -270,7 +278,7 @@ func TestCaseConsistency(t *testing.T) {
if !equal("ToLower(lower)", ToLower(lower), lower, t) { if !equal("ToLower(lower)", ToLower(lower), lower, t) {
t.Error("ToLower(lower) consistency fail"); t.Error("ToLower(lower) consistency fail");
} }
/* /*
These fail because of non-one-to-oneness of the data, such as multiple These fail because of non-one-to-oneness of the data, such as multiple
upper case 'I' mapping to 'i'. We comment them out but keep them for upper case 'I' mapping to 'i'. We comment them out but keep them for
interest. interest.
......
...@@ -7,9 +7,9 @@ ...@@ -7,9 +7,9 @@
package sync package sync
func Semacquire(s *int32) { func Semacquire(s *int32) {
semacquire(s) semacquire(s);
} }
func Semrelease(s *int32) { func Semrelease(s *int32) {
semrelease(s) semrelease(s);
} }
...@@ -27,7 +27,7 @@ func xadd(val *int32, delta int32) (new int32) { ...@@ -27,7 +27,7 @@ func xadd(val *int32, delta int32) (new int32) {
return v+delta; return v+delta;
} }
} }
panic("unreached") panic("unreached");
} }
// Lock locks m. // Lock locks m.
...@@ -111,4 +111,3 @@ func (rw *RWMutex) Lock() { ...@@ -111,4 +111,3 @@ func (rw *RWMutex) Lock() {
func (rw *RWMutex) Unlock() { func (rw *RWMutex) Unlock() {
rw.m.Unlock(); rw.m.Unlock();
} }
...@@ -8,7 +8,7 @@ package sync_test ...@@ -8,7 +8,7 @@ package sync_test
import ( import (
. "sync"; . "sync";
"testing" "testing";
) )
func HammerSemaphore(s *int32, cdone chan bool) { func HammerSemaphore(s *int32, cdone chan bool) {
...@@ -50,4 +50,3 @@ func TestMutex(t *testing.T) { ...@@ -50,4 +50,3 @@ func TestMutex(t *testing.T) {
<-c; <-c;
} }
} }
...@@ -29,7 +29,7 @@ func (l *writeLogger) Write(p []byte) (n int, err os.Error) { ...@@ -29,7 +29,7 @@ func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
// that it logs (using log.Stdout) each write to standard output, // that it logs (using log.Stdout) each write to standard output,
// printing the prefix and the hexadecimal data written. // printing the prefix and the hexadecimal data written.
func NewWriteLogger(prefix string, w io.Writer) io.Writer { func NewWriteLogger(prefix string, w io.Writer) io.Writer {
return &writeLogger{prefix, w} return &writeLogger{prefix, w};
} }
type readLogger struct { type readLogger struct {
...@@ -51,5 +51,5 @@ func (l *readLogger) Read(p []byte) (n int, err os.Error) { ...@@ -51,5 +51,5 @@ func (l *readLogger) Read(p []byte) (n int, err os.Error) {
// that it logs (using log.Stdout) each write to standard output, // that it logs (using log.Stdout) each write to standard output,
// printing the prefix and the hexadecimal data written. // printing the prefix and the hexadecimal data written.
func NewReadLogger(prefix string, r io.Reader) io.Reader { func NewReadLogger(prefix string, r io.Reader) io.Reader {
return &readLogger{prefix, r} return &readLogger{prefix, r};
} }
...@@ -40,7 +40,7 @@ type halfReader struct { ...@@ -40,7 +40,7 @@ type halfReader struct {
} }
func (r *halfReader) Read(p []byte) (int, os.Error) { func (r *halfReader) Read(p []byte) (int, os.Error) {
return r.r.Read(p[0:(len(p)+1)/2]); return r.r.Read(p[0 : (len(p)+1)/2]);
} }
...@@ -70,8 +70,7 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { ...@@ -70,8 +70,7 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
break; break;
} }
n = bytes.Copy(p, r.unread); n = bytes.Copy(p, r.unread);
r.unread = r.unread[n:len(r.unread)]; r.unread = r.unread[n : len(r.unread)];
} }
return; return;
} }
...@@ -22,7 +22,7 @@ type truncateWriter struct { ...@@ -22,7 +22,7 @@ type truncateWriter struct {
func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
if t.n <= 0 { if t.n <= 0 {
return len(p), nil return len(p), nil;
} }
// real write // real write
n = len(p); n = len(p);
...@@ -34,5 +34,5 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { ...@@ -34,5 +34,5 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
if err == nil { if err == nil {
n = len(p); n = len(p);
} }
return return;
} }
...@@ -30,12 +30,12 @@ func tabify(s string) string { ...@@ -30,12 +30,12 @@ func tabify(s string) string {
s += "\n"; s += "\n";
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' { if s[i] == '\n' {
return s[0:i+1] + "\t" + tabify(s[i+1: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. // T is a type passed to Test functions to manage test state and support formatted test logs.
...@@ -48,12 +48,12 @@ type T struct { ...@@ -48,12 +48,12 @@ type T struct {
// Fail marks the Test function as having failed but continues execution. // Fail marks the Test function as having failed but continues execution.
func (t *T) Fail() { func (t *T) Fail() {
t.failed = true t.failed = true;
} }
// Failed returns whether the Test function has failed. // Failed returns whether the Test function has failed.
func (t *T) Failed() bool { func (t *T) Failed() bool {
return t.failed return t.failed;
} }
// FailNow marks the Test function as having failed and stops its execution. // FailNow marks the Test function as having failed and stops its execution.
......
...@@ -30,7 +30,7 @@ type Ticker struct { ...@@ -30,7 +30,7 @@ type Ticker struct {
// Stop turns off a ticker. After Stop, no more ticks will be delivered. // Stop turns off a ticker. After Stop, no more ticks will be delivered.
func (t *Ticker) Stop() { func (t *Ticker) Stop() {
t.shutdown = true t.shutdown = true;
} }
func (t *Ticker) ticker(c chan<- int64) { func (t *Ticker) ticker(c chan<- int64) {
...@@ -42,14 +42,14 @@ func (t *Ticker) ticker(c chan<- int64) { ...@@ -42,14 +42,14 @@ func (t *Ticker) ticker(c chan<- int64) {
// if c <- now took too long, skip ahead // if c <- now took too long, skip ahead
if when < now { if when < now {
// one big step // one big step
when += (now-when)/t.ns * t.ns; when += (now-when) / t.ns * t.ns;
} }
for when <= now { for when <= now {
// little steps until when > now // little steps until when > now
when += t.ns when += t.ns;
} }
Sleep(when - now); Sleep(when-now);
now = Nanoseconds(); now = Nanoseconds();
if t.shutdown { if t.shutdown {
return; return;
...@@ -62,7 +62,7 @@ func (t *Ticker) ticker(c chan<- int64) { ...@@ -62,7 +62,7 @@ func (t *Ticker) ticker(c chan<- int64) {
// channel only. Useful for clients that have no need to shut down the ticker. // channel only. Useful for clients that have no need to shut down the ticker.
func Tick(ns int64) <-chan int64 { func Tick(ns int64) <-chan int64 {
if ns <= 0 { if ns <= 0 {
return nil return nil;
} }
return NewTicker(ns).C; return NewTicker(ns).C;
} }
...@@ -72,7 +72,7 @@ func Tick(ns int64) <-chan int64 { ...@@ -72,7 +72,7 @@ func Tick(ns int64) <-chan int64 {
// intervals to make up for pauses in delivery of the ticks. // intervals to make up for pauses in delivery of the ticks.
func NewTicker(ns int64) *Ticker { func NewTicker(ns int64) *Ticker {
if ns <= 0 { if ns <= 0 {
return nil return nil;
} }
c := make(chan int64); c := make(chan int64);
t := &Ticker{c, ns, false}; t := &Ticker{c, ns, false};
......
...@@ -13,7 +13,7 @@ func TestTicker(t *testing.T) { ...@@ -13,7 +13,7 @@ func TestTicker(t *testing.T) {
const ( const (
Delta = 100*1e6; Delta = 100*1e6;
Count = 10; Count = 10;
); )
ticker := NewTicker(Delta); ticker := NewTicker(Delta);
t0 := Nanoseconds(); t0 := Nanoseconds();
for i := 0; i < Count; i++ { for i := 0; i < Count; i++ {
...@@ -21,10 +21,10 @@ func TestTicker(t *testing.T) { ...@@ -21,10 +21,10 @@ func TestTicker(t *testing.T) {
} }
ticker.Stop(); ticker.Stop();
t1 := Nanoseconds(); t1 := Nanoseconds();
ns := t1 - t0; ns := t1-t0;
target := int64(Delta*Count); target := int64(Delta*Count);
slop := target*2/10; slop := target*2/10;
if ns < target - slop || ns > target + slop { if ns < target-slop || ns > target+slop {
t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target)); t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target));
} }
// Now test that the ticker stopped // Now test that the ticker stopped
......
...@@ -17,7 +17,7 @@ func Seconds() int64 { ...@@ -17,7 +17,7 @@ func Seconds() int64 {
if err != nil { if err != nil {
panic("time: os.Time: ", err.String()); panic("time: os.Time: ", err.String());
} }
return sec return sec;
} }
// Nanoseconds reports the number of nanoseconds since the Unix epoch, // Nanoseconds reports the number of nanoseconds since the Unix epoch,
...@@ -27,7 +27,7 @@ func Nanoseconds() int64 { ...@@ -27,7 +27,7 @@ func Nanoseconds() int64 {
if err != nil { if err != nil {
panic("time: os.Time: ", err.String()); panic("time: os.Time: ", err.String());
} }
return sec*1e9 + nsec return sec*1e9 + nsec;
} }
// Days of the week. // Days of the week.
...@@ -51,28 +51,22 @@ type Time struct { ...@@ -51,28 +51,22 @@ type Time struct {
Zone string; Zone string;
} }
var nonleapyear = []int{ var nonleapyear = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 var leapyear = []int{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
}
var leapyear = []int{
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
}
func months(year int64) []int { func months(year int64) []int {
if year%4 == 0 && (year%100 != 0 || year%400 == 0) { if year%4 == 0 && (year%100 != 0 || year%400 == 0) {
return leapyear return leapyear;
} }
return nonleapyear return nonleapyear;
} }
const ( const (
secondsPerDay = 24*60*60; secondsPerDay = 24*60*60;
daysPer400Years = 365*400 + 97;
daysPer400Years = 365*400+97; daysPer100Years = 365*100 + 24;
daysPer100Years = 365*100+24; daysPer4Years = 365*4 + 1;
daysPer4Years = 365*4+1; days1970To2001 = 31*365 + 8;
days1970To2001 = 31*365+8;
) )
// SecondsToUTC converts sec, in number of seconds since the Unix epoch, // SecondsToUTC converts sec, in number of seconds since the Unix epoch,
...@@ -81,11 +75,11 @@ func SecondsToUTC(sec int64) *Time { ...@@ -81,11 +75,11 @@ func SecondsToUTC(sec int64) *Time {
t := new(Time); t := new(Time);
// Split into time and day. // Split into time and day.
day := sec/secondsPerDay; day := sec / secondsPerDay;
sec -= day*secondsPerDay; sec -= day * secondsPerDay;
if sec < 0 { if sec < 0 {
day--; day--;
sec += secondsPerDay sec += secondsPerDay;
} }
// Time // Time
...@@ -94,9 +88,9 @@ func SecondsToUTC(sec int64) *Time { ...@@ -94,9 +88,9 @@ func SecondsToUTC(sec int64) *Time {
t.Second = int(sec%60); t.Second = int(sec%60);
// Day 0 = January 1, 1970 was a Thursday // Day 0 = January 1, 1970 was a Thursday
t.Weekday = int((day + Thursday) % 7); t.Weekday = int((day+Thursday)%7);
if t.Weekday < 0 { if t.Weekday < 0 {
t.Weekday += 7 t.Weekday += 7;
} }
// Change day from 0 = 1970 to 0 = 2001, // Change day from 0 = 1970 to 0 = 2001,
...@@ -107,25 +101,25 @@ func SecondsToUTC(sec int64) *Time { ...@@ -107,25 +101,25 @@ func SecondsToUTC(sec int64) *Time {
year := int64(2001); year := int64(2001);
if day < 0 { if day < 0 {
// Go back enough 400 year cycles to make day positive. // Go back enough 400 year cycles to make day positive.
n := -day/daysPer400Years + 1; n := -day / daysPer400Years + 1;
year -= 400*n; year -= 400*n;
day += daysPer400Years*n; day += daysPer400Years * n;
} else { } else {
// Cut off 400 year cycles. // Cut off 400 year cycles.
n := day/daysPer400Years; n := day / daysPer400Years;
year += 400*n; year += 400*n;
day -= daysPer400Years*n; day -= daysPer400Years * n;
} }
// Cut off 100-year cycles // Cut off 100-year cycles
n := day/daysPer100Years; n := day / daysPer100Years;
year += 100*n; year += 100*n;
day -= daysPer100Years*n; day -= daysPer100Years * n;
// Cut off 4-year cycles // Cut off 4-year cycles
n = day/daysPer4Years; n = day / daysPer4Years;
year += 4*n; year += 4*n;
day -= daysPer4Years*n; day -= daysPer4Years * n;
// Cut off non-leap years. // Cut off non-leap years.
n = day/365; n = day/365;
...@@ -141,7 +135,7 @@ func SecondsToUTC(sec int64) *Time { ...@@ -141,7 +135,7 @@ func SecondsToUTC(sec int64) *Time {
var m int; var m int;
yday := int(day); yday := int(day);
for m = 0; m < 12 && yday >= months[m]; m++ { for m = 0; m < 12 && yday >= months[m]; m++ {
yday -= months[m] yday -= months[m];
} }
t.Month = m+1; t.Month = m+1;
t.Day = yday+1; t.Day = yday+1;
...@@ -152,7 +146,7 @@ func SecondsToUTC(sec int64) *Time { ...@@ -152,7 +146,7 @@ func SecondsToUTC(sec int64) *Time {
// UTC returns the current time as a parsed Time value in the UTC time zone. // UTC returns the current time as a parsed Time value in the UTC time zone.
func UTC() *Time { func UTC() *Time {
return SecondsToUTC(Seconds()) return SecondsToUTC(Seconds());
} }
// SecondsToLocalTime converts sec, in number of seconds since the Unix epoch, // SecondsToLocalTime converts sec, in number of seconds since the Unix epoch,
...@@ -162,12 +156,12 @@ func SecondsToLocalTime(sec int64) *Time { ...@@ -162,12 +156,12 @@ func SecondsToLocalTime(sec int64) *Time {
t := SecondsToUTC(sec+int64(offset)); t := SecondsToUTC(sec+int64(offset));
t.Zone = z; t.Zone = z;
t.ZoneOffset = offset; t.ZoneOffset = offset;
return t return t;
} }
// LocalTime returns the current time as a parsed Time value in the local time zone. // LocalTime returns the current time as a parsed Time value in the local time zone.
func LocalTime() *Time { func LocalTime() *Time {
return SecondsToLocalTime(Seconds()) return SecondsToLocalTime(Seconds());
} }
// Seconds returns the number of seconds since January 1, 1970 represented by the // Seconds returns the number of seconds since January 1, 1970 represented by the
...@@ -182,34 +176,34 @@ func (t *Time) Seconds() int64 { ...@@ -182,34 +176,34 @@ func (t *Time) Seconds() int64 {
// Rewrite year to be >= 2001. // Rewrite year to be >= 2001.
year := t.Year; year := t.Year;
if year < 2001 { if year < 2001 {
n := (2001 - year)/400 + 1; n := (2001-year)/400 + 1;
year += 400*n; year += 400*n;
day -= daysPer400Years*n; day -= daysPer400Years * n;
} }
// Add in days from 400-year cycles. // Add in days from 400-year cycles.
n := (year - 2001) / 400; n := (year-2001)/400;
year -= 400*n; year -= 400*n;
day += daysPer400Years*n; day += daysPer400Years * n;
// Add in 100-year cycles. // Add in 100-year cycles.
n = (year - 2001) / 100; n = (year-2001)/100;
year -= 100*n; year -= 100*n;
day += daysPer100Years*n; day += daysPer100Years * n;
// Add in 4-year cycles. // Add in 4-year cycles.
n = (year - 2001) / 4; n = (year-2001)/4;
year -= 4*n; year -= 4*n;
day += daysPer4Years*n; day += daysPer4Years * n;
// Add in non-leap years. // Add in non-leap years.
n = year - 2001; n = year-2001;
day += 365*n; day += 365*n;
// Add in days this year. // Add in days this year.
months := months(t.Year); months := months(t.Year);
for m := 0; m < t.Month-1; m++ { for m := 0; m < t.Month - 1; m++ {
day += int64(months[m]) day += int64(months[m]);
} }
day += int64(t.Day - 1); day += int64(t.Day - 1);
...@@ -226,7 +220,7 @@ func (t *Time) Seconds() int64 { ...@@ -226,7 +220,7 @@ func (t *Time) Seconds() int64 {
// Account for local time zone. // Account for local time zone.
sec -= int64(t.ZoneOffset); sec -= int64(t.ZoneOffset);
return sec return sec;
} }
var longDayNames = []string{ var longDayNames = []string{
...@@ -236,7 +230,7 @@ var longDayNames = []string{ ...@@ -236,7 +230,7 @@ var longDayNames = []string{
"Wednesday", "Wednesday",
"Thursday", "Thursday",
"Friday", "Friday",
"Saturday" "Saturday",
} }
var shortDayNames = []string{ var shortDayNames = []string{
...@@ -246,7 +240,7 @@ var shortDayNames = []string{ ...@@ -246,7 +240,7 @@ var shortDayNames = []string{
"Wed", "Wed",
"Thu", "Thu",
"Fri", "Fri",
"Sat" "Sat",
} }
var shortMonthNames = []string{ var shortMonthNames = []string{
...@@ -262,29 +256,29 @@ var shortMonthNames = []string{ ...@@ -262,29 +256,29 @@ var shortMonthNames = []string{
"Sep", "Sep",
"Oct", "Oct",
"Nov", "Nov",
"Dec" "Dec",
} }
func copy(dst []byte, s string) { func copy(dst []byte, s string) {
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
dst[i] = s[i] dst[i] = s[i];
} }
} }
func decimal(dst []byte, n int) { func decimal(dst []byte, n int) {
if n < 0 { if n < 0 {
n = 0 n = 0;
} }
for i := len(dst)-1; i >= 0; i-- { for i := len(dst)-1; i >= 0; i-- {
dst[i] = byte(n%10 + '0'); dst[i] = byte(n%10 + '0');
n /= 10 n /= 10;
} }
} }
func addString(buf []byte, bp int, s string) int { func addString(buf []byte, bp int, s string) int {
n := len(s); n := len(s);
copy(buf[bp:bp+n], s); copy(buf[bp : bp+n], s);
return bp+n return bp+n;
} }
// Just enough of strftime to implement the date formats below. // Just enough of strftime to implement the date formats below.
...@@ -304,66 +298,66 @@ func format(t *Time, fmt string) string { ...@@ -304,66 +298,66 @@ func format(t *Time, fmt string) string {
case 'b': // %b abbreviated month name case 'b': // %b abbreviated month name
bp = addString(buf, bp, shortMonthNames[t.Month]); bp = addString(buf, bp, shortMonthNames[t.Month]);
case 'd': // %d day of month (01-31) case 'd': // %d day of month (01-31)
decimal(buf[bp:bp+2], t.Day); decimal(buf[bp : bp+2], t.Day);
bp += 2; bp += 2;
case 'e': // %e day of month ( 1-31) case 'e': // %e day of month ( 1-31)
if t.Day >= 10 { if t.Day >= 10 {
decimal(buf[bp:bp+2], t.Day) decimal(buf[bp : bp+2], t.Day);
} else { } else {
buf[bp] = ' '; buf[bp] = ' ';
buf[bp+1] = byte(t.Day + '0') buf[bp+1] = byte(t.Day + '0');
} }
bp += 2; bp += 2;
case 'H': // %H hour 00-23 case 'H': // %H hour 00-23
decimal(buf[bp:bp+2], t.Hour); decimal(buf[bp : bp+2], t.Hour);
bp += 2; bp += 2;
case 'M': // %M minute 00-59 case 'M': // %M minute 00-59
decimal(buf[bp:bp+2], t.Minute); decimal(buf[bp : bp+2], t.Minute);
bp += 2; bp += 2;
case 'S': // %S second 00-59 case 'S': // %S second 00-59
decimal(buf[bp:bp+2], t.Second); decimal(buf[bp : bp+2], t.Second);
bp += 2; bp += 2;
case 'Y': // %Y year 2008 case 'Y': // %Y year 2008
decimal(buf[bp:bp+4], int(t.Year)); decimal(buf[bp : bp+4], int(t.Year));
bp += 4; bp += 4;
case 'y': // %y year 08 case 'y': // %y year 08
decimal(buf[bp:bp+2], int(t.Year%100)); decimal(buf[bp : bp+2], int(t.Year % 100));
bp += 2; bp += 2;
case 'Z': case 'Z':
bp = addString(buf, bp, t.Zone); bp = addString(buf, bp, t.Zone);
default: default:
buf[bp] = '%'; buf[bp] = '%';
buf[bp+1] = fmt[i]; buf[bp+1] = fmt[i];
bp += 2 bp += 2;
} }
} else { } else {
buf[bp] = fmt[i]; buf[bp] = fmt[i];
bp++; bp++;
} }
} }
return string(buf[0:bp]) return string(buf[0:bp]);
} }
// Asctime formats the parsed time value in the style of // Asctime formats the parsed time value in the style of
// ANSI C asctime: Sun Nov 6 08:49:37 1994 // ANSI C asctime: Sun Nov 6 08:49:37 1994
func (t *Time) Asctime() string { func (t *Time) Asctime() string {
return format(t, "%a %b %e %H:%M:%S %Y") return format(t, "%a %b %e %H:%M:%S %Y");
} }
// RFC850 formats the parsed time value in the style of // RFC850 formats the parsed time value in the style of
// RFC 850: Sunday, 06-Nov-94 08:49:37 UTC // RFC 850: Sunday, 06-Nov-94 08:49:37 UTC
func (t *Time) RFC850() string { func (t *Time) RFC850() string {
return format(t, "%A, %d-%b-%y %H:%M:%S %Z") return format(t, "%A, %d-%b-%y %H:%M:%S %Z");
} }
// RFC1123 formats the parsed time value in the style of // RFC1123 formats the parsed time value in the style of
// RFC 1123: Sun, 06 Nov 1994 08:49:37 UTC // RFC 1123: Sun, 06 Nov 1994 08:49:37 UTC
func (t *Time) RFC1123() string { func (t *Time) RFC1123() string {
return format(t, "%a, %d %b %Y %H:%M:%S %Z") return format(t, "%a, %d %b %Y %H:%M:%S %Z");
} }
// String formats the parsed time value in the style of // String formats the parsed time value in the style of
// date(1) - Sun Nov 6 08:49:37 UTC 1994 // date(1) - Sun Nov 6 08:49:37 UTC 1994
func (t *Time) String() string { func (t *Time) String() string {
return format(t, "%a %b %e %H:%M:%S %Z %Y") return format(t, "%a %b %e %H:%M:%S %Z %Y");
} }
...@@ -12,12 +12,11 @@ package time ...@@ -12,12 +12,11 @@ package time
import ( import (
"io"; "io";
"once"; "once";
"os" "os";
) )
const ( const (
headerSize = 4+16+4*7; headerSize = 4 + 16 + 4*7;
zoneDir = "/usr/share/zoneinfo/"; zoneDir = "/usr/share/zoneinfo/";
) )
...@@ -35,26 +34,26 @@ func (d *data) read(n int) []byte { ...@@ -35,26 +34,26 @@ func (d *data) read(n int) []byte {
return nil; return nil;
} }
p := d.p[0:n]; p := d.p[0:n];
d.p = d.p[n:len(d.p)]; d.p = d.p[n : len(d.p)];
return p return p;
} }
func (d *data) big4() (n uint32, ok bool) { func (d *data) big4() (n uint32, ok bool) {
p := d.read(4); p := d.read(4);
if len(p) < 4 { if len(p) < 4 {
d.error = true; d.error = true;
return 0, false return 0, false;
} }
return uint32(p[0]) << 24 | uint32(p[1]) << 16 | uint32(p[2]) << 8 | uint32(p[3]), true return uint32(p[0])<<24 | uint32(p[1])<<16 | uint32(p[2])<<8 | uint32(p[3]), true;
} }
func (d *data) byte() (n byte, ok bool) { func (d *data) byte() (n byte, ok bool) {
p := d.read(1); p := d.read(1);
if len(p) < 1 { if len(p) < 1 {
d.error = true; d.error = true;
return 0, false return 0, false;
} }
return p[0], true return p[0], true;
} }
...@@ -62,10 +61,10 @@ func (d *data) byte() (n byte, ok bool) { ...@@ -62,10 +61,10 @@ func (d *data) byte() (n byte, ok bool) {
func byteString(p []byte) string { func byteString(p []byte) string {
for i := 0; i < len(p); i++ { for i := 0; i < len(p); i++ {
if p[i] == 0 { if p[i] == 0 {
return string(p[0:i]) return string(p[0:i]);
} }
} }
return string(p) return string(p);
} }
// Parsed representation // Parsed representation
...@@ -86,13 +85,13 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -86,13 +85,13 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
// 4-byte magic "TZif" // 4-byte magic "TZif"
if magic := d.read(4); string(magic) != "TZif" { if magic := d.read(4); string(magic) != "TZif" {
return nil, false return nil, false;
} }
// 1-byte version, then 15 bytes of padding // 1-byte version, then 15 bytes of padding
var p []byte; var p []byte;
if p = d.read(16); len(p) != 16 || p[0] != 0 && p[0] != '2' { if p = d.read(16); len(p) != 16 || p[0] != 0 && p[0] != '2' {
return nil, false return nil, false;
} }
// six big-endian 32-bit integers: // six big-endian 32-bit integers:
...@@ -108,13 +107,13 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -108,13 +107,13 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
NLeap; NLeap;
NTime; NTime;
NZone; NZone;
NChar NChar;
) )
var n [6]int; var n [6]int;
for i := 0; i < 6; i++ { for i := 0; i < 6; i++ {
nn, ok := d.big4(); nn, ok := d.big4();
if !ok { if !ok {
return nil, false return nil, false;
} }
n[i] = int(nn); n[i] = int(nn);
} }
...@@ -143,7 +142,7 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -143,7 +142,7 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
isutc := d.read(n[NUTCLocal]); isutc := d.read(n[NUTCLocal]);
if d.error { // ran out of data if d.error { // ran out of data
return nil, false return nil, false;
} }
// If version == 2, the entire file repeats, this time using // If version == 2, the entire file repeats, this time using
...@@ -158,18 +157,18 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -158,18 +157,18 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
var ok bool; var ok bool;
var n uint32; var n uint32;
if n, ok = zonedata.big4(); !ok { if n, ok = zonedata.big4(); !ok {
return nil, false return nil, false;
} }
z[i].utcoff = int(n); z[i].utcoff = int(n);
var b byte; var b byte;
if b, ok = zonedata.byte(); !ok { if b, ok = zonedata.byte(); !ok {
return nil, false return nil, false;
} }
z[i].isdst = b != 0; z[i].isdst = b != 0;
if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) { if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) {
return nil, false return nil, false;
} }
z[i].name = byteString(abbrev[b:len(abbrev)]) z[i].name = byteString(abbrev[b:len(abbrev)]);
} }
// Now the transition time info. // Now the transition time info.
...@@ -178,27 +177,27 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -178,27 +177,27 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
var ok bool; var ok bool;
var n uint32; var n uint32;
if n, ok = txtimes.big4(); !ok { if n, ok = txtimes.big4(); !ok {
return nil, false return nil, false;
} }
zt[i].time = int32(n); zt[i].time = int32(n);
if int(txzones[i]) >= len(z) { if int(txzones[i]) >= len(z) {
return nil, false return nil, false;
} }
zt[i].zone = &z[txzones[i]]; zt[i].zone = &z[txzones[i]];
if i < len(isstd) { if i < len(isstd) {
zt[i].isstd = isstd[i] != 0 zt[i].isstd = isstd[i] != 0;
} }
if i < len(isutc) { if i < len(isutc) {
zt[i].isutc = isutc[i] != 0 zt[i].isutc = isutc[i] != 0;
} }
} }
return zt, true return zt, true;
} }
func readinfofile(name string) ([]zonetime, bool) { func readinfofile(name string) ([]zonetime, bool) {
buf, err := io.ReadFile(name); buf, err := io.ReadFile(name);
if err != nil { if err != nil {
return nil, false return nil, false;
} }
return parseinfo(buf); return parseinfo(buf);
} }
...@@ -216,7 +215,7 @@ func setupZone() { ...@@ -216,7 +215,7 @@ func setupZone() {
case err == os.ENOENV: case err == os.ENOENV:
zones, _ = readinfofile("/etc/localtime"); zones, _ = readinfofile("/etc/localtime");
case len(tz) > 0: case len(tz) > 0:
zones, _ = readinfofile(zoneDir + tz); zones, _ = readinfofile(zoneDir+tz);
case len(tz) == 0: case len(tz) == 0:
// do nothing: use UTC // do nothing: use UTC
} }
...@@ -225,7 +224,7 @@ func setupZone() { ...@@ -225,7 +224,7 @@ func setupZone() {
func lookupTimezone(sec int64) (zone string, offset int) { func lookupTimezone(sec int64) (zone string, offset int) {
once.Do(setupZone); once.Do(setupZone);
if len(zones) == 0 { if len(zones) == 0 {
return "UTC", 0 return "UTC", 0;
} }
// Binary search for entry with largest time <= sec // Binary search for entry with largest time <= sec
...@@ -233,11 +232,11 @@ func lookupTimezone(sec int64) (zone string, offset int) { ...@@ -233,11 +232,11 @@ func lookupTimezone(sec int64) (zone string, offset int) {
for len(tz) > 1 { for len(tz) > 1 {
m := len(tz)/2; m := len(tz)/2;
if sec < int64(tz[m].time) { if sec < int64(tz[m].time) {
tz = tz[0:m] tz = tz[0:m];
} else { } else {
tz = tz[m:len(tz)] tz = tz[m:len(tz)];
} }
} }
z := tz[0].zone; z := tz[0].zone;
return z.name, z.utcoff return z.name, z.utcoff;
} }
...@@ -7,7 +7,7 @@ package unicode ...@@ -7,7 +7,7 @@ package unicode
// IsDigit reports whether the rune is a decimal digit. // IsDigit reports whether the rune is a decimal digit.
func IsDigit(rune int) bool { 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 '0' <= rune && rune <= '9';
} }
return Is(Digit, rune); return Is(Digit, rune);
} }
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
. "unicode"; . "unicode";
) )
var testDigit = []int { var testDigit = []int{
0x0030, 0x0030,
0x0039, 0x0039,
0x0661, 0x0661,
...@@ -68,7 +68,7 @@ var testDigit = []int { ...@@ -68,7 +68,7 @@ var testDigit = []int {
0x1D7CE, 0x1D7CE,
} }
var testLetter = []int { var testLetter = []int{
0x0041, 0x0041,
0x0061, 0x0061,
0x00AA, 0x00AA,
...@@ -120,7 +120,7 @@ func TestDigit(t *testing.T) { ...@@ -120,7 +120,7 @@ func TestDigit(t *testing.T) {
func TestDigitOptimization(t *testing.T) { func TestDigitOptimization(t *testing.T) {
for i := 0; i < 0x100; i++ { for i := 0; i < 0x100; i++ {
if Is(Digit, i) != IsDigit(i) { if Is(Digit, i) != IsDigit(i) {
t.Errorf("IsDigit(U+%04X) disagrees with Is(Digit)", i) t.Errorf("IsDigit(U+%04X) disagrees with Is(Digit)", i);
} }
} }
} }
...@@ -41,13 +41,14 @@ const ( ...@@ -41,13 +41,14 @@ const (
TitleCase; TitleCase;
MaxCase; MaxCase;
) )
type d [MaxCase]int32 // to make the CaseRanges text shorter type d [MaxCase]int32 // to make the CaseRanges text shorter
// If the Delta field of a CaseRange is UpperLower or LowerUpper, it means // If the Delta field of a CaseRange is UpperLower or LowerUpper, it means
// this CaseRange represents a sequence of the form (say) // this CaseRange represents a sequence of the form (say)
// Upper Lower Upper Lower. // Upper Lower Upper Lower.
const ( const (
UpperLower = MaxRune + 1; // (Cannot be a valid delta.) UpperLower = MaxRune+1; // (Cannot be a valid delta.)
) )
// Is tests whether rune is in the specified table of ranges. // Is tests whether rune is in the specified table of ranges.
...@@ -70,7 +71,7 @@ func Is(ranges []Range, rune int) bool { ...@@ -70,7 +71,7 @@ func Is(ranges []Range, rune int) bool {
lo := 0; lo := 0;
hi := len(ranges); hi := len(ranges);
for lo < hi { for lo < hi {
m := lo + (hi - lo)/2; m := lo + (hi-lo)/2;
r := ranges[m]; r := ranges[m];
if r.Lo <= rune && rune <= r.Hi { if r.Lo <= rune && rune <= r.Hi {
return (rune - r.Lo) % r.Stride == 0; return (rune - r.Lo) % r.Stride == 0;
...@@ -132,13 +133,13 @@ func IsSpace(rune int) bool { ...@@ -132,13 +133,13 @@ func IsSpace(rune int) bool {
// To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase // To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase
func To(_case int, rune int) int { func To(_case int, rune int) int {
if _case < 0 || MaxCase <= _case { if _case < 0 || MaxCase <= _case {
return ReplacementChar // as reasonable an error as any return ReplacementChar; // as reasonable an error as any
} }
// binary search over ranges // binary search over ranges
lo := 0; lo := 0;
hi := len(CaseRanges); hi := len(CaseRanges);
for lo < hi { for lo < hi {
m := lo + (hi - lo)/2; m := lo + (hi-lo)/2;
r := CaseRanges[m]; r := CaseRanges[m];
if r.Lo <= rune && rune <= r.Hi { if r.Lo <= rune && rune <= r.Hi {
delta := int(r.Delta[_case]); delta := int(r.Delta[_case]);
...@@ -155,7 +156,7 @@ func To(_case int, rune int) int { ...@@ -155,7 +156,7 @@ func To(_case int, rune int) int {
// is odd so we take the low bit from _case. // is odd so we take the low bit from _case.
return r.Lo + ((rune - r.Lo)&^1 | _case&1); return r.Lo + ((rune - r.Lo)&^1 | _case&1);
} }
return rune + delta; return rune+delta;
} }
if rune < r.Lo { if rune < r.Lo {
hi = m; hi = m;
...@@ -170,9 +171,9 @@ func To(_case int, rune int) int { ...@@ -170,9 +171,9 @@ func To(_case int, rune int) int {
func ToUpper(rune int) int { func ToUpper(rune int) int {
if rune < 0x80 { // quick ASCII check if rune < 0x80 { // quick ASCII check
if 'a' <= rune && rune <= 'z' { if 'a' <= rune && rune <= 'z' {
rune -= 'a'-'A' rune -= 'a'-'A';
} }
return rune return rune;
} }
return To(UpperCase, rune); return To(UpperCase, rune);
} }
...@@ -181,9 +182,9 @@ func ToUpper(rune int) int { ...@@ -181,9 +182,9 @@ func ToUpper(rune int) int {
func ToLower(rune int) int { func ToLower(rune int) int {
if rune < 0x80 { // quick ASCII check if rune < 0x80 { // quick ASCII check
if 'A' <= rune && rune <= 'Z' { if 'A' <= rune && rune <= 'Z' {
rune += 'a'-'A' rune += 'a'-'A';
} }
return rune return rune;
} }
return To(LowerCase, rune); return To(LowerCase, rune);
} }
...@@ -192,9 +193,9 @@ func ToLower(rune int) int { ...@@ -192,9 +193,9 @@ func ToLower(rune int) int {
func ToTitle(rune int) int { func ToTitle(rune int) int {
if rune < 0x80 { // quick ASCII check if rune < 0x80 { // quick ASCII check
if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII
rune -= 'a'-'A' rune -= 'a'-'A';
} }
return rune return rune;
} }
return To(TitleCase, rune); return To(TitleCase, rune);
} }
...@@ -107,10 +107,10 @@ var spaceTest = []int{ ...@@ -107,10 +107,10 @@ var spaceTest = []int{
} }
type caseT struct { type caseT struct {
cas, in, out int cas, in, out int;
} }
var caseTest = []caseT { var caseTest = []caseT{
// errors // errors
caseT{-1, '\n', 0xFFFD}, caseT{-1, '\n', 0xFFFD},
caseT{UpperCase, -1, -1}, caseT{UpperCase, -1, -1},
...@@ -252,13 +252,13 @@ func TestIsUpper(t *testing.T) { ...@@ -252,13 +252,13 @@ func TestIsUpper(t *testing.T) {
func caseString(c int) string { func caseString(c int) string {
switch c { switch c {
case UpperCase: case UpperCase:
return "UpperCase" return "UpperCase";
case LowerCase: case LowerCase:
return "LowerCase" return "LowerCase";
case TitleCase: case TitleCase:
return "TitleCase" return "TitleCase";
} }
return "ErrorCase" return "ErrorCase";
} }
func TestTo(t *testing.T) { func TestTo(t *testing.T) {
...@@ -273,7 +273,7 @@ func TestTo(t *testing.T) { ...@@ -273,7 +273,7 @@ func TestTo(t *testing.T) {
func TestToUpperCase(t *testing.T) { func TestToUpperCase(t *testing.T) {
for _, c := range caseTest { for _, c := range caseTest {
if c.cas != UpperCase { if c.cas != UpperCase {
continue continue;
} }
r := ToUpper(c.in); r := ToUpper(c.in);
if c.out != r { if c.out != r {
...@@ -285,7 +285,7 @@ func TestToUpperCase(t *testing.T) { ...@@ -285,7 +285,7 @@ func TestToUpperCase(t *testing.T) {
func TestToLowerCase(t *testing.T) { func TestToLowerCase(t *testing.T) {
for _, c := range caseTest { for _, c := range caseTest {
if c.cas != LowerCase { if c.cas != LowerCase {
continue continue;
} }
r := ToLower(c.in); r := ToLower(c.in);
if c.out != r { if c.out != r {
...@@ -297,7 +297,7 @@ func TestToLowerCase(t *testing.T) { ...@@ -297,7 +297,7 @@ func TestToLowerCase(t *testing.T) {
func TestToTitleCase(t *testing.T) { func TestToTitleCase(t *testing.T) {
for _, c := range caseTest { for _, c := range caseTest {
if c.cas != TitleCase { if c.cas != TitleCase {
continue continue;
} }
r := ToTitle(c.in); r := ToTitle(c.in);
if c.out != r { if c.out != r {
...@@ -324,28 +324,28 @@ func TestIsSpace(t *testing.T) { ...@@ -324,28 +324,28 @@ func TestIsSpace(t *testing.T) {
func TestLetterOptimizations(t *testing.T) { func TestLetterOptimizations(t *testing.T) {
for i := 0; i < 0x100; i++ { for i := 0; i < 0x100; i++ {
if Is(Letter, i) != IsLetter(i) { if Is(Letter, i) != IsLetter(i) {
t.Errorf("IsLetter(U+%04X) disagrees with Is(Letter)", i) t.Errorf("IsLetter(U+%04X) disagrees with Is(Letter)", i);
} }
if Is(Upper, i) != IsUpper(i) { if Is(Upper, i) != IsUpper(i) {
t.Errorf("IsUpper(U+%04X) disagrees with Is(Upper)", i) t.Errorf("IsUpper(U+%04X) disagrees with Is(Upper)", i);
} }
if Is(Lower, i) != IsLower(i) { if Is(Lower, i) != IsLower(i) {
t.Errorf("IsLower(U+%04X) disagrees with Is(Lower)", i) t.Errorf("IsLower(U+%04X) disagrees with Is(Lower)", i);
} }
if Is(Title, i) != IsTitle(i) { if Is(Title, i) != IsTitle(i) {
t.Errorf("IsTitle(U+%04X) disagrees with Is(Title)", i) t.Errorf("IsTitle(U+%04X) disagrees with Is(Title)", i);
} }
if Is(White_Space, i) != IsSpace(i) { if Is(White_Space, i) != IsSpace(i) {
t.Errorf("IsSpace(U+%04X) disagrees with Is(White_Space)", i) t.Errorf("IsSpace(U+%04X) disagrees with Is(White_Space)", i);
} }
if To(UpperCase, i) != ToUpper(i) { if To(UpperCase, i) != ToUpper(i) {
t.Errorf("ToUpper(U+%04X) disagrees with To(Upper)", i) t.Errorf("ToUpper(U+%04X) disagrees with To(Upper)", i);
} }
if To(LowerCase, i) != ToLower(i) { if To(LowerCase, i) != ToLower(i) {
t.Errorf("ToLower(U+%04X) disagrees with To(Lower)", i) t.Errorf("ToLower(U+%04X) disagrees with To(Lower)", i);
} }
if To(TitleCase, i) != ToTitle(i) { if To(TitleCase, i) != ToTitle(i) {
t.Errorf("ToTitle(U+%04X) disagrees with To(Title)", i) t.Errorf("ToTitle(U+%04X) disagrees with To(Title)", i);
} }
} }
} }
...@@ -36,12 +36,12 @@ func Offsetof(v ArbitraryType) int ...@@ -36,12 +36,12 @@ func Offsetof(v ArbitraryType) int
func Alignof(v ArbitraryType) int func Alignof(v ArbitraryType) int
// Typeof returns the type of an interface value, a runtime.Type. // Typeof returns the type of an interface value, a runtime.Type.
func Typeof(i interface {}) (typ interface {}) func Typeof(i interface{}) (typ interface{})
// Reflect unpacks an interface value into its type and the address of a copy of the // Reflect unpacks an interface value into its type and the address of a copy of the
// internal value. // internal value.
func Reflect(i interface {}) (typ interface {}, addr uintptr) func Reflect(i interface{}) (typ interface{}, addr uintptr)
// Unreflect inverts Reflect: Given a type and a pointer, it returns an empty interface value // Unreflect inverts Reflect: Given a type and a pointer, it returns an empty interface value
// with those contents. // with those contents.
func Unreflect(typ interface {}, addr uintptr) (ret interface {}) func Unreflect(typ interface{}, addr uintptr) (ret interface{})
...@@ -16,39 +16,39 @@ type Utf8Map struct { ...@@ -16,39 +16,39 @@ type Utf8Map struct {
str string; str string;
} }
var utf8map = []Utf8Map { var utf8map = []Utf8Map{
Utf8Map{ 0x0000, "\x00" }, Utf8Map{0x0000, "\x00"},
Utf8Map{ 0x0001, "\x01" }, Utf8Map{0x0001, "\x01"},
Utf8Map{ 0x007e, "\x7e" }, Utf8Map{0x007e, "\x7e"},
Utf8Map{ 0x007f, "\x7f" }, Utf8Map{0x007f, "\x7f"},
Utf8Map{ 0x0080, "\xc2\x80" }, Utf8Map{0x0080, "\xc2\x80"},
Utf8Map{ 0x0081, "\xc2\x81" }, Utf8Map{0x0081, "\xc2\x81"},
Utf8Map{ 0x00bf, "\xc2\xbf" }, Utf8Map{0x00bf, "\xc2\xbf"},
Utf8Map{ 0x00c0, "\xc3\x80" }, Utf8Map{0x00c0, "\xc3\x80"},
Utf8Map{ 0x00c1, "\xc3\x81" }, Utf8Map{0x00c1, "\xc3\x81"},
Utf8Map{ 0x00c8, "\xc3\x88" }, Utf8Map{0x00c8, "\xc3\x88"},
Utf8Map{ 0x00d0, "\xc3\x90" }, Utf8Map{0x00d0, "\xc3\x90"},
Utf8Map{ 0x00e0, "\xc3\xa0" }, Utf8Map{0x00e0, "\xc3\xa0"},
Utf8Map{ 0x00f0, "\xc3\xb0" }, Utf8Map{0x00f0, "\xc3\xb0"},
Utf8Map{ 0x00f8, "\xc3\xb8" }, Utf8Map{0x00f8, "\xc3\xb8"},
Utf8Map{ 0x00ff, "\xc3\xbf" }, Utf8Map{0x00ff, "\xc3\xbf"},
Utf8Map{ 0x0100, "\xc4\x80" }, Utf8Map{0x0100, "\xc4\x80"},
Utf8Map{ 0x07ff, "\xdf\xbf" }, Utf8Map{0x07ff, "\xdf\xbf"},
Utf8Map{ 0x0800, "\xe0\xa0\x80" }, Utf8Map{0x0800, "\xe0\xa0\x80"},
Utf8Map{ 0x0801, "\xe0\xa0\x81" }, Utf8Map{0x0801, "\xe0\xa0\x81"},
Utf8Map{ 0xfffe, "\xef\xbf\xbe" }, Utf8Map{0xfffe, "\xef\xbf\xbe"},
Utf8Map{ 0xffff, "\xef\xbf\xbf" }, Utf8Map{0xffff, "\xef\xbf\xbf"},
Utf8Map{ 0x10000, "\xf0\x90\x80\x80" }, Utf8Map{0x10000, "\xf0\x90\x80\x80"},
Utf8Map{ 0x10001, "\xf0\x90\x80\x81" }, Utf8Map{0x10001, "\xf0\x90\x80\x81"},
Utf8Map{ 0x10fffe, "\xf4\x8f\xbf\xbe" }, Utf8Map{0x10fffe, "\xf4\x8f\xbf\xbe"},
Utf8Map{ 0x10ffff, "\xf4\x8f\xbf\xbf" }, Utf8Map{0x10ffff, "\xf4\x8f\xbf\xbf"},
} }
// strings.Bytes with one extra byte at end // strings.Bytes with one extra byte at end
func makeBytes(s string) []byte { func makeBytes(s string) []byte {
s += "\x00"; s += "\x00";
b := strings.Bytes(s); b := strings.Bytes(s);
return b[0:len(s)-1]; return b[0 : len(s)-1];
} }
func TestFullRune(t *testing.T) { func TestFullRune(t *testing.T) {
...@@ -62,7 +62,7 @@ func TestFullRune(t *testing.T) { ...@@ -62,7 +62,7 @@ func TestFullRune(t *testing.T) {
if !FullRuneInString(s) { if !FullRuneInString(s) {
t.Errorf("FullRuneInString(%q) (rune %04x) = false, want true", s, m.rune); t.Errorf("FullRuneInString(%q) (rune %04x) = false, want true", s, m.rune);
} }
b1 := b[0:len(b)-1]; b1 := b[0 : len(b)-1];
if FullRune(b1) { if FullRune(b1) {
t.Errorf("FullRune(%q) = true, want false", b1); t.Errorf("FullRune(%q) = true, want false", b1);
} }
...@@ -105,7 +105,7 @@ func TestDecodeRune(t *testing.T) { ...@@ -105,7 +105,7 @@ func TestDecodeRune(t *testing.T) {
if rune != m.rune || size != len(b) { if rune != m.rune || size != len(b) {
t.Errorf("DecodeRune(%q) = 0x%04x, %d want 0x%04x, %d", b, rune, size, m.rune, len(b)); t.Errorf("DecodeRune(%q) = 0x%04x, %d want 0x%04x, %d", b, rune, size, m.rune, len(b));
} }
s = m.str+"\x00"; s = m.str + "\x00";
rune, size = DecodeRuneInString(s); rune, size = DecodeRuneInString(s);
if rune != m.rune || size != len(b) { if rune != m.rune || size != len(b) {
t.Errorf("DecodeRuneInString(%q) = 0x%04x, %d want 0x%04x, %d", s, rune, size, m.rune, len(b)); t.Errorf("DecodeRuneInString(%q) = 0x%04x, %d want 0x%04x, %d", s, rune, size, m.rune, len(b));
...@@ -116,11 +116,11 @@ func TestDecodeRune(t *testing.T) { ...@@ -116,11 +116,11 @@ func TestDecodeRune(t *testing.T) {
if wantsize >= len(b) { if wantsize >= len(b) {
wantsize = 0; wantsize = 0;
} }
rune, size = DecodeRune(b[0:len(b)-1]); rune, size = DecodeRune(b[0 : len(b)-1]);
if rune != RuneError || size != wantsize { if rune != RuneError || size != wantsize {
t.Errorf("DecodeRune(%q) = 0x%04x, %d want 0x%04x, %d", b[0:len(b)-1], rune, size, RuneError, wantsize); t.Errorf("DecodeRune(%q) = 0x%04x, %d want 0x%04x, %d", b[0 : len(b)-1], rune, size, RuneError, wantsize);
} }
s = m.str[0:len(m.str)-1]; s = m.str[0 : len(m.str) - 1];
rune, size = DecodeRuneInString(s); rune, size = DecodeRuneInString(s);
if rune != RuneError || size != wantsize { if rune != RuneError || size != wantsize {
t.Errorf("DecodeRuneInString(%q) = 0x%04x, %d want 0x%04x, %d", s, rune, size, RuneError, wantsize); t.Errorf("DecodeRuneInString(%q) = 0x%04x, %d want 0x%04x, %d", s, rune, size, RuneError, wantsize);
...@@ -148,12 +148,14 @@ type RuneCountTest struct { ...@@ -148,12 +148,14 @@ type RuneCountTest struct {
in string; in string;
out int; out int;
} }
var runecounttests = []RuneCountTest {
RuneCountTest{ "abcd", 4 }, var runecounttests = []RuneCountTest{
RuneCountTest{ "☺☻☹", 3 }, RuneCountTest{"abcd", 4},
RuneCountTest{ "1,2,3,4", 7 }, RuneCountTest{"☺☻☹", 3},
RuneCountTest{ "\xe2\x00", 2 }, RuneCountTest{"1,2,3,4", 7},
RuneCountTest{"\xe2\x00", 2},
} }
func TestRuneCount(t *testing.T) { func TestRuneCount(t *testing.T) {
for i := 0; i < len(runecounttests); i++ { for i := 0; i < len(runecounttests); i++ {
tt := runecounttests[i]; tt := runecounttests[i];
......
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