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
This diff is collapsed.
...@@ -12,10 +12,10 @@ package reflect ...@@ -12,10 +12,10 @@ package reflect
// checks in progress are true when it reencounters them. // checks in progress are true when it reencounters them.
// Visited are stored in a map indexed by 17 * a1 + a2; // Visited are stored in a map indexed by 17 * a1 + a2;
type visit struct { type visit struct {
a1 uintptr; a1 uintptr;
a2 uintptr; a2 uintptr;
typ Type; typ Type;
next *visit; next *visit;
} }
// Tests for deep equality using reflected types. The map argument tracks // Tests for deep equality using reflected types. The map argument tracks
...@@ -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;
} }
......
...@@ -9,8 +9,8 @@ ...@@ -9,8 +9,8 @@
package reflect_test package reflect_test
import ( import (
. "reflect"; . "reflect";
"strconv"; "strconv";
) )
// valueToString returns a textual representation of the reflection value val. // valueToString returns a textual representation of the reflection value val.
...@@ -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));
} }
......
...@@ -24,197 +24,198 @@ import ( ...@@ -24,197 +24,198 @@ import (
*/ */
type commonType struct { type commonType struct {
size uintptr; size uintptr;
hash uint32; hash uint32;
alg uint8; alg uint8;
align uint8; align uint8;
fieldAlign uint8; fieldAlign uint8;
string *string; string *string;
*uncommonType; *uncommonType;
} }
type method struct { type method struct {
hash uint32; hash uint32;
name *string; name *string;
pkgPath *string; pkgPath *string;
typ *runtime.Type; typ *runtime.Type;
ifn unsafe.Pointer; ifn unsafe.Pointer;
tfn unsafe.Pointer; tfn unsafe.Pointer;
} }
type uncommonType struct { type uncommonType struct {
name *string; name *string;
pkgPath *string; pkgPath *string;
methods []method; methods []method;
} }
// 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.
type ArrayType struct { type ArrayType struct {
commonType; commonType;
elem *runtime.Type; elem *runtime.Type;
len uintptr; len uintptr;
} }
// 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.
type ChanType struct { type ChanType struct {
commonType; commonType;
elem *runtime.Type; elem *runtime.Type;
dir uintptr; dir uintptr;
} }
// FuncType represents a function type. // FuncType represents a function type.
type FuncType struct { type FuncType struct {
commonType; commonType;
in []*runtime.Type; in []*runtime.Type;
out []*runtime.Type; out []*runtime.Type;
} }
// Method on interface type // Method on interface type
type imethod struct { type imethod struct {
hash uint32; hash uint32;
perm uint32; perm uint32;
name *string; name *string;
pkgPath *string; pkgPath *string;
typ *runtime.Type; typ *runtime.Type;
} }
// InterfaceType represents an interface type. // InterfaceType represents an interface type.
type InterfaceType struct { type InterfaceType struct {
commonType; commonType;
methods []imethod; methods []imethod;
} }
// MapType represents a map type. // MapType represents a map type.
type MapType struct { type MapType struct {
commonType; commonType;
key *runtime.Type; key *runtime.Type;
elem *runtime.Type; elem *runtime.Type;
} }
// PtrType represents a pointer type. // PtrType represents a pointer type.
type PtrType struct { type PtrType struct {
commonType; commonType;
elem *runtime.Type; elem *runtime.Type;
} }
// SliceType represents a slice type. // SliceType represents a slice type.
type SliceType struct { type SliceType struct {
commonType; commonType;
elem *runtime.Type; elem *runtime.Type;
} }
// Struct field // Struct field
type structField struct { type structField struct {
name *string; name *string;
pkgPath *string; pkgPath *string;
typ *runtime.Type; typ *runtime.Type;
tag *string; tag *string;
offset uintptr; offset uintptr;
} }
// StructType represents a struct type. // StructType represents a struct type.
type StructType struct { type StructType struct {
commonType; commonType;
fields []structField; fields []structField;
} }
...@@ -225,10 +226,10 @@ type StructType struct { ...@@ -225,10 +226,10 @@ type StructType struct {
// Method represents a single method. // Method represents a single method.
type Method struct { type Method struct {
PkgPath string; // empty for uppercase Name PkgPath string; // empty for uppercase Name
Name string; Name string;
Type *FuncType; Type *FuncType;
Func *FuncValue; Func *FuncValue;
} }
// Type is the runtime representation of a Go type. // Type is the runtime representation of a Go type.
...@@ -240,36 +241,35 @@ type Method struct { ...@@ -240,36 +241,35 @@ type Method struct {
type Type interface { type Type interface {
// PkgPath returns the type's package path. // PkgPath returns the type's package path.
// The package path is a full package import path like "container/vector". // The package path is a full package import path like "container/vector".
PkgPath() string; PkgPath() string;
// Name returns the type's name within its package. // Name returns the type's name within its package.
Name() string; Name() string;
// String returns a string representation of the type. // String returns a string representation of the type.
// The string representation may use shortened package names // The string representation may use shortened package names
// (e.g., vector instead of "container/vector") and is not // (e.g., vector instead of "container/vector") and is not
// guaranteed to be unique among types. To test for equality, // guaranteed to be unique among types. To test for equality,
// compare the Types directly. // compare the Types directly.
String() string; String() string;
// Size returns the number of bytes needed to store // Size returns the number of bytes needed to store
// a value of the given type; it is analogous to unsafe.Sizeof. // a value of the given type; it is analogous to unsafe.Sizeof.
Size() uintptr; Size() uintptr;
// Align returns the alignment of a value of this type // Align returns the alignment of a value of this type
// when allocated in memory. // when allocated in memory.
Align() int; Align() int;
// FieldAlign returns the alignment of a value of this type // FieldAlign returns the alignment of a value of this type
// when used as a field in a struct. // when used as a field in a struct.
FieldAlign() int; FieldAlign() int;
// For non-interface types, Method returns the i'th method with receiver T. // For non-interface types, Method returns the i'th method with receiver T.
// For interface types, Method returns the i'th method in the interface. // For interface types, Method returns the i'th method in the 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;
} }
...@@ -448,13 +448,13 @@ func (t *SliceType) Elem() Type { ...@@ -448,13 +448,13 @@ func (t *SliceType) Elem() Type {
} }
type StructField struct { type StructField struct {
PkgPath string; // empty for uppercase Name PkgPath string; // empty for uppercase Name
Name string; Name string;
Type Type; Type Type;
Tag string; Tag string;
Offset uintptr; Offset uintptr;
Index []int; Index []int;
Anonymous bool; Anonymous bool;
} }
// Field returns the i'th struct field. // Field returns the i'th struct field.
...@@ -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
...@@ -521,7 +521,7 @@ func (t *StructType) fieldByName(name string, mark map[*StructType]bool, depth i ...@@ -521,7 +521,7 @@ func (t *StructType) fieldByName(name string, mark map[*StructType]bool, depth i
mark[t] = true; mark[t] = true;
var fi int; // field index var fi int; // field index
n := 0; // number of matching fields at depth fd n := 0; // number of matching fields at depth fd
L: for i, _ := range t.fields { L: for i, _ := range t.fields {
f := t.Field(i); f := t.Field(i);
d := inf; d := inf;
...@@ -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));
} }
This diff is collapsed.
...@@ -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,22 +123,22 @@ import ( ...@@ -123,22 +123,22 @@ 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 {
sync.Mutex; // protects counters sync.Mutex; // protects counters
method reflect.Method; method reflect.Method;
argType *reflect.PtrType; argType *reflect.PtrType;
replyType *reflect.PtrType; replyType *reflect.PtrType;
numCalls uint; numCalls uint;
} }
type service struct { 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
...@@ -146,7 +146,7 @@ type service struct { ...@@ -146,7 +146,7 @@ type service struct {
// network traffic. // network traffic.
type Request struct { type Request struct {
ServiceMethod string; // format: "Service.Method" ServiceMethod string; // format: "Service.Method"
Seq uint64; // sequence number chosen by client Seq uint64; // sequence number chosen by client
} }
// Response is a header written before every RPC return. It is used internally // Response is a header written before every RPC return. It is used internally
...@@ -154,38 +154,38 @@ type Request struct { ...@@ -154,38 +154,38 @@ type Request struct {
// network traffic. // network traffic.
type Response struct { type Response struct {
ServiceMethod string; // echoes that of the Request ServiceMethod string; // echoes that of the Request
Seq uint64; // echoes that of the request Seq uint64; // echoes that of the request
Error string; // error, if any. Error string; // error, if any.
} }
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);
......
...@@ -12,20 +12,20 @@ package runtime ...@@ -12,20 +12,20 @@ package runtime
// Gosched yields the processor, allowing other goroutines to run. It does not // Gosched yields the processor, allowing other goroutines to run. It does not
// suspend the current goroutine, so execution resumes automatically. // suspend the current goroutine, so execution resumes automatically.
func Gosched() func Gosched()
// Goexit terminates the goroutine that calls it. No other goroutine is affected. // Goexit terminates the goroutine that calls it. No other goroutine is affected.
func Goexit() func Goexit()
// Breakpoint() executes a breakpoint trap. // Breakpoint() executes a breakpoint trap.
func Breakpoint() func Breakpoint()
// Caller reports file and line number information about function invocations on // Caller reports file and line number information about function invocations on
// the calling goroutine's stack. The argument is the number of stack frames to // the calling goroutine's stack. The argument is the number of stack frames to
// ascend, with 1 identifying the the caller of Caller. The return values report the // ascend, with 1 identifying the the caller of Caller. The return values report the
// program counter, file name, and line number within the file of the corresponding // program counter, file name, and line number within the file of the corresponding
// call. The boolean ok is false if it was not possible to recover the information. // call. The boolean ok is false if it was not possible to recover the information.
func Caller(n int) (pc uintptr, file string, line int, ok bool) func Caller(n int) (pc uintptr, file string, line int, ok bool)
// mid returns the current os thread (m) id. // mid returns the current os thread (m) id.
func mid() uint32 func mid() uint32
......
...@@ -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));
}
...@@ -87,7 +87,7 @@ func TestSortLarge_Random(t *testing.T) { ...@@ -87,7 +87,7 @@ func TestSortLarge_Random(t *testing.T) {
} }
const ( const (
_Sawtooth = iota; _Sawtooth = iota;
_Rand; _Rand;
_Stagger; _Stagger;
_Plateau; _Plateau;
...@@ -96,7 +96,7 @@ const ( ...@@ -96,7 +96,7 @@ const (
) )
const ( const (
_Copy = iota; _Copy = iota;
_Reverse; _Reverse;
_ReverseFirstHalf; _ReverseFirstHalf;
_ReverseSecondHalf; _ReverseSecondHalf;
...@@ -106,15 +106,19 @@ const ( ...@@ -106,15 +106,19 @@ const (
) )
type testingData struct { type testingData struct {
desc string; desc string;
t *testing.T; t *testing.T;
data []int; data []int;
maxswap int; // number of swaps allowed maxswap int; // number of swaps allowed
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;
} }
...@@ -5,91 +5,91 @@ ...@@ -5,91 +5,91 @@
package strconv_test package strconv_test
import ( import (
"os"; "os";
"reflect"; "reflect";
. "strconv"; . "strconv";
"testing"; "testing";
) )
type atofTest struct { type atofTest struct {
in string; in string;
out string; out string;
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};
} }
} }
} }
......
...@@ -7,8 +7,8 @@ package strconv ...@@ -7,8 +7,8 @@ package strconv
import "os" import "os"
type NumError struct { type NumError struct {
Num string; Num string;
Error os.Error; Error os.Error;
} }
func (e *NumError) String() string { func (e *NumError) String() string {
...@@ -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;
} }
...@@ -5,19 +5,19 @@ ...@@ -5,19 +5,19 @@
package strconv_test package strconv_test
import ( import (
"os"; "os";
"reflect"; "reflect";
. "strconv"; . "strconv";
"testing"; "testing";
) )
type atoui64Test struct { type atoui64Test struct {
in string; in string;
out uint64; out uint64;
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,24 +27,24 @@ var atoui64tests = []atoui64Test { ...@@ -27,24 +27,24 @@ 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},
} }
type atoi64Test struct { type atoi64Test struct {
in string; in string;
out int64; out int64;
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,21 +60,21 @@ var atoi64tests = []atoi64Test { ...@@ -60,21 +60,21 @@ 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 {
in string; in string;
out uint32; out uint32;
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,17 +84,17 @@ var atoui32tests = []atoui32Test { ...@@ -84,17 +84,17 @@ 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 {
in string; in string;
out int32; out int32;
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) {
} }
} }
} }
...@@ -5,27 +5,28 @@ ...@@ -5,27 +5,28 @@
package strconv_test package strconv_test
import ( import (
. "strconv"; . "strconv";
"testing"; "testing";
) )
type shiftTest struct { type shiftTest struct {
i uint64; i uint64;
shift int; shift int;
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) {
...@@ -40,28 +41,28 @@ func TestDecimalShift(t *testing.T) { ...@@ -40,28 +41,28 @@ func TestDecimalShift(t *testing.T) {
} }
type roundTest struct { type roundTest struct {
i uint64; i uint64;
nd int; nd int;
down, round, up string; down, round, up string;
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) {
...@@ -86,22 +87,22 @@ func TestDecimalRound(t *testing.T) { ...@@ -86,22 +87,22 @@ func TestDecimalRound(t *testing.T) {
} }
type roundIntTest struct { type roundIntTest struct {
i uint64; i uint64;
shift int; shift int;
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 {
......
...@@ -5,98 +5,100 @@ ...@@ -5,98 +5,100 @@
package strconv_test package strconv_test
import ( import (
"math"; "math";
. "strconv"; . "strconv";
"testing"; "testing";
) )
type ftoaTest struct { type ftoaTest struct {
f float64; f float64;
fmt byte; fmt byte;
prec int; prec int;
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 {
......
...@@ -5,56 +5,56 @@ ...@@ -5,56 +5,56 @@
package strconv_test package strconv_test
import ( import (
. "strconv"; . "strconv";
"testing"; "testing";
) )
type itob64Test struct { type itob64Test struct {
in int64; in int64;
base uint; base uint;
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) {
...@@ -80,7 +80,7 @@ func TestItoa(t *testing.T) { ...@@ -80,7 +80,7 @@ func TestItoa(t *testing.T) {
test.in, test.base, s, test.out); test.in, test.base, s, test.out);
} }
if test.in >= 0 { if test.in >= 0 {
s := Uitob(uint(test.in), test.base); s := Uitob(uint(test.in), test.base);
if s != test.out { if s != test.out {
t.Errorf("Uitob(%v, %v) = %v want %v\n", t.Errorf("Uitob(%v, %v) = %v want %v\n",
...@@ -124,17 +124,17 @@ func TestItoa(t *testing.T) { ...@@ -124,17 +124,17 @@ func TestItoa(t *testing.T) {
} }
type uitob64Test struct { type uitob64Test struct {
in uint64; in uint64;
base uint; base uint;
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,18 +89,18 @@ func unhex(b byte) (v int, ok bool) { ...@@ -89,18 +89,18 @@ 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;
} }
// UnquoteChar decodes the first character or byte in the escaped string // UnquoteChar decodes the first character or byte in the escaped string
// or character literal represented by the string s. // or character literal represented by the string s.
// It returns four values: // It returns four values:
// 1) value, the decoded Unicode code point or byte value; // 1) value, the decoded Unicode code point or byte value;
// 2) multibyte, a boolean indicating whether the decoded character // 2) multibyte, a boolean indicating whether the decoded character
// requires a multibyte UTF-8 representation; // requires a multibyte UTF-8 representation;
...@@ -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 {
...@@ -223,7 +223,7 @@ func UnquoteChar(s string, quote byte) (value int, multibyte bool, tail string, ...@@ -223,7 +223,7 @@ func UnquoteChar(s string, quote byte) (value int, multibyte bool, tail string,
// character literal; Unquote returns the corresponding // character literal; Unquote returns the corresponding
// one-character string.) // one-character string.)
func Unquote(s string) (t string, err os.Error) { func Unquote(s string) (t string, err os.Error) {
err = os.EINVAL; // assume error for easy return err = os.EINVAL; // assume error for easy return
n := len(s); n := len(s);
if n < 2 { if n < 2 {
return; return;
...@@ -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;
} }
...@@ -5,23 +5,23 @@ ...@@ -5,23 +5,23 @@
package strconv_test package strconv_test
import ( import (
"os"; "os";
. "strconv"; . "strconv";
"testing"; "testing";
) )
type quoteTest struct { type quoteTest struct {
in string; in string;
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) {
...@@ -34,49 +34,49 @@ func TestQuote(t *testing.T) { ...@@ -34,49 +34,49 @@ func TestQuote(t *testing.T) {
} }
type canBackquoteTest struct { type canBackquoteTest struct {
in string; in string;
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`,
......
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
package strings_test package strings_test
import ( import (
. "strings"; . "strings";
"testing"; "testing";
"unicode"; "unicode";
"utf8"; "utf8";
) )
func eq(a, b []string) bool { func eq(a, b []string) bool {
...@@ -23,18 +23,18 @@ func eq(a, b []string) bool { ...@@ -23,18 +23,18 @@ 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;
sep string; sep string;
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},
...@@ -84,15 +84,17 @@ func TestLastIndex(t *testing.T) { ...@@ -84,15 +84,17 @@ func TestLastIndex(t *testing.T) {
type ExplodeTest struct { type ExplodeTest struct {
s string; s string;
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);
...@@ -108,25 +110,27 @@ func TestExplode(t *testing.T) { ...@@ -108,25 +110,27 @@ func TestExplode(t *testing.T) {
} }
type SplitTest struct { type SplitTest struct {
s string; s string;
sep string; sep string;
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);
} }
...@@ -16,8 +16,8 @@ func semrelease(*int32) ...@@ -16,8 +16,8 @@ func semrelease(*int32)
// Mutexes can be created as part of other structures; // Mutexes can be created as part of other structures;
// the zero value for a Mutex is an unlocked mutex. // the zero value for a Mutex is an unlocked mutex.
type Mutex struct { type Mutex struct {
key int32; key int32;
sema int32; sema int32;
} }
func xadd(val *int32, delta int32) (new int32) { func xadd(val *int32, delta int32) (new int32) {
...@@ -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();
} }
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
package sync_test 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;
} }
} }
...@@ -11,8 +11,8 @@ import ( ...@@ -11,8 +11,8 @@ import (
) )
type writeLogger struct { type writeLogger struct {
prefix string; prefix string;
w io.Writer; w io.Writer;
} }
func (l *writeLogger) Write(p []byte) (n int, err os.Error) { func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
...@@ -29,12 +29,12 @@ func (l *writeLogger) Write(p []byte) (n int, err os.Error) { ...@@ -29,12 +29,12 @@ 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 {
prefix string; prefix string;
r io.Reader; r io.Reader;
} }
func (l *readLogger) Read(p []byte) (n int, err os.Error) { 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) { ...@@ -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]);
} }
...@@ -52,9 +52,9 @@ func DataErrReader(r io.Reader) io.Reader { ...@@ -52,9 +52,9 @@ func DataErrReader(r io.Reader) io.Reader {
} }
type dataErrReader struct { type dataErrReader struct {
r io.Reader; r io.Reader;
unread []byte; unread []byte;
data []byte; data []byte;
} }
func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { 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) { ...@@ -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;
} }
...@@ -16,13 +16,13 @@ func TruncateWriter(w io.Writer, n int64) io.Writer { ...@@ -16,13 +16,13 @@ func TruncateWriter(w io.Writer, n int64) io.Writer {
} }
type truncateWriter struct { type truncateWriter struct {
w io.Writer; w io.Writer;
n int64; n int64;
} }
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.
...@@ -103,8 +103,8 @@ func (t *T) Fatalf(format string, args ...) { ...@@ -103,8 +103,8 @@ func (t *T) Fatalf(format string, args ...) {
// An internal type but exported because it is cross-package; part of the implementation // An internal type but exported because it is cross-package; part of the implementation
// of gotest. // of gotest.
type Test struct { type Test struct {
Name string; Name string;
F func(*T); F func(*T);
} }
func tRunner(t *T, test *Test) { func tRunner(t *T, test *Test) {
......
...@@ -23,14 +23,14 @@ package time ...@@ -23,14 +23,14 @@ package time
// A Ticker holds a synchronous channel that delivers `ticks' of a clock // A Ticker holds a synchronous channel that delivers `ticks' of a clock
// at intervals. // at intervals.
type Ticker struct { type Ticker struct {
C <-chan int64; // The channel on which the ticks are delivered. C <-chan int64; // The channel on which the ticks are delivered.
ns int64; ns int64;
shutdown bool; shutdown bool;
} }
// 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};
......
...@@ -5,15 +5,15 @@ ...@@ -5,15 +5,15 @@
package time_test package time_test
import ( import (
"testing"; "testing";
. "time"; . "time";
) )
func TestTicker(t *testing.T) { 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,12 +27,12 @@ func Nanoseconds() int64 { ...@@ -27,12 +27,12 @@ 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.
const ( const (
Sunday = iota; Sunday = iota;
Monday; Monday;
Tuesday; Tuesday;
Wednesday; Wednesday;
...@@ -43,36 +43,30 @@ const ( ...@@ -43,36 +43,30 @@ const (
// Time is the struct representing a parsed time value. // Time is the struct representing a parsed time value.
type Time struct { type Time struct {
Year int64; // 2008 is 2008 Year int64; // 2008 is 2008
Month, Day int; // Sep-17 is 9, 17 Month, Day int; // Sep-17 is 9, 17
Hour, Minute, Second int; // 10:43:12 is 10, 43, 12 Hour, Minute, Second int; // 10:43:12 is 10, 43, 12
Weekday int; // Sunday, Monday, ... Weekday int; // Sunday, Monday, ...
ZoneOffset int; // seconds east of UTC ZoneOffset int; // seconds east of UTC
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,19 +12,18 @@ package time ...@@ -12,19 +12,18 @@ 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/";
) )
// Simple I/O interface to binary blob of data. // Simple I/O interface to binary blob of data.
type data struct { type data struct {
p []byte; p []byte;
error bool; error bool;
} }
...@@ -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,23 +61,23 @@ func (d *data) byte() (n byte, ok bool) { ...@@ -62,23 +61,23 @@ 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
type zone struct { type zone struct {
utcoff int; utcoff int;
isdst bool; isdst bool;
name string; name string;
} }
type zonetime struct { type zonetime struct {
time int32; // transition time, in seconds since 1970 GMT time int32; // transition time, in seconds since 1970 GMT
zone *zone; // the zone that goes into effect at that time zone *zone; // the zone that goes into effect at that time
isstd, isutc bool; // ignored - no idea what these mean isstd, isutc bool; // ignored - no idea what these mean
} }
func parseinfo(bytes []byte) (zt []zonetime, ok bool) { func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
...@@ -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:
...@@ -103,18 +102,18 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) { ...@@ -103,18 +102,18 @@ func parseinfo(bytes []byte) (zt []zonetime, ok bool) {
// number of local time zones // number of local time zones
// number of characters of time zone abbrev strings // number of characters of time zone abbrev strings
const ( const (
NUTCLocal = iota; NUTCLocal = iota;
NStdWall; NStdWall;
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,16 +215,16 @@ func setupZone() { ...@@ -216,16 +215,16 @@ 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
} }
} }
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);
} }
...@@ -5,11 +5,11 @@ ...@@ -5,11 +5,11 @@
package unicode_test package unicode_test
import ( import (
"testing"; "testing";
. "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);
} }
} }
} }
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
package unicode package unicode
const ( const (
MaxRune = 0x10FFFF; // Maximum valid Unicode code point. MaxRune = 0x10FFFF; // Maximum valid Unicode code point.
ReplacementChar = 0xFFFD; // Represents invalid code points. ReplacementChar = 0xFFFD; // Represents invalid code points.
) )
...@@ -36,18 +36,19 @@ type CaseRange struct { ...@@ -36,18 +36,19 @@ type CaseRange struct {
// Indices into the Delta arrays inside CaseRanges for case mapping. // Indices into the Delta arrays inside CaseRanges for case mapping.
const ( const (
UpperCase = iota; UpperCase = iota;
LowerCase; LowerCase;
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);
} }
...@@ -5,8 +5,8 @@ ...@@ -5,8 +5,8 @@
package unicode_test package unicode_test
import ( import (
"testing"; "testing";
. "unicode"; . "unicode";
) )
var upperTest = []int{ var upperTest = []int{
...@@ -107,110 +107,110 @@ var spaceTest = []int{ ...@@ -107,110 +107,110 @@ 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},
caseT{UpperCase, 1<<30, 1<<30}, caseT{UpperCase, 1<<30, 1<<30},
// ASCII (special-cased so test carefully) // ASCII (special-cased so test carefully)
caseT{UpperCase, '\n', '\n'}, caseT{UpperCase, '\n', '\n'},
caseT{UpperCase, 'a', 'A'}, caseT{UpperCase, 'a', 'A'},
caseT{UpperCase, 'A', 'A'}, caseT{UpperCase, 'A', 'A'},
caseT{UpperCase, '7', '7'}, caseT{UpperCase, '7', '7'},
caseT{LowerCase, '\n', '\n'}, caseT{LowerCase, '\n', '\n'},
caseT{LowerCase, 'a', 'a'}, caseT{LowerCase, 'a', 'a'},
caseT{LowerCase, 'A', 'a'}, caseT{LowerCase, 'A', 'a'},
caseT{LowerCase, '7', '7'}, caseT{LowerCase, '7', '7'},
caseT{TitleCase, '\n', '\n'}, caseT{TitleCase, '\n', '\n'},
caseT{TitleCase, 'a', 'A'}, caseT{TitleCase, 'a', 'A'},
caseT{TitleCase, 'A', 'A'}, caseT{TitleCase, 'A', 'A'},
caseT{TitleCase, '7', '7'}, caseT{TitleCase, '7', '7'},
// Latin-1: easy to read the tests! // Latin-1: easy to read the tests!
caseT{UpperCase, 0x80, 0x80}, caseT{UpperCase, 0x80, 0x80},
caseT{UpperCase, 'Å', 'Å'}, caseT{UpperCase, 'Å', 'Å'},
caseT{UpperCase, 'å', 'Å'}, caseT{UpperCase, 'å', 'Å'},
caseT{LowerCase, 0x80, 0x80}, caseT{LowerCase, 0x80, 0x80},
caseT{LowerCase, 'Å', 'å'}, caseT{LowerCase, 'Å', 'å'},
caseT{LowerCase, 'å', 'å'}, caseT{LowerCase, 'å', 'å'},
caseT{TitleCase, 0x80, 0x80}, caseT{TitleCase, 0x80, 0x80},
caseT{TitleCase, 'Å', 'Å'}, caseT{TitleCase, 'Å', 'Å'},
caseT{TitleCase, 'å', 'Å'}, caseT{TitleCase, 'å', 'Å'},
// 0131;LATIN SMALL LETTER DOTLESS I;Ll;0;L;;;;;N;;;0049;;0049 // 0131;LATIN SMALL LETTER DOTLESS I;Ll;0;L;;;;;N;;;0049;;0049
caseT{UpperCase, 0x0131, 'I'}, caseT{UpperCase, 0x0131, 'I'},
caseT{LowerCase, 0x0131, 0x0131}, caseT{LowerCase, 0x0131, 0x0131},
caseT{TitleCase, 0x0131, 'I'}, caseT{TitleCase, 0x0131, 'I'},
// 0133;LATIN SMALL LIGATURE IJ;Ll;0;L;<compat> 0069 006A;;;;N;LATIN SMALL LETTER I J;;0132;;0132 // 0133;LATIN SMALL LIGATURE IJ;Ll;0;L;<compat> 0069 006A;;;;N;LATIN SMALL LETTER I J;;0132;;0132
caseT{UpperCase, 0x0133, 0x0132}, caseT{UpperCase, 0x0133, 0x0132},
caseT{LowerCase, 0x0133, 0x0133}, caseT{LowerCase, 0x0133, 0x0133},
caseT{TitleCase, 0x0133, 0x0132}, caseT{TitleCase, 0x0133, 0x0132},
// 212A;KELVIN SIGN;Lu;0;L;004B;;;;N;DEGREES KELVIN;;;006B; // 212A;KELVIN SIGN;Lu;0;L;004B;;;;N;DEGREES KELVIN;;;006B;
caseT{UpperCase, 0x212A, 0x212A}, caseT{UpperCase, 0x212A, 0x212A},
caseT{LowerCase, 0x212A, 'k'}, caseT{LowerCase, 0x212A, 'k'},
caseT{TitleCase, 0x212A, 0x212A}, caseT{TitleCase, 0x212A, 0x212A},
// From an UpperLower sequence // From an UpperLower sequence
// A640;CYRILLIC CAPITAL LETTER ZEMLYA;Lu;0;L;;;;;N;;;;A641; // A640;CYRILLIC CAPITAL LETTER ZEMLYA;Lu;0;L;;;;;N;;;;A641;
caseT{UpperCase, 0xA640, 0xA640}, caseT{UpperCase, 0xA640, 0xA640},
caseT{LowerCase, 0xA640, 0xA641}, caseT{LowerCase, 0xA640, 0xA641},
caseT{TitleCase, 0xA640, 0xA640}, caseT{TitleCase, 0xA640, 0xA640},
// A641;CYRILLIC SMALL LETTER ZEMLYA;Ll;0;L;;;;;N;;;A640;;A640 // A641;CYRILLIC SMALL LETTER ZEMLYA;Ll;0;L;;;;;N;;;A640;;A640
caseT{UpperCase, 0xA641, 0xA640}, caseT{UpperCase, 0xA641, 0xA640},
caseT{LowerCase, 0xA641, 0xA641}, caseT{LowerCase, 0xA641, 0xA641},
caseT{TitleCase, 0xA641, 0xA640}, caseT{TitleCase, 0xA641, 0xA640},
// A64E;CYRILLIC CAPITAL LETTER NEUTRAL YER;Lu;0;L;;;;;N;;;;A64F; // A64E;CYRILLIC CAPITAL LETTER NEUTRAL YER;Lu;0;L;;;;;N;;;;A64F;
caseT{UpperCase, 0xA64E, 0xA64E}, caseT{UpperCase, 0xA64E, 0xA64E},
caseT{LowerCase, 0xA64E, 0xA64F}, caseT{LowerCase, 0xA64E, 0xA64F},
caseT{TitleCase, 0xA64E, 0xA64E}, caseT{TitleCase, 0xA64E, 0xA64E},
// A65F;CYRILLIC SMALL LETTER YN;Ll;0;L;;;;;N;;;A65E;;A65E // A65F;CYRILLIC SMALL LETTER YN;Ll;0;L;;;;;N;;;A65E;;A65E
caseT{UpperCase, 0xA65F, 0xA65E}, caseT{UpperCase, 0xA65F, 0xA65E},
caseT{LowerCase, 0xA65F, 0xA65F}, caseT{LowerCase, 0xA65F, 0xA65F},
caseT{TitleCase, 0xA65F, 0xA65E}, caseT{TitleCase, 0xA65F, 0xA65E},
// From another UpperLower sequence // From another UpperLower sequence
// 0139;LATIN CAPITAL LETTER L WITH ACUTE;Lu;0;L;004C 0301;;;;N;LATIN CAPITAL LETTER L ACUTE;;;013A; // 0139;LATIN CAPITAL LETTER L WITH ACUTE;Lu;0;L;004C 0301;;;;N;LATIN CAPITAL LETTER L ACUTE;;;013A;
caseT{UpperCase, 0x0139, 0x0139}, caseT{UpperCase, 0x0139, 0x0139},
caseT{LowerCase, 0x0139, 0x013A}, caseT{LowerCase, 0x0139, 0x013A},
caseT{TitleCase, 0x0139, 0x0139}, caseT{TitleCase, 0x0139, 0x0139},
// 013F;LATIN CAPITAL LETTER L WITH MIDDLE DOT;Lu;0;L;<compat> 004C 00B7;;;;N;;;;0140; // 013F;LATIN CAPITAL LETTER L WITH MIDDLE DOT;Lu;0;L;<compat> 004C 00B7;;;;N;;;;0140;
caseT{UpperCase, 0x013f, 0x013f}, caseT{UpperCase, 0x013f, 0x013f},
caseT{LowerCase, 0x013f, 0x0140}, caseT{LowerCase, 0x013f, 0x0140},
caseT{TitleCase, 0x013f, 0x013f}, caseT{TitleCase, 0x013f, 0x013f},
// 0148;LATIN SMALL LETTER N WITH CARON;Ll;0;L;006E 030C;;;;N;LATIN SMALL LETTER N HACEK;;0147;;0147 // 0148;LATIN SMALL LETTER N WITH CARON;Ll;0;L;006E 030C;;;;N;LATIN SMALL LETTER N HACEK;;0147;;0147
caseT{UpperCase, 0x0148, 0x0147}, caseT{UpperCase, 0x0148, 0x0147},
caseT{LowerCase, 0x0148, 0x0148}, caseT{LowerCase, 0x0148, 0x0148},
caseT{TitleCase, 0x0148, 0x0147}, caseT{TitleCase, 0x0148, 0x0147},
// Last block in the 5.1.0 table // Last block in the 5.1.0 table
// 10400;DESERET CAPITAL LETTER LONG I;Lu;0;L;;;;;N;;;;10428; // 10400;DESERET CAPITAL LETTER LONG I;Lu;0;L;;;;;N;;;;10428;
caseT{UpperCase, 0x10400, 0x10400}, caseT{UpperCase, 0x10400, 0x10400},
caseT{LowerCase, 0x10400, 0x10428}, caseT{LowerCase, 0x10400, 0x10428},
caseT{TitleCase, 0x10400, 0x10400}, caseT{TitleCase, 0x10400, 0x10400},
// 10427;DESERET CAPITAL LETTER EW;Lu;0;L;;;;;N;;;;1044F; // 10427;DESERET CAPITAL LETTER EW;Lu;0;L;;;;;N;;;;1044F;
caseT{UpperCase, 0x10427, 0x10427}, caseT{UpperCase, 0x10427, 0x10427},
caseT{LowerCase, 0x10427, 0x1044F}, caseT{LowerCase, 0x10427, 0x1044F},
caseT{TitleCase, 0x10427, 0x10427}, caseT{TitleCase, 0x10427, 0x10427},
// 10428;DESERET SMALL LETTER LONG I;Ll;0;L;;;;;N;;;10400;;10400 // 10428;DESERET SMALL LETTER LONG I;Ll;0;L;;;;;N;;;10400;;10400
caseT{UpperCase, 0x10428, 0x10400}, caseT{UpperCase, 0x10428, 0x10400},
caseT{LowerCase, 0x10428, 0x10428}, caseT{LowerCase, 0x10428, 0x10428},
caseT{TitleCase, 0x10428, 0x10400}, caseT{TitleCase, 0x10428, 0x10400},
// 1044F;DESERET SMALL LETTER EW;Ll;0;L;;;;;N;;;10427;;10427 // 1044F;DESERET SMALL LETTER EW;Ll;0;L;;;;;N;;;10427;;10427
caseT{UpperCase, 0x1044F, 0x10427}, caseT{UpperCase, 0x1044F, 0x10427},
caseT{LowerCase, 0x1044F, 0x1044F}, caseT{LowerCase, 0x1044F, 0x1044F},
caseT{TitleCase, 0x1044F, 0x10427}, caseT{TitleCase, 0x1044F, 0x10427},
// First one not in the 5.1.0 table // First one not in the 5.1.0 table
// 10450;SHAVIAN LETTER PEEP;Lo;0;L;;;;;N;;;;; // 10450;SHAVIAN LETTER PEEP;Lo;0;L;;;;;N;;;;;
caseT{UpperCase, 0x10450, 0x10450}, caseT{UpperCase, 0x10450, 0x10450},
caseT{LowerCase, 0x10450, 0x10450}, caseT{LowerCase, 0x10450, 0x10450},
caseT{TitleCase, 0x10450, 0x10450}, caseT{TitleCase, 0x10450, 0x10450},
} }
func TestIsLetter(t *testing.T) { func TestIsLetter(t *testing.T) {
...@@ -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);
} }
} }
} }
...@@ -18,30 +18,30 @@ type ArbitraryType int ...@@ -18,30 +18,30 @@ type ArbitraryType int
// 3) A Pointer can be converted to a uintptr. // 3) A Pointer can be converted to a uintptr.
// Pointer therefore allows a program to defeat the type system and read and write // Pointer therefore allows a program to defeat the type system and read and write
// arbitrary memory. It should be used with extreme care. // arbitrary memory. It should be used with extreme care.
type Pointer *ArbitraryType type Pointer *ArbitraryType
// Sizeof returns the size in bytes occupied by the value v. The size is that of the // Sizeof returns the size in bytes occupied by the value v. The size is that of the
// "top level" of the value only. For instance, if v is a slice, it returns the size of // "top level" of the value only. For instance, if v is a slice, it returns the size of
// the slice descriptor, not the size of the memory referenced by the slice. // the slice descriptor, not the size of the memory referenced by the slice.
func Sizeof(v ArbitraryType) int func Sizeof(v ArbitraryType) int
// Offsetof returns the offset within the struct of the field represented by v, // Offsetof returns the offset within the struct of the field represented by v,
// which must be of the form struct_value.field. In other words, it returns the // which must be of the form struct_value.field. In other words, it returns the
// number of bytes between the start of the struct and the start of the field. // number of bytes between the start of the struct and the start of the field.
func Offsetof(v ArbitraryType) int func Offsetof(v ArbitraryType) int
// Alignof returns the alignment of the value v. It is the minimum value m such // Alignof returns the alignment of the value v. It is the minimum value m such
// that the address of a variable with the type of v will always always be zero mod m. // that the address of a variable with the type of v will always always be zero mod m.
// If v is of the form obj.f, it returns the alignment of field f within struct object obj. // If v is of the form obj.f, it returns the alignment of field f within struct object obj.
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{})
...@@ -5,50 +5,50 @@ ...@@ -5,50 +5,50 @@
package utf8_test package utf8_test
import ( import (
"bytes"; "bytes";
"strings"; "strings";
"testing"; "testing";
. "utf8"; . "utf8";
) )
type Utf8Map struct { type Utf8Map struct {
rune int; rune int;
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);
...@@ -145,15 +145,17 @@ func TestDecodeRune(t *testing.T) { ...@@ -145,15 +145,17 @@ func TestDecodeRune(t *testing.T) {
} }
type RuneCountTest struct { 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