- replaced gofmt expression formatting algorithm with

rsc's algorithm
- applied gofmt -w misc src
- partial CL (last chunk)

R=rsc, r
http://go/go-review/1024041
This commit is contained in:
Robert Griesemer 2009-11-09 21:23:52 -08:00
parent baba292998
commit 3bb0032cd6
121 changed files with 750 additions and 750 deletions

View file

@ -47,7 +47,7 @@ func update(a, b uint32, p []byte) (aa, bb uint32) {
a += uint32(p[i]); a += uint32(p[i]);
b += a; b += a;
// invariant: a <= b // invariant: a <= b
if b > (0xffffffff - 255)/2 { if b > (0xffffffff-255)/2 {
a %= mod; a %= mod;
b %= mod; b %= mod;
// invariant: a < mod && b < mod // invariant: a < mod && b < mod
@ -77,9 +77,9 @@ func (d *digest) Sum32() uint32 { return finish(d.a, d.b) }
func (d *digest) Sum() []byte { func (d *digest) Sum() []byte {
p := make([]byte, 4); p := make([]byte, 4);
s := d.Sum32(); s := d.Sum32();
p[0] = byte(s>>24); p[0] = byte(s >> 24);
p[1] = byte(s>>16); p[1] = byte(s >> 16);
p[2] = byte(s>>8); p[2] = byte(s >> 8);
p[3] = byte(s); p[3] = byte(s);
return p; return p;
} }

View file

@ -41,7 +41,7 @@ func MakeTable(poly uint32) *Table {
crc := uint32(i); crc := uint32(i);
for j := 0; j < 8; j++ { for j := 0; j < 8; j++ {
if crc&1 == 1 { if crc&1 == 1 {
crc = (crc>>1)^poly crc = (crc >> 1) ^ poly
} else { } else {
crc >>= 1 crc >>= 1
} }
@ -75,7 +75,7 @@ func (d *digest) Reset() { d.crc = 0 }
func update(crc uint32, tab *Table, p []byte) uint32 { func update(crc uint32, tab *Table, p []byte) uint32 {
crc = ^crc; crc = ^crc;
for i := 0; i < len(p); i++ { for i := 0; i < len(p); i++ {
crc = tab[byte(crc)^p[i]]^(crc>>8) crc = tab[byte(crc)^p[i]] ^ (crc >> 8)
} }
return ^crc; return ^crc;
} }
@ -90,9 +90,9 @@ func (d *digest) Sum32() uint32 { return d.crc }
func (d *digest) Sum() []byte { func (d *digest) Sum() []byte {
p := make([]byte, 4); p := make([]byte, 4);
s := d.Sum32(); s := d.Sum32();
p[0] = byte(s>>24); p[0] = byte(s >> 24);
p[1] = byte(s>>16); p[1] = byte(s >> 16);
p[2] = byte(s>>8); p[2] = byte(s >> 8);
p[3] = byte(s); p[3] = byte(s);
return p; return p;
} }

View file

@ -82,7 +82,7 @@ func ReadResponse(r *bufio.Reader) (*Response, os.Error) {
if len(f) < 3 { if len(f) < 3 {
return nil, &badStringError{"malformed HTTP response", line} return nil, &badStringError{"malformed HTTP response", line}
} }
resp.Status = f[1]+" "+f[2]; resp.Status = f[1] + " " + f[2];
resp.StatusCode, err = strconv.Atoi(f[1]); resp.StatusCode, err = strconv.Atoi(f[1]);
if err != nil { if err != nil {
return nil, &badStringError{"malformed HTTP status code", f[1]} return nil, &badStringError{"malformed HTTP status code", f[1]}

View file

@ -76,9 +76,9 @@ func serveFileInternal(c *Conn, r *Request, name string, redirect bool) {
const indexPage = "/index.html"; const indexPage = "/index.html";
// redirect to strip off any index.html // redirect to strip off any index.html
n := len(name)-len(indexPage); n := len(name) - len(indexPage);
if n >= 0 && name[n:len(name)] == indexPage { if n >= 0 && name[n:len(name)] == indexPage {
Redirect(c, name[0 : n+1], StatusMovedPermanently); Redirect(c, name[0:n+1], StatusMovedPermanently);
return; return;
} }
@ -108,7 +108,7 @@ func serveFileInternal(c *Conn, r *Request, name string, redirect bool) {
} }
} else { } else {
if url[len(url)-1] == '/' { if url[len(url)-1] == '/' {
Redirect(c, url[0 : len(url)-1], StatusMovedPermanently); Redirect(c, url[0:len(url)-1], StatusMovedPermanently);
return; return;
} }
} }
@ -177,5 +177,5 @@ func (f *fileHandler) ServeHTTP(c *Conn, r *Request) {
return; return;
} }
path = path[len(f.prefix):len(path)]; path = path[len(f.prefix):len(path)];
serveFileInternal(c, r, f.root + "/" + path, true); serveFileInternal(c, r, f.root+"/"+path, true);
} }

View file

@ -24,7 +24,7 @@ const (
maxLineLength = 1024; // assumed < bufio.DefaultBufSize maxLineLength = 1024; // assumed < bufio.DefaultBufSize
maxValueLength = 1024; maxValueLength = 1024;
maxHeaderLines = 1024; maxHeaderLines = 1024;
chunkSize = 4<<10; // 4 KB chunks chunkSize = 4 << 10; // 4 KB chunks
) )
// HTTP request parsing errors. // HTTP request parsing errors.
@ -293,7 +293,7 @@ func readKeyValue(b *bufio.Reader) (key, value string, err os.Error) {
if line, e = readLineBytes(b); e != nil { if line, e = readLineBytes(b); e != nil {
return "", "", e return "", "", e
} }
value += " "+string(line); value += " " + string(line);
if len(value) >= maxValueLength { if len(value) >= maxValueLength {
return "", "", &badStringError{"value too long for key", key} return "", "", &badStringError{"value too long for key", key}
@ -360,10 +360,10 @@ func CanonicalHeaderKey(s string) string {
upper := true; upper := true;
for i, v := range a { for i, v := range a {
if upper && 'a' <= v && v <= 'z' { if upper && 'a' <= v && v <= 'z' {
a[i] = v+'A'-'a' a[i] = v + 'A' - 'a'
} }
if !upper && 'A' <= v && v <= 'Z' { if !upper && 'A' <= v && v <= 'Z' {
a[i] = v+'a'-'A' a[i] = v + 'a' - 'A'
} }
upper = false; upper = false;
if v == '-' { if v == '-' {
@ -422,7 +422,7 @@ func (cr *chunkedReader) Read(b []uint8) (n int, err os.Error) {
} }
} }
if uint64(len(b)) > cr.n { if uint64(len(b)) > cr.n {
b = b[0 : cr.n] b = b[0:cr.n]
} }
n, cr.err = cr.r.Read(b); n, cr.err = cr.r.Read(b);
cr.n -= uint64(n); cr.n -= uint64(n);
@ -484,7 +484,7 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) {
// to concatenating the values separated by commas. // to concatenating the values separated by commas.
oldvalue, present := req.Header[key]; oldvalue, present := req.Header[key];
if present { if present {
req.Header[key] = oldvalue+","+value req.Header[key] = oldvalue + "," + value
} else { } else {
req.Header[key] = value req.Header[key] = value
} }

View file

@ -146,7 +146,7 @@ func (c *Conn) WriteHeader(code int) {
if !ok { if !ok {
text = "status code " + codestring text = "status code " + codestring
} }
io.WriteString(c.buf, proto + " " + codestring + " " + text + "\r\n"); io.WriteString(c.buf, proto+" "+codestring+" "+text+"\r\n");
for k, v := range c.header { for k, v := range c.header {
io.WriteString(c.buf, k+": "+v+"\r\n") io.WriteString(c.buf, k+": "+v+"\r\n")
} }
@ -366,7 +366,7 @@ func Redirect(c *Conn, url string, code int) {
if url == "" || url[0] != '/' { if url == "" || url[0] != '/' {
// make relative path absolute // make relative path absolute
olddir, _ := path.Split(oldpath); olddir, _ := path.Split(oldpath);
url = olddir+url; url = olddir + url;
} }
// clean up but preserve trailing slash // clean up but preserve trailing slash
@ -453,7 +453,7 @@ func cleanPath(p string) string {
return "/" return "/"
} }
if p[0] != '/' { if p[0] != '/' {
p = "/"+p p = "/" + p
} }
np := path.Clean(p); np := path.Clean(p);
// path.Clean removes trailing slash except for root; // path.Clean removes trailing slash except for root;
@ -504,7 +504,7 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) {
// If pattern is /tree/, insert permanent redirect for /tree. // If pattern is /tree/, insert permanent redirect for /tree.
n := len(pattern); n := len(pattern);
if n > 0 && pattern[n-1] == '/' { if n > 0 && pattern[n-1] == '/' {
mux.m[pattern[0 : n-1]] = RedirectHandler(pattern, StatusMovedPermanently) mux.m[pattern[0:n-1]] = RedirectHandler(pattern, StatusMovedPermanently)
} }
} }

View file

@ -37,11 +37,11 @@ func ishex(c byte) bool {
func unhex(c byte) byte { func unhex(c byte) byte {
switch { switch {
case '0' <= c && c <= '9': case '0' <= c && c <= '9':
return c-'0' return c - '0'
case 'a' <= c && c <= 'f': case 'a' <= c && c <= 'f':
return c-'a'+10 return c - 'a' + 10
case 'A' <= c && c <= 'F': case 'A' <= c && c <= 'F':
return c-'A'+10 return c - 'A' + 10
} }
return 0; return 0;
} }
@ -97,7 +97,7 @@ func URLUnescape(s string) (string, os.Error) {
return s, nil return s, nil
} }
t := make([]byte, len(s) - 2*n); t := make([]byte, len(s)-2*n);
j := 0; j := 0;
for i := 0; i < len(s); { for i := 0; i < len(s); {
switch s[i] { switch s[i] {
@ -136,7 +136,7 @@ func URLEscape(s string) string {
return s return s
} }
t := make([]byte, len(s) + 2*hexCount); t := make([]byte, len(s)+2*hexCount);
j := 0; j := 0;
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
switch c := s[i]; { switch c := s[i]; {

View file

@ -18,17 +18,17 @@ type RGBAColor struct {
func (c RGBAColor) RGBA() (r, g, b, a uint32) { func (c RGBAColor) RGBA() (r, g, b, a uint32) {
r = uint32(c.R); r = uint32(c.R);
r |= r<<8; r |= r << 8;
r |= r<<16; r |= r << 16;
g = uint32(c.G); g = uint32(c.G);
g |= g<<8; g |= g << 8;
g |= g<<16; g |= g << 16;
b = uint32(c.B); b = uint32(c.B);
b |= b<<8; b |= b << 8;
b |= b<<16; b |= b << 16;
a = uint32(c.A); a = uint32(c.A);
a |= a<<8; a |= a << 8;
a |= a<<16; a |= a << 16;
return; return;
} }
@ -39,13 +39,13 @@ type RGBA64Color struct {
func (c RGBA64Color) RGBA() (r, g, b, a uint32) { func (c RGBA64Color) RGBA() (r, g, b, a uint32) {
r = uint32(c.R); r = uint32(c.R);
r |= r<<16; r |= r << 16;
g = uint32(c.G); g = uint32(c.G);
g |= g<<16; g |= g << 16;
b = uint32(c.B); b = uint32(c.B);
b |= b<<16; b |= b << 16;
a = uint32(c.A); a = uint32(c.A);
a |= a<<16; a |= a << 16;
return; return;
} }
@ -56,23 +56,23 @@ type NRGBAColor struct {
func (c NRGBAColor) RGBA() (r, g, b, a uint32) { func (c NRGBAColor) RGBA() (r, g, b, a uint32) {
r = uint32(c.R); r = uint32(c.R);
r |= r<<8; r |= r << 8;
r *= uint32(c.A); r *= uint32(c.A);
r /= 0xff; r /= 0xff;
r |= r<<16; r |= r << 16;
g = uint32(c.G); g = uint32(c.G);
g |= g<<8; g |= g << 8;
g *= uint32(c.A); g *= uint32(c.A);
g /= 0xff; g /= 0xff;
g |= g<<16; g |= g << 16;
b = uint32(c.B); b = uint32(c.B);
b |= b<<8; b |= b << 8;
b *= uint32(c.A); b *= uint32(c.A);
b /= 0xff; b /= 0xff;
b |= b<<16; b |= b << 16;
a = uint32(c.A); a = uint32(c.A);
a |= a<<8; a |= a << 8;
a |= a<<16; a |= a << 16;
return; return;
} }
@ -85,18 +85,18 @@ func (c NRGBA64Color) RGBA() (r, g, b, a uint32) {
r = uint32(c.R); r = uint32(c.R);
r *= uint32(c.A); r *= uint32(c.A);
r /= 0xffff; r /= 0xffff;
r |= r<<16; r |= r << 16;
g = uint32(c.G); g = uint32(c.G);
g *= uint32(c.A); g *= uint32(c.A);
g /= 0xffff; g /= 0xffff;
g |= g<<16; g |= g << 16;
b = uint32(c.B); b = uint32(c.B);
b *= uint32(c.A); b *= uint32(c.A);
b /= 0xffff; b /= 0xffff;
b |= b<<16; b |= b << 16;
a = uint32(c.A); a = uint32(c.A);
a |= a<<8; a |= a << 8;
a |= a<<16; a |= a << 16;
return; return;
} }
@ -121,7 +121,7 @@ func toRGBAColor(c Color) Color {
return c return c
} }
r, g, b, a := c.RGBA(); r, g, b, a := c.RGBA();
return RGBAColor{uint8(r>>24), uint8(g>>24), uint8(b>>24), uint8(a>>24)}; return RGBAColor{uint8(r >> 24), uint8(g >> 24), uint8(b >> 24), uint8(a >> 24)};
} }
func toRGBA64Color(c Color) Color { func toRGBA64Color(c Color) Color {
@ -129,7 +129,7 @@ func toRGBA64Color(c Color) Color {
return c return c
} }
r, g, b, a := c.RGBA(); r, g, b, a := c.RGBA();
return RGBA64Color{uint16(r>>16), uint16(g>>16), uint16(b>>16), uint16(a>>16)}; return RGBA64Color{uint16(r >> 16), uint16(g >> 16), uint16(b >> 16), uint16(a >> 16)};
} }
func toNRGBAColor(c Color) Color { func toNRGBAColor(c Color) Color {
@ -139,7 +139,7 @@ func toNRGBAColor(c Color) Color {
r, g, b, a := c.RGBA(); r, g, b, a := c.RGBA();
a >>= 16; a >>= 16;
if a == 0xffff { if a == 0xffff {
return NRGBAColor{uint8(r>>24), uint8(g>>24), uint8(b>>24), 0xff} return NRGBAColor{uint8(r >> 24), uint8(g >> 24), uint8(b >> 24), 0xff}
} }
if a == 0 { if a == 0 {
return NRGBAColor{0, 0, 0, 0} return NRGBAColor{0, 0, 0, 0}
@ -148,10 +148,10 @@ func toNRGBAColor(c Color) Color {
g >>= 16; g >>= 16;
b >>= 16; b >>= 16;
// Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a.
r = (r*0xffff)/a; r = (r * 0xffff) / a;
g = (g*0xffff)/a; g = (g * 0xffff) / a;
b = (b*0xffff)/a; b = (b * 0xffff) / a;
return NRGBAColor{uint8(r>>8), uint8(g>>8), uint8(b>>8), uint8(a>>8)}; return NRGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)};
} }
func toNRGBA64Color(c Color) Color { func toNRGBA64Color(c Color) Color {
@ -170,9 +170,9 @@ func toNRGBA64Color(c Color) Color {
return NRGBA64Color{0, 0, 0, 0} return NRGBA64Color{0, 0, 0, 0}
} }
// Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a.
r = (r*0xffff)/a; r = (r * 0xffff) / a;
g = (g*0xffff)/a; g = (g * 0xffff) / a;
b = (b*0xffff)/a; b = (b * 0xffff) / a;
return NRGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)}; return NRGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)};
} }

View file

@ -140,9 +140,9 @@ type PalettedColorModel []Color
func diff(a, b uint32) uint32 { func diff(a, b uint32) uint32 {
if a > b { if a > b {
return a-b return a - b
} }
return b-a; return b - a;
} }
// Convert returns the palette color closest to c in Euclidean R,G,B space. // Convert returns the palette color closest to c in Euclidean R,G,B space.
@ -166,7 +166,7 @@ func (p PalettedColorModel) Convert(c Color) Color {
vg >>= 17; vg >>= 17;
vb >>= 17; vb >>= 17;
dr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb); dr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb);
ssd := (dr*dr)+(dg*dg)+(db*db); ssd := (dr * dr) + (dg * dg) + (db * db);
if ssd < bestSSD { if ssd < bestSSD {
bestSSD = ssd; bestSSD = ssd;
result = v; result = v;

View file

@ -57,7 +57,7 @@ type decoder struct {
stage int; stage int;
idatWriter io.WriteCloser; idatWriter io.WriteCloser;
idatDone chan os.Error; idatDone chan os.Error;
tmp [3*256]byte; tmp [3 * 256]byte;
} }
// A FormatError reports that the input is not a valid PNG. // A FormatError reports that the input is not a valid PNG.
@ -118,7 +118,7 @@ func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Erro
if w < 0 || h < 0 { if w < 0 || h < 0 {
return FormatError("negative dimension") return FormatError("negative dimension")
} }
nPixels := int64(w)*int64(h); nPixels := int64(w) * int64(h);
if nPixels != int64(int(nPixels)) { if nPixels != int64(int(nPixels)) {
return UnsupportedError("dimension overflow") return UnsupportedError("dimension overflow")
} }
@ -138,11 +138,11 @@ func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Erro
} }
func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Error { func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Error {
np := int(length/3); // The number of palette entries. np := int(length / 3); // The number of palette entries.
if length%3 != 0 || np <= 0 || np > 256 { if length%3 != 0 || np <= 0 || np > 256 {
return FormatError("bad PLTE length") return FormatError("bad PLTE length")
} }
n, err := io.ReadFull(r, d.tmp[0 : 3*np]); n, err := io.ReadFull(r, d.tmp[0:3*np]);
if err != nil { if err != nil {
return err return err
} }
@ -151,7 +151,7 @@ func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Erro
case ctPaletted: case ctPaletted:
palette := make([]image.Color, np); palette := make([]image.Color, np);
for i := 0; i < np; i++ { for i := 0; i < np; i++ {
palette[i] = image.RGBAColor{d.tmp[3*i + 0], d.tmp[3*i + 1], d.tmp[3*i + 2], 0xff} palette[i] = image.RGBAColor{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff}
} }
d.image.(*image.Paletted).Palette = image.PalettedColorModel(palette); d.image.(*image.Paletted).Palette = image.PalettedColorModel(palette);
case ctTrueColor, ctTrueColorAlpha: case ctTrueColor, ctTrueColorAlpha:
@ -166,10 +166,10 @@ func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Erro
// The Paeth filter function, as per the PNG specification. // The Paeth filter function, as per the PNG specification.
func paeth(a, b, c uint8) uint8 { func paeth(a, b, c uint8) uint8 {
p := int(a)+int(b)-int(c); p := int(a) + int(b) - int(c);
pa := abs(p-int(a)); pa := abs(p - int(a));
pb := abs(p-int(b)); pb := abs(p - int(b));
pc := abs(p-int(c)); pc := abs(p - int(c));
if pa <= pb && pa <= pc { if pa <= pb && pa <= pc {
return a return a
} else if pb <= pc { } else if pb <= pc {
@ -198,15 +198,15 @@ func (d *decoder) idatReader(idat io.Reader) os.Error {
case ctPaletted: case ctPaletted:
bpp = 1; bpp = 1;
paletted = d.image.(*image.Paletted); paletted = d.image.(*image.Paletted);
maxPalette = uint8(len(paletted.Palette)-1); maxPalette = uint8(len(paletted.Palette) - 1);
case ctTrueColorAlpha: case ctTrueColorAlpha:
bpp = 4; bpp = 4;
nrgba = d.image.(*image.NRGBA); nrgba = d.image.(*image.NRGBA);
} }
// cr and pr are the bytes for the current and previous row. // cr and pr are the bytes for the current and previous row.
// The +1 is for the per-row filter type, which is at cr[0]. // The +1 is for the per-row filter type, which is at cr[0].
cr := make([]uint8, 1 + bpp * d.width); cr := make([]uint8, 1+bpp*d.width);
pr := make([]uint8, 1 + bpp * d.width); pr := make([]uint8, 1+bpp*d.width);
for y := 0; y < d.height; y++ { for y := 0; y < d.height; y++ {
// Read the decompressed bytes. // Read the decompressed bytes.
@ -231,10 +231,10 @@ func (d *decoder) idatReader(idat io.Reader) os.Error {
} }
case ftAverage: case ftAverage:
for i := 0; i < bpp; i++ { for i := 0; i < bpp; i++ {
cdat[i] += pdat[i]/2 cdat[i] += pdat[i] / 2
} }
for i := bpp; i < len(cdat); i++ { for i := bpp; i < len(cdat); i++ {
cdat[i] += uint8((int(cdat[i-bpp])+int(pdat[i]))/2) cdat[i] += uint8((int(cdat[i-bpp]) + int(pdat[i])) / 2)
} }
case ftPaeth: case ftPaeth:
for i := 0; i < bpp; i++ { for i := 0; i < bpp; i++ {
@ -251,7 +251,7 @@ func (d *decoder) idatReader(idat io.Reader) os.Error {
switch d.colorType { switch d.colorType {
case ctTrueColor: case ctTrueColor:
for x := 0; x < d.width; x++ { for x := 0; x < d.width; x++ {
rgba.Set(x, y, image.RGBAColor{cdat[3*x + 0], cdat[3*x + 1], cdat[3*x + 2], 0xff}) rgba.Set(x, y, image.RGBAColor{cdat[3*x+0], cdat[3*x+1], cdat[3*x+2], 0xff})
} }
case ctPaletted: case ctPaletted:
for x := 0; x < d.width; x++ { for x := 0; x < d.width; x++ {
@ -262,7 +262,7 @@ func (d *decoder) idatReader(idat io.Reader) os.Error {
} }
case ctTrueColorAlpha: case ctTrueColorAlpha:
for x := 0; x < d.width; x++ { for x := 0; x < d.width; x++ {
nrgba.Set(x, y, image.NRGBAColor{cdat[4*x + 0], cdat[4*x + 1], cdat[4*x + 2], cdat[4*x + 3]}) nrgba.Set(x, y, image.NRGBAColor{cdat[4*x+0], cdat[4*x+1], cdat[4*x+2], cdat[4*x+3]})
} }
} }
@ -293,7 +293,7 @@ func (d *decoder) parseIDAT(r io.Reader, crc hash.Hash32, length uint32) os.Erro
} }
var buf [4096]byte; var buf [4096]byte;
for length > 0 { for length > 0 {
n, err1 := r.Read(buf[0 : min(len(buf), int(length))]); n, err1 := r.Read(buf[0:min(len(buf), int(length))]);
// We delay checking err1. It is possible to get n bytes and an error, // We delay checking err1. It is possible to get n bytes and an error,
// but if the n bytes themselves contain a FormatError, for example, we // but if the n bytes themselves contain a FormatError, for example, we
// want to report that error, and not the one that made the Read stop. // want to report that error, and not the one that made the Read stop.
@ -369,7 +369,7 @@ func (d *decoder) parseChunk(r io.Reader) os.Error {
// Ignore this chunk (of a known length). // Ignore this chunk (of a known length).
var ignored [4096]byte; var ignored [4096]byte;
for length > 0 { for length > 0 {
n, err = io.ReadFull(r, ignored[0 : min(len(ignored), int(length))]); n, err = io.ReadFull(r, ignored[0:min(len(ignored), int(length))]);
if err != nil { if err != nil {
return err return err
} }

View file

@ -49,7 +49,7 @@ func sng(w io.WriteCloser, filename string, png image.Image) {
bitdepth := 8; bitdepth := 8;
// Write the filename and IHDR. // Write the filename and IHDR.
io.WriteString(w, "#SNG: from " + filename + ".png\nIHDR {\n"); io.WriteString(w, "#SNG: from "+filename+".png\nIHDR {\n");
fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", png.Width(), png.Height(), bitdepth); fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", png.Width(), png.Height(), bitdepth);
cm := png.ColorModel(); cm := png.ColorModel();
var paletted *image.Paletted; var paletted *image.Paletted;
@ -122,7 +122,7 @@ func TestReader(t *testing.T) {
defer piper.Close(); defer piper.Close();
// Read the .sng file. // Read the .sng file.
sf, err := os.Open("testdata/pngsuite/" + fn + ".sng", os.O_RDONLY, 0444); sf, err := os.Open("testdata/pngsuite/"+fn+".sng", os.O_RDONLY, 0444);
if err != nil { if err != nil {
t.Error(fn, err); t.Error(fn, err);
continue; continue;

View file

@ -21,15 +21,15 @@ type encoder struct {
err os.Error; err os.Error;
header [8]byte; header [8]byte;
footer [4]byte; footer [4]byte;
tmp [3*256]byte; tmp [3 * 256]byte;
} }
// Big-endian. // Big-endian.
func writeUint32(b []uint8, u uint32) { func writeUint32(b []uint8, u uint32) {
b[0] = uint8(u>>24); b[0] = uint8(u >> 24);
b[1] = uint8(u>>16); b[1] = uint8(u >> 16);
b[2] = uint8(u>>8); b[2] = uint8(u >> 8);
b[3] = uint8(u>>0); b[3] = uint8(u >> 0);
} }
// Returns whether or not the image is fully opaque. // Returns whether or not the image is fully opaque.
@ -50,7 +50,7 @@ func abs8(d uint8) int {
if d < 128 { if d < 128 {
return int(d) return int(d)
} }
return 256-int(d); return 256 - int(d);
} }
func (e *encoder) writeChunk(b []byte, name string) { func (e *encoder) writeChunk(b []byte, name string) {
@ -105,11 +105,11 @@ func (e *encoder) writePLTE(p image.PalettedColorModel) {
e.err = UnsupportedError("non-opaque palette color"); e.err = UnsupportedError("non-opaque palette color");
return; return;
} }
e.tmp[3*i + 0] = uint8(r>>24); e.tmp[3*i+0] = uint8(r >> 24);
e.tmp[3*i + 1] = uint8(g>>24); e.tmp[3*i+1] = uint8(g >> 24);
e.tmp[3*i + 2] = uint8(b>>24); e.tmp[3*i+2] = uint8(b >> 24);
} }
e.writeChunk(e.tmp[0 : 3*len(p)], "PLTE"); e.writeChunk(e.tmp[0:3*len(p)], "PLTE");
} }
// An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks, // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks,
@ -148,7 +148,7 @@ func filter(cr [][]byte, pr []byte, bpp int) int {
// The up filter. // The up filter.
sum := 0; sum := 0;
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
cdat2[i] = cdat0[i]-pdat[i]; cdat2[i] = cdat0[i] - pdat[i];
sum += abs8(cdat2[i]); sum += abs8(cdat2[i]);
} }
best := sum; best := sum;
@ -192,7 +192,7 @@ func filter(cr [][]byte, pr []byte, bpp int) int {
sum += abs8(cdat1[i]); sum += abs8(cdat1[i]);
} }
for i := bpp; i < n; i++ { for i := bpp; i < n; i++ {
cdat1[i] = cdat0[i]-cdat0[i-bpp]; cdat1[i] = cdat0[i] - cdat0[i-bpp];
sum += abs8(cdat1[i]); sum += abs8(cdat1[i]);
if sum >= best { if sum >= best {
break break
@ -210,7 +210,7 @@ func filter(cr [][]byte, pr []byte, bpp int) int {
sum += abs8(cdat3[i]); sum += abs8(cdat3[i]);
} }
for i := bpp; i < n; i++ { for i := bpp; i < n; i++ {
cdat3[i] = cdat0[i]-uint8((int(cdat0[i-bpp])+int(pdat[i]))/2); cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2);
sum += abs8(cdat3[i]); sum += abs8(cdat3[i]);
if sum >= best { if sum >= best {
break break
@ -249,10 +249,10 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error {
// The +1 is for the per-row filter type, which is at cr[*][0]. // The +1 is for the per-row filter type, which is at cr[*][0].
var cr [nFilter][]uint8; var cr [nFilter][]uint8;
for i := 0; i < len(cr); i++ { for i := 0; i < len(cr); i++ {
cr[i] = make([]uint8, 1 + bpp * m.Width()); cr[i] = make([]uint8, 1+bpp*m.Width());
cr[i][0] = uint8(i); cr[i][0] = uint8(i);
} }
pr := make([]uint8, 1 + bpp * m.Width()); pr := make([]uint8, 1+bpp*m.Width());
for y := 0; y < m.Height(); y++ { for y := 0; y < m.Height(); y++ {
// Convert from colors to bytes. // Convert from colors to bytes.
@ -261,9 +261,9 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error {
for x := 0; x < m.Width(); x++ { for x := 0; x < m.Width(); x++ {
// We have previously verified that the alpha value is fully opaque. // We have previously verified that the alpha value is fully opaque.
r, g, b, _ := m.At(x, y).RGBA(); r, g, b, _ := m.At(x, y).RGBA();
cr[0][3*x + 1] = uint8(r>>24); cr[0][3*x+1] = uint8(r >> 24);
cr[0][3*x + 2] = uint8(g>>24); cr[0][3*x+2] = uint8(g >> 24);
cr[0][3*x + 3] = uint8(b>>24); cr[0][3*x+3] = uint8(b >> 24);
} }
case ctPaletted: case ctPaletted:
for x := 0; x < m.Width(); x++ { for x := 0; x < m.Width(); x++ {
@ -273,10 +273,10 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error {
// Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
for x := 0; x < m.Width(); x++ { for x := 0; x < m.Width(); x++ {
c := image.NRGBAColorModel.Convert(m.At(x, y)).(image.NRGBAColor); c := image.NRGBAColorModel.Convert(m.At(x, y)).(image.NRGBAColor);
cr[0][4*x + 1] = c.R; cr[0][4*x+1] = c.R;
cr[0][4*x + 2] = c.G; cr[0][4*x+2] = c.G;
cr[0][4*x + 3] = c.B; cr[0][4*x+3] = c.B;
cr[0][4*x + 4] = c.A; cr[0][4*x+4] = c.A;
} }
} }

View file

@ -183,7 +183,7 @@ func Copyn(dst Writer, src Reader, n int64) (written int64, err os.Error) {
buf := make([]byte, 32*1024); buf := make([]byte, 32*1024);
for written < n { for written < n {
l := len(buf); l := len(buf);
if d := n-written; d < int64(l) { if d := n - written; d < int64(l) {
l = int(d) l = int(d)
} }
nr, er := src.Read(buf[0:l]); nr, er := src.Read(buf[0:l]);
@ -255,7 +255,7 @@ func (l *limitedReader) Read(p []byte) (n int, err os.Error) {
return 0, os.EOF return 0, os.EOF
} }
if int64(len(p)) > l.n { if int64(len(p)) > l.n {
p = p[0 : l.n] p = p[0:l.n]
} }
n, err = l.r.Read(p); n, err = l.r.Read(p);
l.n -= int64(n); l.n -= int64(n);
@ -265,7 +265,7 @@ func (l *limitedReader) Read(p []byte) (n int, err os.Error) {
// NewSectionReader returns a SectionReader that reads from r // NewSectionReader returns a SectionReader that reads from r
// starting at offset off and stops with os.EOF after n bytes. // starting at offset off and stops with os.EOF after n bytes.
func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader {
return &SectionReader{r, off, off, off+n} return &SectionReader{r, off, off, off + n}
} }
// SectionReader implements Read, Seek, and ReadAt on a section // SectionReader implements Read, Seek, and ReadAt on a section
@ -308,7 +308,7 @@ func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err os.Error)
} }
func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err os.Error) { func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err os.Error) {
if off < 0 || off >= s.limit - s.base { if off < 0 || off >= s.limit-s.base {
return 0, os.EOF return 0, os.EOF
} }
off += s.base; off += s.base;

View file

@ -63,7 +63,7 @@ func TestPipe2(t *testing.T) {
go reader(t, r, c); go reader(t, r, c);
var buf = make([]byte, 64); var buf = make([]byte, 64);
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
p := buf[0 : 5 + i*10]; p := buf[0 : 5+i*10];
n, err := w.Write(p); n, err := w.Write(p);
if n != len(p) { if n != len(p) {
t.Errorf("wrote %d, got %d", len(p), n) t.Errorf("wrote %d, got %d", len(p), n)

View file

@ -33,7 +33,7 @@ func ReadFile(filename string) ([]byte, os.Error) {
// If the file does not exist, WriteFile creates it with permissions perm; // If the file does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing. // otherwise WriteFile truncates it before writing.
func WriteFile(filename string, data []byte, perm int) os.Error { func WriteFile(filename string, data []byte, perm int) os.Error {
f, err := os.Open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, perm); f, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm);
if err != nil { if err != nil {
return err return err
} }

View file

@ -31,11 +31,11 @@ func _UnHex(p string, r, l int) (v int, ok bool) {
v *= 16; v *= 16;
switch { switch {
case '0' <= p[i] && p[i] <= '9': case '0' <= p[i] && p[i] <= '9':
v += int(p[i]-'0') v += int(p[i] - '0')
case 'a' <= p[i] && p[i] <= 'f': case 'a' <= p[i] && p[i] <= 'f':
v += int(p[i]-'a'+10) v += int(p[i] - 'a' + 10)
case 'A' <= p[i] && p[i] <= 'F': case 'A' <= p[i] && p[i] <= 'F':
v += int(p[i]-'A'+10) v += int(p[i] - 'A' + 10)
default: default:
return 0, false return 0, false
} }
@ -208,7 +208,7 @@ func skipstring(p string, i int) int {
if i >= len(p) { if i >= len(p) {
return i return i
} }
return i+1; return i + 1;
} }
func (t *_Lexer) Next() { func (t *_Lexer) Next() {

View file

@ -167,7 +167,7 @@ func (b *structBuilder) Elem(i int) Builder {
v.Set(nv); v.Set(nv);
} }
if v.Len() <= i && i < v.Cap() { if v.Len() <= i && i < v.Cap() {
v.SetLen(i+1) v.SetLen(i + 1)
} }
if i < v.Len() { if i < v.Len() {
return &structBuilder{val: v.Elem(i)} return &structBuilder{val: v.Elem(i)}

View file

@ -29,7 +29,7 @@ const (
// order they appear (the order listed here) or the format they present (as // order they appear (the order listed here) or the format they present (as
// described in the comments). A colon appears after these items: // described in the comments). A colon appears after these items:
// 2009/0123 01:23:23.123123 /a/b/c/d.go:23: message // 2009/0123 01:23:23.123123 /a/b/c/d.go:23: message
Ldate = 1<<iota; // the date: 2009/0123 Ldate = 1 << iota; // the date: 2009/0123
Ltime; // the time: 01:23:23 Ltime; // the time: 01:23:23
Lmicroseconds; // microsecond resolution: 01:23:23.123123. assumes Ltime. Lmicroseconds; // microsecond resolution: 01:23:23.123123. assumes Ltime.
Llongfile; // full file name and line number: /a/b/c/d.go:23 Llongfile; // full file name and line number: /a/b/c/d.go:23
@ -75,7 +75,7 @@ func itoa(i int, wid int) string {
for ; u > 0 || wid > 0; u /= 10 { for ; u > 0 || wid > 0; u /= 10 {
bp--; bp--;
wid--; wid--;
b[bp] = byte(u%10)+'0'; b[bp] = byte(u%10) + '0';
} }
return string(b[bp:len(b)]); return string(b[bp:len(b)]);
@ -83,27 +83,27 @@ func itoa(i int, wid int) string {
func (l *Logger) formatHeader(ns int64, calldepth int) string { func (l *Logger) formatHeader(ns int64, calldepth int) string {
h := l.prefix; h := l.prefix;
if l.flag & (Ldate | Ltime | Lmicroseconds) != 0 { if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
t := time.SecondsToLocalTime(ns/1e9); t := time.SecondsToLocalTime(ns / 1e9);
if l.flag & (Ldate) != 0 { if l.flag&(Ldate) != 0 {
h += itoa(int(t.Year), 4) + "/" + itoa(t.Month, 2) + "/" + itoa(t.Day, 2) + " " h += itoa(int(t.Year), 4) + "/" + itoa(t.Month, 2) + "/" + itoa(t.Day, 2) + " "
} }
if l.flag & (Ltime | Lmicroseconds) != 0 { if l.flag&(Ltime|Lmicroseconds) != 0 {
h += itoa(t.Hour, 2) + ":" + itoa(t.Minute, 2) + ":" + itoa(t.Second, 2); h += itoa(t.Hour, 2) + ":" + itoa(t.Minute, 2) + ":" + itoa(t.Second, 2);
if l.flag & Lmicroseconds != 0 { if l.flag&Lmicroseconds != 0 {
h += "." + itoa(int(ns%1e9)/1e3, 6) h += "." + itoa(int(ns%1e9)/1e3, 6)
} }
h += " "; h += " ";
} }
} }
if l.flag & (Lshortfile | Llongfile) != 0 { if l.flag&(Lshortfile|Llongfile) != 0 {
_, file, line, ok := runtime.Caller(calldepth); _, file, line, ok := runtime.Caller(calldepth);
if ok { if ok {
if l.flag & Lshortfile != 0 { if l.flag&Lshortfile != 0 {
short, ok := shortnames[file]; short, ok := shortnames[file];
if !ok { if !ok {
short = file; short = file;
for i := len(file)-1; i > 0; i-- { for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' { if file[i] == '/' {
short = file[i+1 : len(file)]; short = file[i+1 : len(file)];
break; break;
@ -131,7 +131,7 @@ func (l *Logger) Output(calldepth int, s string) {
if len(s) > 0 && s[len(s)-1] == '\n' { if len(s) > 0 && s[len(s)-1] == '\n' {
newline = "" newline = ""
} }
s = l.formatHeader(now, calldepth + 1) + s + newline; s = l.formatHeader(now, calldepth+1) + s + newline;
io.WriteString(l.out0, s); io.WriteString(l.out0, s);
if l.out1 != nil { if l.out1 != nil {
io.WriteString(l.out1, s) io.WriteString(l.out1, s)

View file

@ -32,8 +32,8 @@ var tests = []tester{
// individual pieces: // individual pieces:
tester{0, "", ""}, tester{0, "", ""},
tester{0, "XXX", "XXX"}, tester{0, "XXX", "XXX"},
tester{Lok|Ldate, "", Rdate+" "}, tester{Lok | Ldate, "", Rdate + " "},
tester{Lok|Ltime, "", Rtime+" "}, tester{Lok | Ltime, "", Rtime + " "},
tester{Lok | Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, tester{Lok | Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "},
tester{Lok | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time tester{Lok | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time
tester{Lok | Llongfile, "", Rlongfile + " "}, tester{Lok | Llongfile, "", Rlongfile + " "},

View file

@ -155,13 +155,13 @@ var tanh = []float64{
} }
func tolerance(a, b, e float64) bool { func tolerance(a, b, e float64) bool {
d := a-b; d := a - b;
if d < 0 { if d < 0 {
d = -d d = -d
} }
if a != 0 { if a != 0 {
e = e*a; e = e * a;
if e < 0 { if e < 0 {
e = -e e = -e
} }
@ -173,7 +173,7 @@ func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) }
func TestAsin(t *testing.T) { func TestAsin(t *testing.T) {
for i := 0; i < len(vf); i++ { for i := 0; i < len(vf); i++ {
if f := Asin(vf[i]/10); !veryclose(asin[i], f) { if f := Asin(vf[i] / 10); !veryclose(asin[i], f) {
t.Errorf("Asin(%g) = %g, want %g\n", vf[i]/10, f, asin[i]) t.Errorf("Asin(%g) = %g, want %g\n", vf[i]/10, f, asin[i])
} }
} }
@ -266,7 +266,7 @@ func TestTanh(t *testing.T) {
func TestHypot(t *testing.T) { func TestHypot(t *testing.T) {
for i := 0; i < len(vf); i++ { for i := 0; i < len(vf); i++ {
a := Fabs(tanh[i]*Sqrt(2)); a := Fabs(tanh[i] * Sqrt(2));
if f := Hypot(tanh[i], tanh[i]); !veryclose(a, f) { if f := Hypot(tanh[i], tanh[i]); !veryclose(a, f) {
t.Errorf("Hypot(%g, %g) = %g, want %g\n", tanh[i], tanh[i], f, a) t.Errorf("Hypot(%g, %g) = %g, want %g\n", tanh[i], tanh[i], f, a)
} }

View file

@ -27,7 +27,7 @@ func Asin(x float64) float64 {
if x > 0.7 { if x > 0.7 {
temp = Pi/2 - Atan(temp/x) temp = Pi/2 - Atan(temp/x)
} else { } else {
temp = Atan(x/temp) temp = Atan(x / temp)
} }
if sign { if sign {

View file

@ -31,10 +31,10 @@ func xatan(arg float64) float64 {
Q1 = .207933497444540981287275926e4; Q1 = .207933497444540981287275926e4;
Q0 = .89678597403663861962481162e3; Q0 = .89678597403663861962481162e3;
) )
sq := arg*arg; sq := arg * arg;
value := ((((P4*sq + P3)*sq + P2)*sq + P1)*sq + P0); value := ((((P4*sq+P3)*sq+P2)*sq + P1) * sq + P0);
value = value/(((((sq+Q4)*sq + Q3)*sq + Q2)*sq + Q1)*sq + Q0); value = value / (((((sq+Q4)*sq+Q3)*sq+Q2)*sq+Q1)*sq + Q0);
return value*arg; return value * arg;
} }
/* /*

View file

@ -12,16 +12,16 @@ func Atan2(x, y float64) float64 {
// Determine the quadrant and call atan. // Determine the quadrant and call atan.
if x+y == x { if x+y == x {
if x >= 0 { if x >= 0 {
return Pi/2 return Pi / 2
} }
return -Pi / 2; return -Pi / 2;
} }
q := Atan(x/y); q := Atan(x / y);
if y < 0 { if y < 0 {
if q <= 0 { if q <= 0 {
return q+Pi return q + Pi
} }
return q-Pi; return q - Pi;
} }
return q; return q;
} }

View file

@ -9,7 +9,7 @@ const (
uvinf = 0x7FF0000000000000; uvinf = 0x7FF0000000000000;
uvneginf = 0xFFF0000000000000; uvneginf = 0xFFF0000000000000;
mask = 0x7FF; mask = 0x7FF;
shift = 64-11-1; shift = 64 - 11 - 1;
bias = 1022; bias = 1022;
) )
@ -51,9 +51,9 @@ func Frexp(f float64) (frac float64, exp int) {
return return
} }
x := Float64bits(f); x := Float64bits(f);
exp = int((x>>shift)&mask)-bias; exp = int((x>>shift)&mask) - bias;
x &^= mask<<shift; x &^= mask << shift;
x |= bias<<shift; x |= bias << shift;
frac = Float64frombits(x); frac = Float64frombits(x);
return; return;
} }
@ -62,7 +62,7 @@ func Frexp(f float64) (frac float64, exp int) {
// It returns frac × 2<sup>exp</sup>. // It returns frac × 2<sup>exp</sup>.
func Ldexp(frac float64, exp int) float64 { func Ldexp(frac float64, exp int) float64 {
x := Float64bits(frac); x := Float64bits(frac);
exp += int(x>>shift)&mask; exp += int(x>>shift) & mask;
if exp <= 0 { if exp <= 0 {
return 0 // underflow return 0 // underflow
} }
@ -72,8 +72,8 @@ func Ldexp(frac float64, exp int) float64 {
} }
return Inf(1); return Inf(1);
} }
x &^= mask<<shift; x &^= mask << shift;
x |= uint64(exp)<<shift; x |= uint64(exp) << shift;
return Float64frombits(x); return Float64frombits(x);
} }
@ -97,6 +97,6 @@ func Modf(f float64) (int float64, frac float64) {
x &^= 1<<(64-11-e) - 1 x &^= 1<<(64-11-e) - 1
} }
int = Float64frombits(x); int = Float64frombits(x);
frac = f-int; frac = f - int;
return; return;
} }

View file

@ -18,9 +18,9 @@ const (
SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038; // A139339 SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038; // A139339
Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009; // A002162 Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009; // A002162
Log2E = 1/Ln2; Log2E = 1 / Ln2;
Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790; // A002392 Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790; // A002392
Log10E = 1/Ln10; Log10E = 1 / Ln10;
) )
// Floating-point limit values. // Floating-point limit values.

View file

@ -101,7 +101,7 @@ func Exp(x float64) float64 {
Overflow = 7.09782712893383973096e+02; Overflow = 7.09782712893383973096e+02;
Underflow = -7.45133219101941108420e+02; Underflow = -7.45133219101941108420e+02;
NearZero = 1.0/(1<<28); // 2^-28 NearZero = 1.0 / (1 << 28); // 2^-28
) )
// special cases // special cases
@ -127,13 +127,13 @@ func Exp(x float64) float64 {
k = int(Log2e*x + 0.5) k = int(Log2e*x + 0.5)
} }
hi := x - float64(k)*Ln2Hi; hi := x - float64(k)*Ln2Hi;
lo := float64(k)*Ln2Lo; lo := float64(k) * Ln2Lo;
r := hi-lo; r := hi - lo;
// compute // compute
t := r*r; t := r * r;
c := r - t*(P1 + t*(P2 + t*(P3 + t*(P4 + t*P5)))); c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5))));
y := 1-((lo - (r*c)/(2-c))-hi); y := 1 - ((lo - (r*c)/(2-c)) - hi);
// TODO(rsc): make sure Ldexp can handle boundary k // TODO(rsc): make sure Ldexp can handle boundary k
return Ldexp(y, k); return Ldexp(y, k);
} }

View file

@ -10,7 +10,7 @@ func Floor(x float64) float64 {
if x < 0 { if x < 0 {
d, fract := Modf(-x); d, fract := Modf(-x);
if fract != 0.0 { if fract != 0.0 {
d = d+1 d = d + 1
} }
return -d; return -d;
} }

View file

@ -29,7 +29,7 @@ func Fmod(x, y float64) float64 {
for r >= y { for r >= y {
rfr, rexp := Frexp(r); rfr, rexp := Frexp(r);
if rfr < yfr { if rfr < yfr {
rexp = rexp-1 rexp = rexp - 1
} }
r = r - Ldexp(y, rexp-yexp); r = r - Ldexp(y, rexp-yexp);
} }

View file

@ -31,19 +31,19 @@ func Hypot(p, q float64) float64 {
} }
pfac := p; pfac := p;
q = q/p; q = q / p;
r := q; r := q;
p = 1; p = 1;
for { for {
r = r*r; r = r * r;
s := r+4; s := r + 4;
if s == 4 { if s == 4 {
return p*pfac return p * pfac
} }
r = r/s; r = r / s;
p = p + 2*r*p; p = p + 2*r*p;
q = q*r; q = q * r;
r = q/p; r = q / p;
} }
panic("unreachable"); panic("unreachable");
} }

View file

@ -103,18 +103,18 @@ func Log(x float64) float64 {
f1 *= 2; f1 *= 2;
ki--; ki--;
} }
f := f1-1; f := f1 - 1;
k := float64(ki); k := float64(ki);
// compute // compute
s := f/(2+f); s := f / (2 + f);
s2 := s*s; s2 := s * s;
s4 := s2*s2; s4 := s2 * s2;
t1 := s2*(L1 + s4*(L3 + s4*(L5 + s4*L7))); t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7)));
t2 := s4*(L2 + s4*(L4 + s4*L6)); t2 := s4 * (L2 + s4*(L4+s4*L6));
R := t1+t2; R := t1 + t2;
hfsq := 0.5*f*f; hfsq := 0.5 * f * f;
return k*Ln2Hi - ((hfsq-(s*(hfsq+R) + k*Ln2Lo))-f); return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f);
} }
// Log10 returns the decimal logarithm of x. // Log10 returns the decimal logarithm of x.
@ -123,5 +123,5 @@ func Log10(x float64) float64 {
if x <= 0 { if x <= 0 {
return NaN() return NaN()
} }
return Log(x)*(1/Ln10); return Log(x) * (1 / Ln10);
} }

View file

@ -20,7 +20,7 @@ func Pow(x, y float64) float64 {
case y == 0.5: case y == 0.5:
return Sqrt(x) return Sqrt(x)
case y == -0.5: case y == -0.5:
return 1/Sqrt(x) return 1 / Sqrt(x)
} }
absy := y; absy := y;
@ -34,7 +34,7 @@ func Pow(x, y float64) float64 {
return NaN() return NaN()
} }
if yi >= 1<<63 { if yi >= 1<<63 {
return Exp(y*Log(x)) return Exp(y * Log(x))
} }
// ans = a1 * 2^ae (= 1 for now). // ans = a1 * 2^ae (= 1 for now).
@ -47,7 +47,7 @@ func Pow(x, y float64) float64 {
yf--; yf--;
yi++; yi++;
} }
a1 = Exp(yf*Log(x)); a1 = Exp(yf * Log(x));
} }
// ans *= x^yi // ans *= x^yi
@ -72,7 +72,7 @@ func Pow(x, y float64) float64 {
// if flip { ans = 1 / ans } // if flip { ans = 1 / ans }
// but in the opposite order // but in the opposite order
if flip { if flip {
a1 = 1/a1; a1 = 1 / a1;
ae = -ae; ae = -ae;
} }
return Ldexp(a1, ae); return Ldexp(a1, ae);

View file

@ -18,20 +18,20 @@ var pow10tab [70]float64
// Pow10 returns 10**x, the base-10 exponential of x. // Pow10 returns 10**x, the base-10 exponential of x.
func Pow10(e int) float64 { func Pow10(e int) float64 {
if e < 0 { if e < 0 {
return 1/Pow10(-e) return 1 / Pow10(-e)
} }
if e < len(pow10tab) { if e < len(pow10tab) {
return pow10tab[e] return pow10tab[e]
} }
m := e/2; m := e / 2;
return Pow10(m)*Pow10(e-m); return Pow10(m) * Pow10(e-m);
} }
func init() { func init() {
pow10tab[0] = 1.0e0; pow10tab[0] = 1.0e0;
pow10tab[1] = 1.0e1; pow10tab[1] = 1.0e1;
for i := 2; i < len(pow10tab); i++ { for i := 2; i < len(pow10tab); i++ {
m := i/2; m := i / 2;
pow10tab[i] = pow10tab[m]*pow10tab[i-m]; pow10tab[i] = pow10tab[m] * pow10tab[i-m];
} }
} }

View file

@ -20,33 +20,33 @@ func sinus(x float64, quad int) float64 {
) )
if x < 0 { if x < 0 {
x = -x; x = -x;
quad = quad+2; quad = quad + 2;
} }
x = x*(2/Pi); /* underflow? */ x = x * (2 / Pi); /* underflow? */
var y float64; var y float64;
if x > 32764 { if x > 32764 {
var e float64; var e float64;
e, y = Modf(x); e, y = Modf(x);
e = e+float64(quad); e = e + float64(quad);
_, f := Modf(0.25*e); _, f := Modf(0.25 * e);
quad = int(e - 4*f); quad = int(e - 4*f);
} else { } else {
k := int32(x); k := int32(x);
y = x-float64(k); y = x - float64(k);
quad = (quad+int(k))&3; quad = (quad + int(k)) & 3;
} }
if quad&1 != 0 { if quad&1 != 0 {
y = 1-y y = 1 - y
} }
if quad > 1 { if quad > 1 {
y = -y y = -y
} }
yy := y*y; yy := y * y;
temp1 := ((((P4*yy + P3)*yy + P2)*yy + P1)*yy + P0)*y; temp1 := ((((P4*yy+P3)*yy+P2)*yy+P1)*yy + P0) * y;
temp2 := ((((yy+Q3)*yy + Q2)*yy + Q1)*yy + Q0); temp2 := ((((yy+Q3)*yy+Q2)*yy + Q1) * yy + Q0);
return temp1/temp2; return temp1 / temp2;
} }
// Cos returns the cosine of x. // Cos returns the cosine of x.

View file

@ -39,15 +39,15 @@ func Sinh(x float64) float64 {
var temp float64; var temp float64;
switch true { switch true {
case x > 21: case x > 21:
temp = Exp(x)/2 temp = Exp(x) / 2
case x > 0.5: case x > 0.5:
temp = (Exp(x)-Exp(-x))/2 temp = (Exp(x) - Exp(-x)) / 2
default: default:
sq := x*x; sq := x * x;
temp = (((P3*sq + P2)*sq + P1)*sq + P0)*x; temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x;
temp = temp/(((sq+Q2)*sq + Q1)*sq + Q0); temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0);
} }
if sign { if sign {
@ -62,7 +62,7 @@ func Cosh(x float64) float64 {
x = -x x = -x
} }
if x > 21 { if x > 21 {
return Exp(x)/2 return Exp(x) / 2
} }
return (Exp(x)+Exp(-x))/2; return (Exp(x) + Exp(-x)) / 2;
} }

View file

@ -32,34 +32,34 @@ func Sqrt(x float64) float64 {
y, exp := Frexp(x); y, exp := Frexp(x);
for y < 0.5 { for y < 0.5 {
y = y*2; y = y * 2;
exp = exp-1; exp = exp - 1;
} }
if exp&1 != 0 { if exp&1 != 0 {
y = y*2; y = y * 2;
exp = exp-1; exp = exp - 1;
} }
temp := 0.5*(1+y); temp := 0.5 * (1 + y);
for exp > 60 { for exp > 60 {
temp = temp*float64(1<<30); temp = temp * float64(1<<30);
exp = exp-60; exp = exp - 60;
} }
for exp < -60 { for exp < -60 {
temp = temp/float64(1<<30); temp = temp / float64(1<<30);
exp = exp+60; exp = exp + 60;
} }
if exp >= 0 { if exp >= 0 {
exp = 1<<uint(exp/2); exp = 1 << uint(exp/2);
temp = temp*float64(exp); temp = temp * float64(exp);
} else { } else {
exp = 1<<uint(-exp / 2); exp = 1 << uint(-exp/2);
temp = temp/float64(exp); temp = temp / float64(exp);
} }
for i := 0; i <= 4; i++ { for i := 0; i <= 4; i++ {
temp = 0.5*(temp + x/temp) temp = 0.5 * (temp + x/temp)
} }
return temp; return temp;
} }

View file

@ -29,14 +29,14 @@ func Tan(x float64) float64 {
x = -x; x = -x;
sign = true; sign = true;
} }
x = x*(4/Pi); /* overflow? */ x = x * (4 / Pi); /* overflow? */
var e float64; var e float64;
e, x = Modf(x); e, x = Modf(x);
i := int32(e); i := int32(e);
switch i&3 { switch i & 3 {
case 1: case 1:
x = 1-x; x = 1 - x;
flag = true; flag = true;
case 2: case 2:
@ -44,19 +44,19 @@ func Tan(x float64) float64 {
flag = true; flag = true;
case 3: case 3:
x = 1-x; x = 1 - x;
sign = !sign; sign = !sign;
} }
xsq := x*x; xsq := x * x;
temp := ((((P4*xsq + P3)*xsq + P2)*xsq + P1)*xsq + P0)*x; temp := ((((P4*xsq+P3)*xsq+P2)*xsq+P1)*xsq + P0) * x;
temp = temp/(((xsq+Q2)*xsq + Q1)*xsq + Q0); temp = temp / (((xsq+Q2)*xsq+Q1)*xsq + Q0);
if flag { if flag {
if temp == 0 { if temp == 0 {
panic(NaN()) panic(NaN())
} }
temp = 1/temp; temp = 1 / temp;
} }
if sign { if sign {
temp = -temp temp = -temp

View file

@ -25,5 +25,5 @@ func Tanh(x float64) float64 {
if x > 21 { if x > 21 {
return 1 return 1
} }
return Sinh(x)/Cosh(x); return Sinh(x) / Cosh(x);
} }

View file

@ -82,11 +82,11 @@ type __DNS_Header struct {
const ( const (
// __DNS_Header.Bits // __DNS_Header.Bits
_QR = 1<<15; // query/response (response=1) _QR = 1 << 15; // query/response (response=1)
_AA = 1<<10; // authoritative _AA = 1 << 10; // authoritative
_TC = 1<<9; // truncated _TC = 1 << 9; // truncated
_RD = 1<<8; // recursion desired _RD = 1 << 8; // recursion desired
_RA = 1<<7; // recursion available _RA = 1 << 7; // recursion available
) )
// DNS queries. // DNS queries.
@ -271,7 +271,7 @@ func packDomainName(s string, msg []byte, off int) (off1 int, ok bool) {
// We trade each dot byte for a length byte. // We trade each dot byte for a length byte.
// There is also a trailing zero. // There is also a trailing zero.
// Check that we have all the space we need. // Check that we have all the space we need.
tot := len(s)+1; tot := len(s) + 1;
if off+tot > len(msg) { if off+tot > len(msg) {
return len(msg), false return len(msg), false
} }
@ -283,13 +283,13 @@ func packDomainName(s string, msg []byte, off int) (off1 int, ok bool) {
if i-begin >= 1<<6 { // top two bits of length must be clear if i-begin >= 1<<6 { // top two bits of length must be clear
return len(msg), false return len(msg), false
} }
msg[off] = byte(i-begin); msg[off] = byte(i - begin);
off++; off++;
for j := begin; j < i; j++ { for j := begin; j < i; j++ {
msg[off] = s[j]; msg[off] = s[j];
off++; off++;
} }
begin = i+1; begin = i + 1;
} }
} }
msg[off] = 0; msg[off] = 0;
@ -320,7 +320,7 @@ Loop:
} }
c := int(msg[off]); c := int(msg[off]);
off++; off++;
switch c&0xC0 { switch c & 0xC0 {
case 0x00: case 0x00:
if c == 0x00 { if c == 0x00 {
// end of name // end of name
@ -330,7 +330,7 @@ Loop:
if off+c > len(msg) { if off+c > len(msg) {
return "", len(msg), false return "", len(msg), false
} }
s += string(msg[off : off+c])+"."; s += string(msg[off:off+c]) + ".";
off += c; off += c;
case 0xC0: case 0xC0:
// pointer to somewhere else in msg. // pointer to somewhere else in msg.
@ -378,7 +378,7 @@ func packStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, o
if off+2 > len(msg) { if off+2 > len(msg) {
return len(msg), false return len(msg), false
} }
msg[off] = byte(i>>8); msg[off] = byte(i >> 8);
msg[off+1] = byte(i); msg[off+1] = byte(i);
off += 2; off += 2;
case *reflect.Uint32Value: case *reflect.Uint32Value:
@ -386,9 +386,9 @@ func packStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, o
if off+4 > len(msg) { if off+4 > len(msg) {
return len(msg), false return len(msg), false
} }
msg[off] = byte(i>>24); msg[off] = byte(i >> 24);
msg[off+1] = byte(i>>16); msg[off+1] = byte(i >> 16);
msg[off+2] = byte(i>>8); msg[off+2] = byte(i >> 8);
msg[off+4] = byte(i); msg[off+4] = byte(i);
off += 4; off += 4;
case *reflect.StringValue: case *reflect.StringValue:
@ -535,7 +535,7 @@ func packRR(rr _DNS_RR, msg []byte, off int) (off2 int, ok bool) {
return len(msg), false return len(msg), false
} }
// pack a third time; redo header with correct data length // pack a third time; redo header with correct data length
rr.Header().Rdlength = uint16(off2-off1); rr.Header().Rdlength = uint16(off2 - off1);
packStruct(rr.Header(), msg, off); packStruct(rr.Header(), msg, off);
return off2, true; return off2, true;
} }
@ -548,7 +548,7 @@ func unpackRR(msg []byte, off int) (rr _DNS_RR, off1 int, ok bool) {
if off, ok = unpackStruct(&h, msg, off); !ok { if off, ok = unpackStruct(&h, msg, off); !ok {
return nil, len(msg), false return nil, len(msg), false
} }
end := off+int(h.Rdlength); end := off + int(h.Rdlength);
// make an rr of that type and re-unpack. // make an rr of that type and re-unpack.
// again inefficient but doesn't need to be fast. // again inefficient but doesn't need to be fast.
@ -657,7 +657,7 @@ func (dns *_DNS_Msg) Unpack(msg []byte) bool {
} }
dns.id = dh.Id; dns.id = dh.Id;
dns.response = (dh.Bits & _QR) != 0; dns.response = (dh.Bits & _QR) != 0;
dns.opcode = int(dh.Bits >> 11)&0xF; dns.opcode = int(dh.Bits>>11) & 0xF;
dns.authoritative = (dh.Bits & _AA) != 0; dns.authoritative = (dh.Bits & _AA) != 0;
dns.truncated = (dh.Bits & _TC) != 0; dns.truncated = (dh.Bits & _TC) != 0;
dns.recursion_desired = (dh.Bits & _RD) != 0; dns.recursion_desired = (dh.Bits & _RD) != 0;

View file

@ -134,7 +134,7 @@ func (s *pollServer) AddFD(fd *netFD, mode int) {
} }
var t int64; var t int64;
key := intfd<<1; key := intfd << 1;
if mode == 'r' { if mode == 'r' {
fd.ncr++; fd.ncr++;
t = fd.rdeadline; t = fd.rdeadline;
@ -150,7 +150,7 @@ func (s *pollServer) AddFD(fd *netFD, mode int) {
} }
func (s *pollServer) LookupFD(fd int, mode int) *netFD { func (s *pollServer) LookupFD(fd int, mode int) *netFD {
key := fd<<1; key := fd << 1;
if mode == 'w' { if mode == 'w' {
key++ key++
} }
@ -181,7 +181,7 @@ func (s *pollServer) Now() int64 {
if err != nil { if err != nil {
panic("net: os.Time: ", err.String()) panic("net: os.Time: ", err.String())
} }
nsec += sec*1e9; nsec += sec * 1e9;
return nsec; return nsec;
} }

View file

@ -50,7 +50,7 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error {
if e != 0 { if e != 0 {
return os.NewSyscallError("kevent", e) return os.NewSyscallError("kevent", e)
} }
if n != 1 || (ev.Flags & syscall.EV_ERROR) == 0 || int(ev.Ident) != fd || int(ev.Filter) != kmode { if n != 1 || (ev.Flags&syscall.EV_ERROR) == 0 || int(ev.Ident) != fd || int(ev.Filter) != kmode {
return os.ErrorString("kqueue phase error") return os.ErrorString("kqueue phase error")
} }
if ev.Data != 0 { if ev.Data != 0 {
@ -71,7 +71,7 @@ func (p *pollster) DelFD(fd int, mode int) {
// EV_DELETE - delete event from kqueue list // EV_DELETE - delete event from kqueue list
// EV_RECEIPT - generate fake EV_ERROR as result of add, // EV_RECEIPT - generate fake EV_ERROR as result of add,
// rather than waiting for real event // rather than waiting for real event
syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE | syscall.EV_RECEIPT); syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE|syscall.EV_RECEIPT);
syscall.Kevent(p.kq, &events, &events, nil); syscall.Kevent(p.kq, &events, &events, nil);
} }

View file

@ -73,7 +73,7 @@ func (p *pollster) StopWaiting(fd int, bits uint) {
// If syscall.EPOLLONESHOT is not set, the wait // If syscall.EPOLLONESHOT is not set, the wait
// is a repeating wait, so don't change it. // is a repeating wait, so don't change it.
if events & syscall.EPOLLONESHOT == 0 { if events&syscall.EPOLLONESHOT == 0 {
return return
} }
@ -81,7 +81,7 @@ func (p *pollster) StopWaiting(fd int, bits uint) {
// If we're still waiting for other events, modify the fd // If we're still waiting for other events, modify the fd
// event in the kernel. Otherwise, delete it. // event in the kernel. Otherwise, delete it.
events &= ^uint32(bits); events &= ^uint32(bits);
if int32(events) & ^syscall.EPOLLONESHOT != 0 { if int32(events)&^syscall.EPOLLONESHOT != 0 {
var ev syscall.EpollEvent; var ev syscall.EpollEvent;
ev.Fd = int32(fd); ev.Fd = int32(fd);
ev.Events = events; ev.Events = events;
@ -111,7 +111,7 @@ func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) {
ev := &evarray[0]; ev := &evarray[0];
var msec int = -1; var msec int = -1;
if nsec > 0 { if nsec > 0 {
msec = int((nsec+1e6-1)/1e6) msec = int((nsec + 1e6 - 1) / 1e6)
} }
n, e := syscall.EpollWait(p.epfd, &evarray, msec); n, e := syscall.EpollWait(p.epfd, &evarray, msec);
for e == syscall.EAGAIN || e == syscall.EINTR { for e == syscall.EAGAIN || e == syscall.EINTR {
@ -125,18 +125,18 @@ func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) {
} }
fd = int(ev.Fd); fd = int(ev.Fd);
if ev.Events & writeFlags != 0 { if ev.Events&writeFlags != 0 {
p.StopWaiting(fd, writeFlags); p.StopWaiting(fd, writeFlags);
return fd, 'w', nil; return fd, 'w', nil;
} }
if ev.Events & readFlags != 0 { if ev.Events&readFlags != 0 {
p.StopWaiting(fd, readFlags); p.StopWaiting(fd, readFlags);
return fd, 'r', nil; return fd, 'r', nil;
} }
// Other events are error conditions - wake whoever is waiting. // Other events are error conditions - wake whoever is waiting.
events, _ := p.events[fd]; events, _ := p.events[fd];
if events & writeFlags != 0 { if events&writeFlags != 0 {
p.StopWaiting(fd, writeFlags); p.StopWaiting(fd, writeFlags);
return fd, 'w', nil; return fd, 'w', nil;
} }

View file

@ -134,7 +134,7 @@ func (ip IP) Mask(mask IPMask) IP {
} }
out := make(IP, n); out := make(IP, n);
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
out[i] = ip[i]&mask[i] out[i] = ip[i] & mask[i]
} }
return out; return out;
} }
@ -150,7 +150,7 @@ func itod(i uint) string {
bp := len(b); bp := len(b);
for ; i > 0; i /= 10 { for ; i > 0; i /= 10 {
bp--; bp--;
b[bp] = byte(i%10)+'0'; b[bp] = byte(i%10) + '0';
} }
return string(b[bp:len(b)]); return string(b[bp:len(b)]);
@ -221,7 +221,7 @@ func (ip IP) String() string {
} else if i > 0 { } else if i > 0 {
s += ":" s += ":"
} }
s += itox((uint(p[i])<<8)|uint(p[i+1])); s += itox((uint(p[i]) << 8) | uint(p[i+1]));
} }
return s; return s;
} }
@ -235,7 +235,7 @@ func simpleMaskLength(mask IPMask) int {
break break
} }
} }
n := 8*i; n := 8 * i;
v := mask[i]; v := mask[i];
for v&0x80 != 0 { for v&0x80 != 0 {
n++; n++;
@ -356,7 +356,7 @@ L: for j < IPv6len {
} }
// Save this 16-bit chunk. // Save this 16-bit chunk.
p[j] = byte(n>>8); p[j] = byte(n >> 8);
p[j+1] = byte(n); p[j+1] = byte(n);
j += 2; j += 2;
@ -394,11 +394,11 @@ L: for j < IPv6len {
if ellipsis < 0 { if ellipsis < 0 {
return nil return nil
} }
n := IPv6len-j; n := IPv6len - j;
for k := j-1; k >= ellipsis; k-- { for k := j - 1; k >= ellipsis; k-- {
p[k+n] = p[k] p[k+n] = p[k]
} }
for k := ellipsis+n-1; k >= ellipsis; k-- { for k := ellipsis + n - 1; k >= ellipsis; k-- {
p[k] = 0 p[k] = 0
} }
} }

View file

@ -153,7 +153,7 @@ func splitHostPort(hostport string) (host, port string, err os.Error) {
return; return;
} }
host, port = hostport[0:i], hostport[i+1 : len(hostport)]; host, port = hostport[0:i], hostport[i+1:len(hostport)];
// Can put brackets around host ... // Can put brackets around host ...
if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
@ -173,9 +173,9 @@ func splitHostPort(hostport string) (host, port string, err os.Error) {
func joinHostPort(host, port string) string { func joinHostPort(host, port string) string {
// If host has colons, have to bracket it. // If host has colons, have to bracket it.
if byteIndex(host, ':') >= 0 { if byteIndex(host, ':') >= 0 {
return "["+host+"]:"+port return "[" + host + "]:" + port
} }
return host+":"+port; return host + ":" + port;
} }
// Convert "host:port" into IP address and port. // Convert "host:port" into IP address and port.

View file

@ -164,7 +164,7 @@ func Dial(net, laddr, raddr string) (c Conn, err os.Error) {
} }
err = UnknownNetworkError(net); err = UnknownNetworkError(net);
Error: Error:
return nil, &OpError{"dial", net+" "+raddr, nil, err}; return nil, &OpError{"dial", net + " " + raddr, nil, err};
} }
// Listen announces on the local network address laddr. // Listen announces on the local network address laddr.

View file

@ -27,7 +27,7 @@ func (f *file) getLineFromData() (s string, ok bool) {
ok = true; ok = true;
// move data // move data
i++; i++;
n := len(data)-i; n := len(data) - i;
for j := 0; j < n; j++ { for j := 0; j < n; j++ {
data[j] = data[i+j] data[j] = data[i+j]
} }
@ -83,7 +83,7 @@ func countAnyByte(s string, t string) int {
// Split s at any bytes in t. // Split s at any bytes in t.
func splitAtBytes(s string, t string) []string { func splitAtBytes(s string, t string) []string {
a := make([]string, 1 + countAnyByte(s, t)); a := make([]string, 1+countAnyByte(s, t));
n := 0; n := 0;
last := 0; last := 0;
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
@ -92,7 +92,7 @@ func splitAtBytes(s string, t string) []string {
a[n] = string(s[last:i]); a[n] = string(s[last:i]);
n++; n++;
} }
last = i+1; last = i + 1;
} }
} }
if last < len(s) { if last < len(s) {
@ -130,13 +130,13 @@ func xtoi(s string, i0 int) (n int, i int, ok bool) {
for i = i0; i < len(s); i++ { for i = i0; i < len(s); i++ {
if '0' <= s[i] && s[i] <= '9' { if '0' <= s[i] && s[i] <= '9' {
n *= 16; n *= 16;
n += int(s[i]-'0'); n += int(s[i] - '0');
} else if 'a' <= s[i] && s[i] <= 'f' { } else if 'a' <= s[i] && s[i] <= 'f' {
n *= 16; n *= 16;
n += int(s[i]-'a')+10; n += int(s[i]-'a') + 10;
} else if 'A' <= s[i] && s[i] <= 'F' { } else if 'A' <= s[i] && s[i] <= 'F' {
n *= 16; n *= 16;
n += int(s[i]-'A')+10; n += int(s[i]-'A') + 10;
} else { } else {
break break
} }

View file

@ -41,6 +41,6 @@ func TestReadLine(t *testing.T) {
break break
} }
lineno++; lineno++;
byteno += len(line)+1; byteno += len(line) + 1;
} }
} }

View file

@ -63,5 +63,5 @@ func LookupPort(network, service string) (port int, err os.Error) {
return return
} }
} }
return 0, &AddrError{"unknown port", network+"/"+service}; return 0, &AddrError{"unknown port", network + "/" + service};
} }

View file

@ -48,7 +48,7 @@ func runServe(t *testing.T, network, addr string, listening chan<- string, done
func connect(t *testing.T, network, addr string) { func connect(t *testing.T, network, addr string) {
var laddr string; var laddr string;
if network == "unixgram" { if network == "unixgram" {
laddr = addr+".local" laddr = addr + ".local"
} }
fd, err := Dial(network, laddr, addr); fd, err := Dial(network, laddr, addr);
if err != nil { if err != nil {
@ -80,7 +80,7 @@ func doTest(t *testing.T, network, listenaddr, dialaddr string) {
go runServe(t, network, listenaddr, listening, done); go runServe(t, network, listenaddr, listening, done);
addr := <-listening; // wait for server to start addr := <-listening; // wait for server to start
if network == "tcp" { if network == "tcp" {
dialaddr += addr[strings.LastIndex(addr, ":") : len(addr)] dialaddr += addr[strings.LastIndex(addr, ":"):len(addr)]
} }
connect(t, network, dialaddr); connect(t, network, dialaddr);
<-done; // make sure server stopped <-done; // make sure server stopped
@ -141,7 +141,7 @@ func doTestPacket(t *testing.T, network, listenaddr, dialaddr string) {
go runPacket(t, network, listenaddr, listening, done); go runPacket(t, network, listenaddr, listening, done);
addr := <-listening; // wait for server to start addr := <-listening; // wait for server to start
if network == "udp" { if network == "udp" {
dialaddr += addr[strings.LastIndex(addr, ":") : len(addr)] dialaddr += addr[strings.LastIndex(addr, ":"):len(addr)]
} }
connect(t, network, dialaddr); connect(t, network, dialaddr);
<-done; // tell server to stop <-done; // tell server to stop

View file

@ -59,7 +59,7 @@ func (file *File) Readdirnames(count int) (names []string, err Error) {
continue continue
} }
bytes := (*[len(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0])); bytes := (*[len(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0]));
var name = string(bytes[0 : dirent.Namlen]); var name = string(bytes[0:dirent.Namlen]);
if name == "." || name == ".." { // Useless names if name == "." || name == ".." { // Useless names
continue continue
} }

View file

@ -78,7 +78,7 @@ func Environ() []string {
// check i < len(a) for safety, // check i < len(a) for safety,
// in case env is changing underfoot. // in case env is changing underfoot.
if i < len(a) { if i < len(a) {
a[i] = k+"="+v; a[i] = k + "=" + v;
i++; i++;
} }
} }

View file

@ -67,7 +67,7 @@ const (
WNOHANG = syscall.WNOHANG; // Don't wait if no process has exited. WNOHANG = syscall.WNOHANG; // Don't wait if no process has exited.
WSTOPPED = syscall.WSTOPPED; // If set, status of stopped subprocesses is also reported. WSTOPPED = syscall.WSTOPPED; // If set, status of stopped subprocesses is also reported.
WUNTRACED = WSTOPPED; WUNTRACED = WSTOPPED;
WRUSAGE = 1<<20; // Record resource usage. WRUSAGE = 1 << 20; // Record resource usage.
) )
// WRUSAGE must not be too high a bit, to avoid clashing with Linux's // WRUSAGE must not be too high a bit, to avoid clashing with Linux's
@ -111,7 +111,7 @@ func itod(i int) string {
bp := len(b); bp := len(b);
for ; u > 0; u /= 10 { for ; u > 0; u /= 10 {
bp--; bp--;
b[bp] = byte(u%10)+'0'; b[bp] = byte(u%10) + '0';
} }
if i < 0 { if i < 0 {

View file

@ -68,7 +68,7 @@ const (
// if applicable. If successful, methods on the returned File can be used for I/O. // if applicable. If successful, methods on the returned File can be used for I/O.
// It returns the File and an Error, if any. // It returns the File and an Error, if any.
func Open(name string, flag int, perm int) (file *File, err Error) { func Open(name string, flag int, perm int) (file *File, err Error) {
r, e := syscall.Open(name, flag | syscall.O_CLOEXEC, perm); r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm);
if e != 0 { if e != 0 {
return nil, &PathError{"open", name, Errno(e)} return nil, &PathError{"open", name, Errno(e)}
} }
@ -260,7 +260,7 @@ func Stat(name string) (dir *Dir, err Error) {
return nil, &PathError{"stat", name, Errno(e)} return nil, &PathError{"stat", name, Errno(e)}
} }
statp := &lstat; statp := &lstat;
if lstat.Mode & syscall.S_IFMT == syscall.S_IFLNK { if lstat.Mode&syscall.S_IFMT == syscall.S_IFLNK {
e := syscall.Stat(name, &stat); e := syscall.Stat(name, &stat);
if e == 0 { if e == 0 {
statp = &stat statp = &stat
@ -309,7 +309,7 @@ func (file *File) Readdir(count int) (dirs []Dir, err Error) {
} }
dirs = make([]Dir, len(names)); dirs = make([]Dir, len(names));
for i, filename := range names { for i, filename := range names {
dirp, err := Lstat(dirname+filename); dirp, err := Lstat(dirname + filename);
if dirp == nil || err != nil { if dirp == nil || err != nil {
dirs[i].Name = filename // rest is already zeroed out dirs[i].Name = filename // rest is already zeroed out
} else { } else {

View file

@ -50,7 +50,7 @@ func Getwd() (string, Error) {
// and then find name of parent. Each iteration // and then find name of parent. Each iteration
// adds /name to the beginning of pwd. // adds /name to the beginning of pwd.
pwd = ""; pwd = "";
for parent := ".."; ; parent = "../"+parent { for parent := ".."; ; parent = "../" + parent {
if len(parent) >= 1024 { // Sanity check if len(parent) >= 1024 { // Sanity check
return "", ENAMETOOLONG return "", ENAMETOOLONG
} }
@ -66,9 +66,9 @@ func Getwd() (string, Error) {
return "", err; return "", err;
} }
for _, name := range names { for _, name := range names {
d, _ := Lstat(parent+"/"+name); d, _ := Lstat(parent + "/" + name);
if d.Dev == dot.Dev && d.Ino == dot.Ino { if d.Dev == dot.Dev && d.Ino == dot.Ino {
pwd = "/"+name+pwd; pwd = "/" + name + pwd;
goto Found; goto Found;
} }
} }

View file

@ -297,7 +297,7 @@ func TestSymLink(t *testing.T) {
func TestLongSymlink(t *testing.T) { func TestLongSymlink(t *testing.T) {
s := "0123456789abcdef"; s := "0123456789abcdef";
s = s+s+s+s+s+s+s+s+s+s+s+s+s+s+s+s+s; s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s;
from := "longsymlinktestfrom"; from := "longsymlinktestfrom";
err := Symlink(s, from); err := Symlink(s, from);
if err != nil { if err != nil {
@ -339,7 +339,7 @@ func checkMode(t *testing.T, path string, mode uint32) {
if err != nil { if err != nil {
t.Fatalf("Stat %q (looking for mode %#o): %s", path, mode, err) t.Fatalf("Stat %q (looking for mode %#o): %s", path, mode, err)
} }
if dir.Mode & 0777 != mode { if dir.Mode&0777 != mode {
t.Errorf("Stat %q: mode %#o want %#o", path, dir.Mode, 0777) t.Errorf("Stat %q: mode %#o want %#o", path, dir.Mode, 0777)
} }
} }
@ -539,9 +539,9 @@ func TestSeek(t *testing.T) {
test{5, 0, 5}, test{5, 0, 5},
test{0, 2, int64(len(data))}, test{0, 2, int64(len(data))},
test{0, 0, 0}, test{0, 0, 0},
test{-1, 2, int64(len(data))-1}, test{-1, 2, int64(len(data)) - 1},
test{1<<40, 0, 1<<40}, test{1 << 40, 0, 1 << 40},
test{1<<40, 2, 1<<40 + int64(len(data))}, test{1 << 40, 2, 1<<40 + int64(len(data))},
}; };
for i, tt := range tests { for i, tt := range tests {
off, err := f.Seek(tt.in, tt.whence); off, err := f.Seek(tt.in, tt.whence);

View file

@ -35,7 +35,7 @@ func MkdirAll(path string, perm int) Error {
if j > 0 { if j > 0 {
// Create parent // Create parent
err = MkdirAll(path[0 : j-1], perm); err = MkdirAll(path[0:j-1], perm);
if err != nil { if err != nil {
return err return err
} }
@ -91,7 +91,7 @@ func RemoveAll(path string) Error {
for { for {
names, err1 := fd.Readdirnames(100); names, err1 := fd.Readdirnames(100);
for _, name := range names { for _, name := range names {
err1 := RemoveAll(path+"/"+name); err1 := RemoveAll(path + "/" + name);
if err == nil { if err == nil {
err = err1 err = err1
} }

View file

@ -25,7 +25,7 @@ func TestMkdirAll(t *testing.T) {
} }
// Make file. // Make file.
fpath := path+"/file"; fpath := path + "/file";
_, err = Open(fpath, O_WRONLY|O_CREAT, 0666); _, err = Open(fpath, O_WRONLY|O_CREAT, 0666);
if err != nil { if err != nil {
t.Fatalf("create %q: %s", fpath, err) t.Fatalf("create %q: %s", fpath, err)
@ -64,8 +64,8 @@ func TestMkdirAll(t *testing.T) {
func TestRemoveAll(t *testing.T) { func TestRemoveAll(t *testing.T) {
// Work directory. // Work directory.
path := "_obj/_TestRemoveAll_"; path := "_obj/_TestRemoveAll_";
fpath := path+"/file"; fpath := path + "/file";
dpath := path+"/dir"; dpath := path + "/dir";
// Make directory with 1 file and remove. // Make directory with 1 file and remove.
if err := MkdirAll(path, 0777); err != nil { if err := MkdirAll(path, 0777); err != nil {
@ -109,7 +109,7 @@ func TestRemoveAll(t *testing.T) {
t.Fatalf("MkdirAll %q: %s", dpath, err) t.Fatalf("MkdirAll %q: %s", dpath, err)
} }
for _, s := range []string{fpath, dpath+"/file1", path+"/zzz"} { for _, s := range []string{fpath, dpath + "/file1", path + "/zzz"} {
fd, err = Open(s, O_WRONLY|O_CREAT, 0666); fd, err = Open(s, O_WRONLY|O_CREAT, 0666);
if err != nil { if err != nil {
t.Fatalf("create %q: %s", s, err) t.Fatalf("create %q: %s", s, err)
@ -136,7 +136,7 @@ func TestRemoveAll(t *testing.T) {
if err = Chmod(dpath, 0777); err != nil { if err = Chmod(dpath, 0777); err != nil {
t.Fatalf("Chmod %q 0777: %s", dpath, err) t.Fatalf("Chmod %q 0777: %s", dpath, err)
} }
for _, s := range []string{fpath, path+"/zzz"} { for _, s := range []string{fpath, path + "/zzz"} {
if _, err := Lstat(s); err == nil { if _, err := Lstat(s); err == nil {
t.Fatalf("Lstat %q succeeded after partial RemoveAll", s) t.Fatalf("Lstat %q succeeded after partial RemoveAll", s)
} }

View file

@ -7,7 +7,7 @@ package os
import "syscall" import "syscall"
func isSymlink(stat *syscall.Stat_t) bool { func isSymlink(stat *syscall.Stat_t) bool {
return stat.Mode & syscall.S_IFMT == syscall.S_IFLNK return stat.Mode&syscall.S_IFMT == syscall.S_IFLNK
} }
func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir { func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
@ -24,7 +24,7 @@ func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
dir.Atime_ns = uint64(syscall.TimespecToNsec(stat.Atimespec)); dir.Atime_ns = uint64(syscall.TimespecToNsec(stat.Atimespec));
dir.Mtime_ns = uint64(syscall.TimespecToNsec(stat.Mtimespec)); dir.Mtime_ns = uint64(syscall.TimespecToNsec(stat.Mtimespec));
dir.Ctime_ns = uint64(syscall.TimespecToNsec(stat.Ctimespec)); dir.Ctime_ns = uint64(syscall.TimespecToNsec(stat.Ctimespec));
for i := len(name)-1; i >= 0; i-- { for i := len(name) - 1; i >= 0; i-- {
if name[i] == '/' { if name[i] == '/' {
name = name[i+1 : len(name)]; name = name[i+1 : len(name)];
break; break;

View file

@ -7,7 +7,7 @@ package os
import "syscall" import "syscall"
func isSymlink(stat *syscall.Stat_t) bool { func isSymlink(stat *syscall.Stat_t) bool {
return stat.Mode & syscall.S_IFMT == syscall.S_IFLNK return stat.Mode&syscall.S_IFMT == syscall.S_IFLNK
} }
func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir { func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
@ -24,7 +24,7 @@ func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
dir.Atime_ns = uint64(syscall.TimespecToNsec(stat.Atim)); dir.Atime_ns = uint64(syscall.TimespecToNsec(stat.Atim));
dir.Mtime_ns = uint64(syscall.TimespecToNsec(stat.Mtim)); dir.Mtime_ns = uint64(syscall.TimespecToNsec(stat.Mtim));
dir.Ctime_ns = uint64(syscall.TimespecToNsec(stat.Ctim)); dir.Ctime_ns = uint64(syscall.TimespecToNsec(stat.Ctim));
for i := len(name)-1; i >= 0; i-- { for i := len(name) - 1; i >= 0; i-- {
if name[i] == '/' { if name[i] == '/' {
name = name[i+1 : len(name)]; name = name[i+1 : len(name)];
break; break;

View file

@ -7,7 +7,7 @@ package os
import "syscall" import "syscall"
func isSymlink(stat *syscall.Stat_t) bool { func isSymlink(stat *syscall.Stat_t) bool {
return stat.Mode & syscall.S_IFMT == syscall.S_IFLNK return stat.Mode&syscall.S_IFMT == syscall.S_IFLNK
} }
func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir { func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
@ -21,10 +21,10 @@ func dirFromStat(name string, dir *Dir, lstat, stat *syscall.Stat_t) *Dir {
dir.Size = uint64(stat.Size); dir.Size = uint64(stat.Size);
dir.Blksize = uint64(stat.Blksize); dir.Blksize = uint64(stat.Blksize);
dir.Blocks = uint64(stat.Blocks); dir.Blocks = uint64(stat.Blocks);
dir.Atime_ns = uint64(stat.Atime)*1e9; dir.Atime_ns = uint64(stat.Atime) * 1e9;
dir.Mtime_ns = uint64(stat.Mtime)*1e9; dir.Mtime_ns = uint64(stat.Mtime) * 1e9;
dir.Ctime_ns = uint64(stat.Ctime)*1e9; dir.Ctime_ns = uint64(stat.Ctime) * 1e9;
for i := len(name)-1; i >= 0; i-- { for i := len(name) - 1; i >= 0; i-- {
if name[i] == '/' { if name[i] == '/' {
name = name[i+1 : len(name)]; name = name[i+1 : len(name)];
break; break;

View file

@ -16,5 +16,5 @@ func Time() (sec int64, nsec int64, err Error) {
if errno := syscall.Gettimeofday(&tv); errno != 0 { if errno := syscall.Gettimeofday(&tv); errno != 0 {
return 0, 0, NewSyscallError("gettimeofday", errno) return 0, 0, NewSyscallError("gettimeofday", errno)
} }
return int64(tv.Sec), int64(tv.Usec)*1000, err; return int64(tv.Sec), int64(tv.Usec) * 1000, err;
} }

View file

@ -44,11 +44,11 @@ func (d *GITBinaryLiteral) Apply(old []byte) ([]byte, os.Error) {
func unhex(c byte) uint8 { func unhex(c byte) uint8 {
switch { switch {
case '0' <= c && c <= '9': case '0' <= c && c <= '9':
return c-'0' return c - '0'
case 'a' <= c && c <= 'f': case 'a' <= c && c <= 'f':
return c-'a'+10 return c - 'a' + 10
case 'A' <= c && c <= 'F': case 'A' <= c && c <= 'F':
return c-'A'+10 return c - 'A' + 10
} }
return 255; return 255;
} }
@ -61,7 +61,7 @@ func getHex(s []byte) (data []byte, rest []byte) {
n &^= 1; // Only take an even number of hex digits. n &^= 1; // Only take an even number of hex digits.
data = make([]byte, n/2); data = make([]byte, n/2);
for i := range data { for i := range data {
data[i] = unhex(s[2*i])<<4 | unhex(s[2*i + 1]) data[i] = unhex(s[2*i])<<4 | unhex(s[2*i+1])
} }
rest = s[n:len(s)]; rest = s[n:len(s)];
return; return;

View file

@ -112,7 +112,7 @@ func ParseTextDiff(raw []byte) (TextDiff, os.Error) {
if oldLine+delta != newLine { if oldLine+delta != newLine {
return nil, SyntaxError("chunk delta is out of sync with previous chunks") return nil, SyntaxError("chunk delta is out of sync with previous chunks")
} }
delta += nnew-nold; delta += nnew - nold;
c.Line = oldLine; c.Line = oldLine;
var old, new bytes.Buffer; var old, new bytes.Buffer;
@ -157,7 +157,7 @@ func (d TextDiff) Apply(data []byte) ([]byte, os.Error) {
for _, c := range d { for _, c := range d {
var ok bool; var ok bool;
var prefix []byte; var prefix []byte;
prefix, data, ok = getLine(data, c.Line - line); prefix, data, ok = getLine(data, c.Line-line);
if !ok || !bytes.HasPrefix(data, c.Old) { if !ok || !bytes.HasPrefix(data, c.Old) {
return nil, ErrPatchFailure return nil, ErrPatchFailure
} }

View file

@ -107,7 +107,7 @@ func Clean(path string) string {
// If there is no slash in path, DirFile returns an empty dir and // If there is no slash in path, DirFile returns an empty dir and
// file set to path. // file set to path.
func Split(path string) (dir, file string) { func Split(path string) (dir, file string) {
for i := len(path)-1; i >= 0; i-- { for i := len(path) - 1; i >= 0; i-- {
if path[i] == '/' { if path[i] == '/' {
return path[0 : i+1], path[i+1 : len(path)] return path[0 : i+1], path[i+1 : len(path)]
} }
@ -121,7 +121,7 @@ func Join(dir, file string) string {
if dir == "" { if dir == "" {
return file return file
} }
return Clean(dir+"/"+file); return Clean(dir + "/" + file);
} }
// Ext returns the file name extension used by path. // Ext returns the file name extension used by path.
@ -129,7 +129,7 @@ func Join(dir, file string) string {
// in the final slash-separated element of path; // in the final slash-separated element of path;
// it is empty if there is no dot. // it is empty if there is no dot.
func Ext(path string) string { func Ext(path string) string {
for i := len(path)-1; i >= 0 && path[i] != '/'; i-- { for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
if path[i] == '.' { if path[i] == '.' {
return path[i:len(path)] return path[i:len(path)]
} }

View file

@ -31,15 +31,15 @@ const (
func (r *Rand) ExpFloat64() float64 { func (r *Rand) ExpFloat64() float64 {
for { for {
j := r.Uint32(); j := r.Uint32();
i := j&0xFF; i := j & 0xFF;
x := float64(j)*float64(we[i]); x := float64(j) * float64(we[i]);
if j < ke[i] { if j < ke[i] {
return x return x
} }
if i == 0 { if i == 0 {
return re - math.Log(r.Float64()) return re - math.Log(r.Float64())
} }
if fe[i] + float32(r.Float64())*(fe[i-1]-fe[i]) < float32(math.Exp(-x)) { if fe[i]+float32(r.Float64())*(fe[i-1]-fe[i]) < float32(math.Exp(-x)) {
return x return x
} }
} }

View file

@ -38,8 +38,8 @@ func absInt32(i int32) uint32 {
func (r *Rand) NormFloat64() float64 { func (r *Rand) NormFloat64() float64 {
for { for {
j := int32(r.Uint32()); // Possibly negative j := int32(r.Uint32()); // Possibly negative
i := j&0x7F; i := j & 0x7F;
x := float64(j)*float64(wn[i]); x := float64(j) * float64(wn[i]);
if absInt32(j) < kn[i] { if absInt32(j) < kn[i] {
// This case should be hit better than 99% of the time. // This case should be hit better than 99% of the time.
return x return x
@ -48,18 +48,18 @@ func (r *Rand) NormFloat64() float64 {
if i == 0 { if i == 0 {
// This extra work is only required for the base strip. // This extra work is only required for the base strip.
for { for {
x = -math.Log(r.Float64()) * (1.0/rn); x = -math.Log(r.Float64()) * (1.0 / rn);
y := -math.Log(r.Float64()); y := -math.Log(r.Float64());
if y+y >= x*x { if y+y >= x*x {
break break
} }
} }
if j > 0 { if j > 0 {
return rn+x return rn + x
} }
return -rn - x; return -rn - x;
} }
if fn[i] + float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5 * x * x)) { if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) {
return x return x
} }
} }

View file

@ -43,7 +43,7 @@ func (r *Rand) Int31() int32 { return int32(r.Int63() >> 32) }
// Int returns a non-negative pseudo-random int. // Int returns a non-negative pseudo-random int.
func (r *Rand) Int() int { func (r *Rand) Int() int {
u := uint(r.Int63()); u := uint(r.Int63());
return int(u<<1>>1); // clear sign bit if int == int32 return int(u << 1 >> 1); // clear sign bit if int == int32
} }
// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
@ -51,12 +51,12 @@ func (r *Rand) Int63n(n int64) int64 {
if n <= 0 { if n <= 0 {
return 0 return 0
} }
max := int64((1<<63) - 1 - (1<<63)%uint64(n)); max := int64((1 << 63) - 1 - (1<<63)%uint64(n));
v := r.Int63(); v := r.Int63();
for v > max { for v > max {
v = r.Int63() v = r.Int63()
} }
return v%n; return v % n;
} }
// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
@ -66,7 +66,7 @@ func (r *Rand) Int31n(n int32) int32 { return int32(r.Int63n(int64(n))) }
func (r *Rand) Intn(n int) int { return int(r.Int63n(int64(n))) } func (r *Rand) Intn(n int) int { return int(r.Int63n(int64(n))) }
// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
func (r *Rand) Float64() float64 { return float64(r.Int63())/(1<<63) } func (r *Rand) Float64() float64 { return float64(r.Int63()) / (1 << 63) }
// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
func (r *Rand) Float32() float32 { return float32(r.Float64()) } func (r *Rand) Float32() float32 { return float32(r.Float64()) }
@ -81,7 +81,7 @@ func (r *Rand) Perm(n int) []int {
m[i] = i m[i] = i
} }
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
j := r.Intn(i+1); j := r.Intn(i + 1);
m[i], m[j] = m[j], m[i]; m[i], m[j] = m[j], m[i];
} }
return m; return m;

View file

@ -30,11 +30,11 @@ func max(a, b float64) float64 {
} }
func nearEqual(a, b, closeEnough, maxError float64) bool { func nearEqual(a, b, closeEnough, maxError float64) bool {
absDiff := math.Fabs(a-b); absDiff := math.Fabs(a - b);
if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero. if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
return true return true
} }
return absDiff / max(math.Fabs(a), math.Fabs(b)) < maxError; return absDiff/max(math.Fabs(a), math.Fabs(b)) < maxError;
} }
var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961} var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961}
@ -61,12 +61,12 @@ func getStatsResults(samples []float64) *statsResults {
for i := range samples { for i := range samples {
sum += samples[i] sum += samples[i]
} }
res.mean = sum/float64(len(samples)); res.mean = sum / float64(len(samples));
var devsum float64; var devsum float64;
for i := range samples { for i := range samples {
devsum += math.Pow(samples[i] - res.mean, 2) devsum += math.Pow(samples[i]-res.mean, 2)
} }
res.stddev = math.Sqrt(devsum/float64(len(samples))); res.stddev = math.Sqrt(devsum / float64(len(samples)));
return res; return res;
} }
@ -79,14 +79,14 @@ func checkSampleDistribution(t *testing.T, samples []float64, expected *statsRes
} }
func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) { func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) {
chunk := len(samples)/nslices; chunk := len(samples) / nslices;
for i := 0; i < nslices; i++ { for i := 0; i < nslices; i++ {
low := i*chunk; low := i * chunk;
var high int; var high int;
if i == nslices-1 { if i == nslices-1 {
high = len(samples)-1 high = len(samples) - 1
} else { } else {
high = (i+1)*chunk high = (i + 1) * chunk
} }
checkSampleDistribution(t, samples[low:high], expected); checkSampleDistribution(t, samples[low:high], expected);
} }
@ -100,7 +100,7 @@ func generateNormalSamples(nsamples int, mean, stddev float64, seed int64) []flo
r := New(NewSource(seed)); r := New(NewSource(seed));
samples := make([]float64, nsamples); samples := make([]float64, nsamples);
for i := range samples { for i := range samples {
samples[i] = r.NormFloat64() * stddev + mean samples[i] = r.NormFloat64()*stddev + mean
} }
return samples; return samples;
} }
@ -156,7 +156,7 @@ func generateExponentialSamples(nsamples int, rate float64, seed int64) []float6
func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed int64) { func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed int64) {
//fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed); //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed);
mean := 1/rate; mean := 1 / rate;
stddev := mean; stddev := mean;
samples := generateExponentialSamples(nsamples, rate, seed); samples := generateExponentialSamples(nsamples, rate, seed);
@ -194,7 +194,7 @@ func TestNonStandardExponentialValues(t *testing.T) {
// //
func initNorm() (testKn []uint32, testWn, testFn []float32) { func initNorm() (testKn []uint32, testWn, testFn []float32) {
const m1 = 1<<31; const m1 = 1 << 31;
var ( var (
dn float64 = rn; dn float64 = rn;
tn = dn; tn = dn;
@ -205,25 +205,25 @@ func initNorm() (testKn []uint32, testWn, testFn []float32) {
testWn = make([]float32, 128); testWn = make([]float32, 128);
testFn = make([]float32, 128); testFn = make([]float32, 128);
q := vn / math.Exp(-0.5 * dn * dn); q := vn / math.Exp(-0.5*dn*dn);
testKn[0] = uint32((dn/q)*m1); testKn[0] = uint32((dn / q) * m1);
testKn[1] = 0; testKn[1] = 0;
testWn[0] = float32(q/m1); testWn[0] = float32(q / m1);
testWn[127] = float32(dn/m1); testWn[127] = float32(dn / m1);
testFn[0] = 1.0; testFn[0] = 1.0;
testFn[127] = float32(math.Exp(-0.5 * dn * dn)); testFn[127] = float32(math.Exp(-0.5 * dn * dn));
for i := 126; i >= 1; i-- { for i := 126; i >= 1; i-- {
dn = math.Sqrt(-2.0 * math.Log(vn/dn + math.Exp(-0.5 * dn * dn))); dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn)));
testKn[i+1] = uint32((dn/tn)*m1); testKn[i+1] = uint32((dn / tn) * m1);
tn = dn; tn = dn;
testFn[i] = float32(math.Exp(-0.5 * dn * dn)); testFn[i] = float32(math.Exp(-0.5 * dn * dn));
testWn[i] = float32(dn/m1); testWn[i] = float32(dn / m1);
} }
return; return;
} }
func initExp() (testKe []uint32, testWe, testFe []float32) { func initExp() (testKe []uint32, testWe, testFe []float32) {
const m2 = 1<<32; const m2 = 1 << 32;
var ( var (
de float64 = re; de float64 = re;
te = de; te = de;
@ -235,18 +235,18 @@ func initExp() (testKe []uint32, testWe, testFe []float32) {
testFe = make([]float32, 256); testFe = make([]float32, 256);
q := ve / math.Exp(-de); q := ve / math.Exp(-de);
testKe[0] = uint32((de/q)*m2); testKe[0] = uint32((de / q) * m2);
testKe[1] = 0; testKe[1] = 0;
testWe[0] = float32(q/m2); testWe[0] = float32(q / m2);
testWe[255] = float32(de/m2); testWe[255] = float32(de / m2);
testFe[0] = 1.0; testFe[0] = 1.0;
testFe[255] = float32(math.Exp(-de)); testFe[255] = float32(math.Exp(-de));
for i := 254; i >= 1; i-- { for i := 254; i >= 1; i-- {
de = -math.Log(ve/de + math.Exp(-de)); de = -math.Log(ve/de + math.Exp(-de));
testKe[i+1] = uint32((de/te)*m2); testKe[i+1] = uint32((de / te) * m2);
te = de; te = de;
testFe[i] = float32(math.Exp(-de)); testFe[i] = float32(math.Exp(-de));
testWe[i] = float32(de/m2); testWe[i] = float32(de / m2);
} }
return; return;
} }
@ -257,9 +257,9 @@ func initExp() (testKe []uint32, testWe, testFe []float32) {
func compareUint32Slices(s1, s2 []uint32) int { func compareUint32Slices(s1, s2 []uint32) int {
if len(s1) != len(s2) { if len(s1) != len(s2) {
if len(s1) > len(s2) { if len(s1) > len(s2) {
return len(s2)+1 return len(s2) + 1
} }
return len(s1)+1; return len(s1) + 1;
} }
for i := range s1 { for i := range s1 {
if s1[i] != s2[i] { if s1[i] != s2[i] {
@ -275,9 +275,9 @@ func compareUint32Slices(s1, s2 []uint32) int {
func compareFloat32Slices(s1, s2 []float32) int { func compareFloat32Slices(s1, s2 []float32) int {
if len(s1) != len(s2) { if len(s1) != len(s2) {
if len(s1) > len(s2) { if len(s1) > len(s2) {
return len(s2)+1 return len(s2) + 1
} }
return len(s1)+1; return len(s1) + 1;
} }
for i := range s1 { for i := range s1 {
if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) { if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) {

View file

@ -14,10 +14,10 @@ package rand
const ( const (
_LEN = 607; _LEN = 607;
_TAP = 273; _TAP = 273;
_MAX = 1<<63; _MAX = 1 << 63;
_MASK = _MAX-1; _MASK = _MAX - 1;
_A = 48271; _A = 48271;
_M = (1<<31)-1; _M = (1 << 31) - 1;
_Q = 44488; _Q = 44488;
_R = 3399; _R = 3399;
) )
@ -190,8 +190,8 @@ type rngSource struct {
// seed rng x[n+1] = 48271 * x[n] mod (2**31 - 1) // seed rng x[n+1] = 48271 * x[n] mod (2**31 - 1)
func seedrand(x int32) int32 { func seedrand(x int32) int32 {
hi := x/_Q; hi := x / _Q;
lo := x%_Q; lo := x % _Q;
x = _A*lo - _R*hi; x = _A*lo - _R*hi;
if x < 0 { if x < 0 {
x += _M x += _M
@ -202,9 +202,9 @@ func seedrand(x int32) int32 {
// Seed uses the provided seed value to initialize the generator to a deterministic state. // Seed uses the provided seed value to initialize the generator to a deterministic state.
func (rng *rngSource) Seed(seed int64) { func (rng *rngSource) Seed(seed int64) {
rng.tap = 0; rng.tap = 0;
rng.feed = _LEN-_TAP; rng.feed = _LEN - _TAP;
seed = seed%_M; seed = seed % _M;
if seed < 0 { if seed < 0 {
seed += _M seed += _M
} }
@ -217,13 +217,13 @@ func (rng *rngSource) Seed(seed int64) {
x = seedrand(x); x = seedrand(x);
if i >= 0 { if i >= 0 {
var u int64; var u int64;
u = int64(x)<<40; u = int64(x) << 40;
x = seedrand(x); x = seedrand(x);
u ^= int64(x)<<20; u ^= int64(x) << 20;
x = seedrand(x); x = seedrand(x);
u ^= int64(x); u ^= int64(x);
u ^= rng_cooked[i]; u ^= rng_cooked[i];
rng.vec[i] = u&_MASK; rng.vec[i] = u & _MASK;
} }
} }
} }
@ -240,7 +240,7 @@ func (rng *rngSource) Int63() int64 {
rng.feed += _LEN rng.feed += _LEN
} }
x := (rng.vec[rng.feed] + rng.vec[rng.tap])&_MASK; x := (rng.vec[rng.feed] + rng.vec[rng.tap]) & _MASK;
rng.vec[rng.feed] = x; rng.vec[rng.feed] = x;
return x; return x;
} }

View file

@ -966,7 +966,7 @@ type Point struct {
x, y int; x, y int;
} }
func (p Point) Dist(scale int) int { return p.x * p.x * scale + p.y * p.y * scale } func (p Point) Dist(scale int) int { return p.x*p.x*scale + p.y*p.y*scale }
func TestMethod(t *testing.T) { func TestMethod(t *testing.T) {
// Non-curried method of type. // Non-curried method of type.

View file

@ -161,9 +161,9 @@ type ArrayType struct {
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.
@ -482,7 +482,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

View file

@ -25,17 +25,17 @@ func memmove(adst, asrc addr, n uintptr) {
// careful: i is unsigned // careful: i is unsigned
for i := n; i > 0; { for i := n; i > 0; {
i--; i--;
*(*byte)(addr(dst+i)) = *(*byte)(addr(src+i)); *(*byte)(addr(dst + i)) = *(*byte)(addr(src + i));
} }
case (n|src|dst)&(ptrSize-1) != 0: case (n|src|dst)&(ptrSize-1) != 0:
// byte copy forward // byte copy forward
for i := uintptr(0); i < n; i++ { for i := uintptr(0); i < n; i++ {
*(*byte)(addr(dst+i)) = *(*byte)(addr(src+i)) *(*byte)(addr(dst + i)) = *(*byte)(addr(src + i))
} }
default: default:
// word copy forward // word copy forward
for i := uintptr(0); i < n; i += ptrSize { for i := uintptr(0); i < n; i += ptrSize {
*(*uintptr)(addr(dst+i)) = *(*uintptr)(addr(src+i)) *(*uintptr)(addr(dst + i)) = *(*uintptr)(addr(src + i))
} }
} }
} }
@ -472,7 +472,7 @@ func ArrayCopy(dst, src ArrayOrSliceValue) int {
if xn := src.Len(); n > xn { if xn := src.Len(); n > xn {
n = xn n = xn
} }
memmove(dst.addr(), src.addr(), uintptr(n) * de.Size()); memmove(dst.addr(), src.addr(), uintptr(n)*de.Size());
return n; return n;
} }
@ -510,7 +510,7 @@ func (v *ArrayValue) Elem(i int) Value {
if i < 0 || i >= n { if i < 0 || i >= n {
panic("index", i, "in array len", n) panic("index", i, "in array len", n)
} }
p := addr(uintptr(v.addr()) + uintptr(i) * typ.Size()); p := addr(uintptr(v.addr()) + uintptr(i)*typ.Size());
return newValue(typ, p, v.canSet); return newValue(typ, p, v.canSet);
} }
@ -575,9 +575,9 @@ func (v *SliceValue) Slice(beg, end int) *SliceValue {
} }
typ := v.typ.(*SliceType); typ := v.typ.(*SliceType);
s := new(SliceHeader); s := new(SliceHeader);
s.Data = uintptr(v.addr()) + uintptr(beg) * typ.Elem().Size(); s.Data = uintptr(v.addr()) + uintptr(beg)*typ.Elem().Size();
s.Len = end-beg; s.Len = end - beg;
s.Cap = cap-beg; s.Cap = cap - beg;
return newValue(typ, addr(s), v.canSet).(*SliceValue); return newValue(typ, addr(s), v.canSet).(*SliceValue);
} }
@ -588,7 +588,7 @@ func (v *SliceValue) Elem(i int) Value {
if i < 0 || i >= n { if i < 0 || i >= n {
panicln("index", i, "in array of length", n) panicln("index", i, "in array of length", n)
} }
p := addr(uintptr(v.addr()) + uintptr(i) * typ.Size()); p := addr(uintptr(v.addr()) + uintptr(i)*typ.Size());
return newValue(typ, p, v.canSet); return newValue(typ, p, v.canSet);
} }
@ -670,7 +670,7 @@ func (v *ChanValue) Cap() int {
// internal send; non-blocking if b != nil // internal send; non-blocking if b != nil
func (v *ChanValue) send(x Value, b *bool) { func (v *ChanValue) send(x Value, b *bool) {
t := v.Type().(*ChanType); t := v.Type().(*ChanType);
if t.Dir() & SendDir == 0 { if t.Dir()&SendDir == 0 {
panic("send on recv-only channel") panic("send on recv-only channel")
} }
typesMustMatch(t.Elem(), x.Type()); typesMustMatch(t.Elem(), x.Type());
@ -681,7 +681,7 @@ func (v *ChanValue) send(x Value, b *bool) {
// internal recv; non-blocking if b != nil // internal recv; non-blocking if b != nil
func (v *ChanValue) recv(b *bool) Value { func (v *ChanValue) recv(b *bool) Value {
t := v.Type().(*ChanType); t := v.Type().(*ChanType);
if t.Dir() & RecvDir == 0 { if t.Dir()&RecvDir == 0 {
panic("recv on send-only channel") panic("recv on send-only channel")
} }
ch := *(**byte)(v.addr); ch := *(**byte)(v.addr);
@ -808,14 +808,14 @@ func (fv *FuncValue) Call(in []Value) []Value {
for i := 0; i < nin; i++ { for i := 0; i < nin; i++ {
tv := t.In(i); tv := t.In(i);
a := uintptr(tv.Align()); a := uintptr(tv.Align());
size = (size+a-1)&^(a-1); size = (size + a - 1) &^ (a - 1);
size += tv.Size(); size += tv.Size();
} }
size = (size + structAlign - 1)&^(structAlign - 1); size = (size + structAlign - 1) &^ (structAlign - 1);
for i := 0; i < nout; i++ { for i := 0; i < nout; i++ {
tv := t.Out(i); tv := t.Out(i);
a := uintptr(tv.Align()); a := uintptr(tv.Align());
size = (size+a-1)&^(a-1); size = (size + a - 1) &^ (a - 1);
size += tv.Size(); size += tv.Size();
} }
@ -856,12 +856,12 @@ func (fv *FuncValue) Call(in []Value) []Value {
tv := v.Type(); tv := v.Type();
typesMustMatch(t.In(i+delta), tv); typesMustMatch(t.In(i+delta), tv);
a := uintptr(tv.Align()); a := uintptr(tv.Align());
off = (off+a-1)&^(a-1); off = (off + a - 1) &^ (a - 1);
n := tv.Size(); n := tv.Size();
memmove(addr(ptr+off), v.getAddr(), n); memmove(addr(ptr+off), v.getAddr(), n);
off += n; off += n;
} }
off = (off + structAlign - 1)&^(structAlign - 1); off = (off + structAlign - 1) &^ (structAlign - 1);
// Call // Call
call(*(**byte)(fv.addr), (*byte)(addr(ptr)), uint32(size)); call(*(**byte)(fv.addr), (*byte)(addr(ptr)), uint32(size));
@ -873,7 +873,7 @@ func (fv *FuncValue) Call(in []Value) []Value {
for i := 0; i < nout; i++ { for i := 0; i < nout; i++ {
tv := t.Out(i); tv := t.Out(i);
a := uintptr(tv.Align()); a := uintptr(tv.Align());
off = (off+a-1)&^(a-1); off = (off + a - 1) &^ (a - 1);
v := MakeZero(tv); v := MakeZero(tv);
n := tv.Size(); n := tv.Size();
memmove(v.getAddr(), addr(ptr+off), n); memmove(v.getAddr(), addr(ptr+off), n);
@ -938,7 +938,7 @@ func (v *InterfaceValue) Method(i int) *FuncValue {
// Interface is two words: itable, data. // Interface is two words: itable, data.
tab := *(**runtime.Itable)(v.addr); tab := *(**runtime.Itable)(v.addr);
data := &value{Typeof((*byte)(nil)), addr(uintptr(v.addr)+ptrSize), true}; data := &value{Typeof((*byte)(nil)), addr(uintptr(v.addr) + ptrSize), true};
// Function pointer is at p.perm in the table. // Function pointer is at p.perm in the table.
fn := tab.Fn[p.perm]; fn := tab.Fn[p.perm];
@ -1141,7 +1141,7 @@ func (v *StructValue) Field(i int) Value {
return nil return nil
} }
f := t.Field(i); f := t.Field(i);
return newValue(f.Type, addr(uintptr(v.addr) + f.Offset), v.canSet && f.PkgPath == ""); return newValue(f.Type, addr(uintptr(v.addr)+f.Offset), v.canSet && f.PkgPath == "");
} }
// FieldByIndex returns the nested field corresponding to index. // FieldByIndex returns the nested field corresponding to index.

View file

@ -101,7 +101,7 @@ func printVec(t *testing.T, m []int) {
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i + 2 {
t.Log("\t", m[i], ",", m[i+1]) t.Log("\t", m[i], ",", m[i+1])
} }
} }
@ -112,7 +112,7 @@ func printStrings(t *testing.T, m []string) {
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i + 2 {
t.Logf("\t%q", m[i]) t.Logf("\t%q", m[i])
} }
} }
@ -123,7 +123,7 @@ func printBytes(t *testing.T, b [][]byte) {
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
for i := 0; i < l; i = i+2 { for i := 0; i < l; i = i + 2 {
t.Logf("\t%q", b[i]) t.Logf("\t%q", b[i])
} }
} }

View file

@ -157,7 +157,7 @@ func (cclass *_CharClass) print() {
} }
for i := 0; i < cclass.ranges.Len(); i += 2 { for i := 0; i < cclass.ranges.Len(); i += 2 {
l := cclass.ranges.At(i); l := cclass.ranges.At(i);
r := cclass.ranges.At(i+1); r := cclass.ranges.At(i + 1);
if l == r { if l == r {
print(" [", string(l), "]") print(" [", string(l), "]")
} else { } else {
@ -173,9 +173,9 @@ func (cclass *_CharClass) addRange(a, b int) {
} }
func (cclass *_CharClass) matches(c int) bool { func (cclass *_CharClass) matches(c int) bool {
for i := 0; i < cclass.ranges.Len(); i = i+2 { for i := 0; i < cclass.ranges.Len(); i = i + 2 {
min := cclass.ranges.At(i); min := cclass.ranges.At(i);
max := cclass.ranges.At(i+1); max := cclass.ranges.At(i + 1);
if min <= c && c <= max { if min <= c && c <= max {
return !cclass.negate return !cclass.negate
} }
@ -262,7 +262,7 @@ func (p *parser) nextc() int {
if p.pos >= len(p.re.expr) { if p.pos >= len(p.re.expr) {
p.ch = endOfFile p.ch = endOfFile
} else { } else {
c, w := utf8.DecodeRuneInString(p.re.expr[p.pos : len(p.re.expr)]); c, w := utf8.DecodeRuneInString(p.re.expr[p.pos:len(p.re.expr)]);
p.ch = c; p.ch = c;
p.pos += w; p.pos += w;
} }
@ -680,7 +680,7 @@ func (re *Regexp) doExecute(str string, bytes []byte, pos int) []int {
for pos <= end { for pos <= end {
if !found { if !found {
// prime the pump if we haven't seen a match yet // prime the pump if we haven't seen a match yet
match := make([]int, 2*(re.nbra + 1)); match := make([]int, 2*(re.nbra+1));
for i := 0; i < len(match); i++ { for i := 0; i < len(match); i++ {
match[i] = -1 // no match seen; catches cases like "a(b)?c" on "ac" match[i] = -1 // no match seen; catches cases like "a(b)?c" on "ac"
} }
@ -735,12 +735,12 @@ func (re *Regexp) doExecute(str string, bytes []byte, pos int) []int {
s[in] = addState(s[in], st.inst.next(), st.match); s[in] = addState(s[in], st.inst.next(), st.match);
case _EBRA: case _EBRA:
n := st.inst.(*_Ebra).n; n := st.inst.(*_Ebra).n;
st.match[2*n + 1] = pos; st.match[2*n+1] = pos;
s[in] = addState(s[in], st.inst.next(), st.match); s[in] = addState(s[in], st.inst.next(), st.match);
case _ALT: case _ALT:
s[in] = addState(s[in], st.inst.(*_Alt).left, st.match); s[in] = addState(s[in], st.inst.(*_Alt).left, st.match);
// give other branch a copy of this match vector // give other branch a copy of this match vector
s1 := make([]int, 2*(re.nbra + 1)); s1 := make([]int, 2*(re.nbra+1));
for i := 0; i < len(s1); i++ { for i := 0; i < len(s1); i++ {
s1[i] = st.match[i] s1[i] = st.match[i]
} }
@ -871,7 +871,7 @@ func (re *Regexp) ReplaceAllString(src, repl string) string {
} }
// Copy the unmatched characters before this match. // Copy the unmatched characters before this match.
io.WriteString(buf, src[lastMatchEnd : a[0]]); io.WriteString(buf, src[lastMatchEnd:a[0]]);
// Now insert a copy of the replacement string, but not for a // Now insert a copy of the replacement string, but not for a
// match of the empty string immediately after another match. // match of the empty string immediately after another match.
@ -883,10 +883,10 @@ func (re *Regexp) ReplaceAllString(src, repl string) string {
lastMatchEnd = a[1]; lastMatchEnd = a[1];
// Advance past this match; always advance at least one character. // Advance past this match; always advance at least one character.
_, width := utf8.DecodeRuneInString(src[searchPos : len(src)]); _, width := utf8.DecodeRuneInString(src[searchPos:len(src)]);
if searchPos + width > a[1] { if searchPos+width > a[1] {
searchPos += width searchPos += width
} else if searchPos + 1 > a[1] { } else if searchPos+1 > a[1] {
// This clause is only needed at the end of the input // This clause is only needed at the end of the input
// string. In that case, DecodeRuneInString returns width=0. // string. In that case, DecodeRuneInString returns width=0.
searchPos++ searchPos++
@ -896,7 +896,7 @@ func (re *Regexp) ReplaceAllString(src, repl string) string {
} }
// Copy the unmatched characters after the last match. // Copy the unmatched characters after the last match.
io.WriteString(buf, src[lastMatchEnd : len(src)]); io.WriteString(buf, src[lastMatchEnd:len(src)]);
return buf.String(); return buf.String();
} }
@ -915,7 +915,7 @@ func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
} }
// Copy the unmatched characters before this match. // Copy the unmatched characters before this match.
buf.Write(src[lastMatchEnd : a[0]]); buf.Write(src[lastMatchEnd:a[0]]);
// Now insert a copy of the replacement string, but not for a // Now insert a copy of the replacement string, but not for a
// match of the empty string immediately after another match. // match of the empty string immediately after another match.
@ -927,10 +927,10 @@ func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
lastMatchEnd = a[1]; lastMatchEnd = a[1];
// Advance past this match; always advance at least one character. // Advance past this match; always advance at least one character.
_, width := utf8.DecodeRune(src[searchPos : len(src)]); _, width := utf8.DecodeRune(src[searchPos:len(src)]);
if searchPos + width > a[1] { if searchPos+width > a[1] {
searchPos += width searchPos += width
} else if searchPos + 1 > a[1] { } else if searchPos+1 > a[1] {
// This clause is only needed at the end of the input // This clause is only needed at the end of the input
// string. In that case, DecodeRuneInString returns width=0. // string. In that case, DecodeRuneInString returns width=0.
searchPos++ searchPos++
@ -940,7 +940,7 @@ func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
} }
// Copy the unmatched characters after the last match. // Copy the unmatched characters after the last match.
buf.Write(src[lastMatchEnd : len(src)]); buf.Write(src[lastMatchEnd:len(src)]);
return buf.Bytes(); return buf.Bytes();
} }
@ -996,7 +996,7 @@ func (re *Regexp) allMatches(s string, b []byte, n int, deliver func(int, int))
if width > 0 { if width > 0 {
pos += width pos += width
} else { } else {
pos = end+1 pos = end + 1
} }
} else { } else {
pos = matches[1] pos = matches[1]
@ -1017,7 +1017,7 @@ func (re *Regexp) allMatches(s string, b []byte, n int, deliver func(int, int))
// containing the matching substrings. // containing the matching substrings.
func (re *Regexp) AllMatches(b []byte, n int) [][]byte { func (re *Regexp) AllMatches(b []byte, n int) [][]byte {
if n <= 0 { if n <= 0 {
n = len(b)+1 n = len(b) + 1
} }
result := make([][]byte, n); result := make([][]byte, n);
i := 0; i := 0;
@ -1035,7 +1035,7 @@ func (re *Regexp) AllMatches(b []byte, n int) [][]byte {
// containing the matching substrings. // containing the matching substrings.
func (re *Regexp) AllMatchesString(s string, n int) []string { func (re *Regexp) AllMatchesString(s string, n int) []string {
if n <= 0 { if n <= 0 {
n = len(s)+1 n = len(s) + 1
} }
result := make([]string, n); result := make([]string, n);
i := 0; i := 0;
@ -1053,7 +1053,7 @@ func (re *Regexp) AllMatchesString(s string, n int) []string {
// channel that iterates over the matching substrings. // channel that iterates over the matching substrings.
func (re *Regexp) AllMatchesIter(b []byte, n int) <-chan []byte { func (re *Regexp) AllMatchesIter(b []byte, n int) <-chan []byte {
if n <= 0 { if n <= 0 {
n = len(b)+1 n = len(b) + 1
} }
c := make(chan []byte, 10); c := make(chan []byte, 10);
go func() { go func() {
@ -1070,7 +1070,7 @@ func (re *Regexp) AllMatchesIter(b []byte, n int) <-chan []byte {
// channel that iterates over the matching substrings. // channel that iterates over the matching substrings.
func (re *Regexp) AllMatchesStringIter(s string, n int) <-chan string { func (re *Regexp) AllMatchesStringIter(s string, n int) <-chan string {
if n <= 0 { if n <= 0 {
n = len(s)+1 n = len(s) + 1
} }
c := make(chan string, 10); c := make(chan string, 10);
go func() { go func() {

View file

@ -117,7 +117,7 @@ func DialHTTP(network, address string) (*Client, os.Error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
io.WriteString(conn, "CONNECT " + rpcPath + " HTTP/1.0\n\n"); io.WriteString(conn, "CONNECT "+rpcPath+" HTTP/1.0\n\n");
// Require successful HTTP response // Require successful HTTP response
// before switching to RPC protocol. // before switching to RPC protocol.
@ -129,7 +129,7 @@ func DialHTTP(network, address string) (*Client, os.Error) {
err = os.ErrorString("unexpected HTTP response: " + resp.Status) err = os.ErrorString("unexpected HTTP response: " + resp.Status)
} }
conn.Close(); conn.Close();
return nil, &net.OpError{"dial-http", network+" "+address, nil, err}; return nil, &net.OpError{"dial-http", network + " " + address, nil, err};
} }
// Dial connects to an RPC server at the specified network address. // Dial connects to an RPC server at the specified network address.

View file

@ -391,7 +391,7 @@ func serveHTTP(c *http.Conn, req *http.Request) {
if req.Method != "CONNECT" { if req.Method != "CONNECT" {
c.SetHeader("Content-Type", "text/plain; charset=utf-8"); c.SetHeader("Content-Type", "text/plain; charset=utf-8");
c.WriteHeader(http.StatusMethodNotAllowed); c.WriteHeader(http.StatusMethodNotAllowed);
io.WriteString(c, "405 must CONNECT to " + rpcPath + "\n"); io.WriteString(c, "405 must CONNECT to "+rpcPath+"\n");
return; return;
} }
conn, _, err := c.Hijack(); conn, _, err := c.Hijack();
@ -399,7 +399,7 @@ func serveHTTP(c *http.Conn, req *http.Request) {
log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String()); log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String());
return; return;
} }
io.WriteString(conn, "HTTP/1.0 " + connected + "\n\n"); io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n");
server.input(conn); server.input(conn);
} }

View file

@ -86,15 +86,15 @@ func TestRPC(t *testing.T) {
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 {
t.Errorf("Mul: expected %d got %d", reply.C, args.A * args.B) t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B)
} }
// Out of order. // Out of order.
@ -105,13 +105,13 @@ func TestRPC(t *testing.T) {
addCall := client.Go("Arith.Add", args, addReply, nil); addCall := client.Go("Arith.Add", args, addReply, nil);
<-addCall.Done; <-addCall.Done;
if addReply.C != args.A + args.B { if addReply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", addReply.C, args.A + args.B) t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B)
} }
<-mulCall.Done; <-mulCall.Done;
if mulReply.C != args.A * args.B { if mulReply.C != args.A*args.B {
t.Errorf("Mul: expected %d got %d", mulReply.C, args.A * args.B) t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B)
} }
// Error test // Error test
@ -138,8 +138,8 @@ func TestHTTPRPC(t *testing.T) {
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)
} }
} }

View file

@ -127,9 +127,9 @@ type SliceType struct {
type ChanDir int type ChanDir int
const ( const (
RecvDir ChanDir = 1<<iota; // <-chan RecvDir ChanDir = 1 << iota; // <-chan
SendDir; // chan<- SendDir; // chan<-
BothDir = RecvDir|SendDir; // chan BothDir = RecvDir | SendDir; // chan
) )
// ChanType represents a channel type. // ChanType represents a channel type.

View file

@ -28,7 +28,7 @@ func min(a, b int) int {
// Insertion sort // Insertion sort
func insertionSort(data Interface, a, b int) { func insertionSort(data Interface, a, b int) {
for i := a+1; i < b; i++ { for i := a + 1; i < b; i++ {
for j := i; j > a && data.Less(j, j-1); j-- { for j := i; j > a && data.Less(j, j-1); j-- {
data.Swap(j, j-1) data.Swap(j, j-1)
} }
@ -63,13 +63,13 @@ func swapRange(data Interface, a, b, n int) {
} }
func doPivot(data Interface, lo, hi int) (midlo, midhi int) { func doPivot(data Interface, 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,7 +118,7 @@ func doPivot(data Interface, lo, hi int) (midlo, midhi int) {
n = min(hi-d, d-c); n = min(hi-d, d-c);
swapRange(data, c, hi-n, n); swapRange(data, c, hi-n, n);
return lo+b-a, hi-(d-c); return lo + b - a, hi - (d - c);
} }
func quickSort(data Interface, a, b int) { func quickSort(data Interface, a, b int) {
@ -136,7 +136,7 @@ func Sort(data Interface) { quickSort(data, 0, data.Len()) }
func IsSorted(data Interface) bool { func IsSorted(data Interface) 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
} }

View file

@ -147,11 +147,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,17 +178,17 @@ 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]
} }
case _ReverseSecondHalf: case _ReverseSecondHalf:
for i := 0; i < n/2; i++ { for i := 0; i < n/2; i++ {
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++ {
@ -204,7 +204,7 @@ func TestBentleyMcIlroy(t *testing.T) {
} }
desc := fmt.Sprintf("n=%d m=%d dist=%s mode=%s", n, m, dists[dist], modes[mode]); desc := fmt.Sprintf("n=%d m=%d dist=%s mode=%s", n, m, dists[dist], modes[mode]);
d := &testingData{desc, t, mdata[0:n], n*lg(n)*12/10, 0}; d := &testingData{desc, t, mdata[0:n], n * lg(n) * 12 / 10, 0};
Sort(d); Sort(d);
// If we were testing C qsort, we'd have to make a copy // If we were testing C qsort, we'd have to make a copy

View file

@ -94,7 +94,7 @@ func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) {
e = e*10 + int(s[i]) - '0' e = e*10 + int(s[i]) - '0'
} }
} }
b.dp += e*esign; b.dp += e * esign;
} }
if i != len(s) { if i != len(s) {
@ -162,13 +162,13 @@ 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
} }
@ -176,16 +176,16 @@ func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uin
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;
@ -193,13 +193,13 @@ 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
} }
@ -211,7 +211,7 @@ out:
func decimalAtof64Int(neg bool, d *decimal) float64 { func decimalAtof64Int(neg bool, d *decimal) float64 {
f := float64(0); f := float64(0);
for i := 0; i < d.nd; i++ { for i := 0; i < d.nd; i++ {
f = f*10 + float64(d.d[i] - '0') f = f*10 + float64(d.d[i]-'0')
} }
if neg { if neg {
f *= -1 // BUG work around 6g f = -f. f *= -1 // BUG work around 6g f = -f.
@ -222,7 +222,7 @@ func decimalAtof64Int(neg bool, d *decimal) float64 {
func decimalAtof32Int(neg bool, d *decimal) float32 { func decimalAtof32Int(neg bool, d *decimal) float32 {
f := float32(0); f := float32(0);
for i := 0; i < d.nd; i++ { for i := 0; i < d.nd; i++ {
f = f*10 + float32(d.d[i] - '0') f = f*10 + float32(d.d[i]-'0')
} }
if neg { if neg {
f *= -1 // BUG work around 6g f = -f. f *= -1 // BUG work around 6g f = -f.
@ -267,9 +267,9 @@ func decimalAtof64(neg bool, d *decimal, trunc bool) (f float64, ok bool) {
} }
return f * float64pow10[k], true; return f * float64pow10[k], true;
case d.dp < d.nd && d.nd - d.dp <= 22: // int / 10^k case d.dp < d.nd && d.nd-d.dp <= 22: // int / 10^k
f := decimalAtof64Int(neg, d); f := decimalAtof64Int(neg, d);
return f / float64pow10[d.nd - d.dp], true; return f / float64pow10[d.nd-d.dp], true;
} }
return; return;
} }
@ -298,9 +298,9 @@ func decimalAtof32(neg bool, d *decimal, trunc bool) (f float32, ok bool) {
} }
return f * float32pow10[k], true; return f * float32pow10[k], true;
case d.dp < d.nd && d.nd - d.dp <= 10: // int / 10^k case d.dp < d.nd && d.nd-d.dp <= 10: // int / 10^k
f := decimalAtof32Int(neg, d); f := decimalAtof32Int(neg, d);
return f / float32pow10[d.nd - d.dp], true; return f / float32pow10[d.nd-d.dp], true;
} }
return; return;
} }

View file

@ -29,7 +29,7 @@ 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)
@ -79,11 +79,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;
@ -103,7 +103,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) {
} }
n *= uint64(b); n *= uint64(b);
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;
@ -193,7 +193,7 @@ func Atoi(s string) (i int, err os.Error) {
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};
} }

View file

@ -48,7 +48,7 @@ var btoui64tests = []atoui64Test{
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 {
@ -70,7 +70,7 @@ var atoi64tests = []atoi64Test{
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},
@ -94,7 +94,7 @@ var btoi64tests = []atoi64Test{
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},
@ -140,7 +140,7 @@ var atoi32tests = []atoi32Test{
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},

View file

@ -42,20 +42,20 @@ func (a *decimal) String() string {
w++; w++;
buf[w] = '.'; buf[w] = '.';
w++; w++;
w += digitZero(buf[w : w + -a.dp]); w += digitZero(buf[w : w+-a.dp]);
w += bytes.Copy(buf[w : w + a.nd], a.d[0 : a.nd]); w += bytes.Copy(buf[w:w+a.nd], a.d[0:a.nd]);
case a.dp < a.nd: case a.dp < a.nd:
// decimal point in middle of digits // decimal point in middle of digits
w += bytes.Copy(buf[w : w + a.dp], a.d[0 : a.dp]); w += bytes.Copy(buf[w:w+a.dp], a.d[0:a.dp]);
buf[w] = '.'; buf[w] = '.';
w++; w++;
w += bytes.Copy(buf[w : w + a.nd - a.dp], a.d[a.dp : a.nd]); w += bytes.Copy(buf[w:w+a.nd-a.dp], a.d[a.dp:a.nd]);
default: default:
// zeros fill space between digits and decimal point // zeros fill space between digits and decimal point
w += bytes.Copy(buf[w : w + a.nd], a.d[0 : a.nd]); w += bytes.Copy(buf[w:w+a.nd], a.d[0:a.nd]);
w += digitZero(buf[w : w + a.dp - a.nd]); w += digitZero(buf[w : w+a.dp-a.nd]);
} }
return string(buf[0:w]); return string(buf[0:w]);
} }
@ -78,7 +78,7 @@ func digitZero(dst []byte) int {
// (They are meaningless; the decimal point is tracked // (They are meaningless; the decimal point is tracked
// independent of the number of digits.) // independent of the number of digits.)
func trim(a *decimal) { func trim(a *decimal) {
for a.nd > 0 && a.d[a.nd - 1] == '0' { for a.nd > 0 && a.d[a.nd-1] == '0' {
a.nd-- a.nd--
} }
if a.nd == 0 { if a.nd == 0 {
@ -93,9 +93,9 @@ func (a *decimal) Assign(v uint64) {
// Write reversed decimal in buf. // Write reversed decimal in buf.
n := 0; n := 0;
for v > 0 { for v > 0 {
v1 := v/10; v1 := v / 10;
v -= 10*v1; v -= 10 * v1;
buf[n] = byte(v+'0'); buf[n] = byte(v + '0');
n++; n++;
v = v1; v = v1;
} }
@ -135,7 +135,7 @@ func rightShift(a *decimal, k uint) {
return; return;
} }
for n>>k == 0 { for n>>k == 0 {
n = n*10; n = n * 10;
r++; r++;
} }
break; break;
@ -143,25 +143,25 @@ func rightShift(a *decimal, k uint) {
c := int(a.d[r]); c := int(a.d[r]);
n = n*10 + c - '0'; n = n*10 + c - '0';
} }
a.dp -= r-1; a.dp -= r - 1;
// Pick up a digit, put down a digit. // Pick up a digit, put down a digit.
for ; r < a.nd; r++ { for ; r < a.nd; r++ {
c := int(a.d[r]); c := int(a.d[r]);
dig := n>>k; dig := n >> k;
n -= dig<<k; n -= dig << k;
a.d[w] = byte(dig+'0'); a.d[w] = byte(dig + '0');
w++; w++;
n = n*10 + c - '0'; n = n*10 + c - '0';
} }
// Put down extra digits. // Put down extra digits.
for n > 0 { for n > 0 {
dig := n>>k; dig := n >> k;
n -= dig<<k; n -= dig << k;
a.d[w] = byte(dig+'0'); a.d[w] = byte(dig + '0');
w++; w++;
n = n*10; n = n * 10;
} }
a.nd = w; a.nd = w;
@ -242,7 +242,7 @@ func prefixIsLessThan(b []byte, s string) bool {
// Binary shift left (/ 2) by k bits. k <= maxShift to avoid overflow. // Binary shift left (/ 2) by k bits. k <= maxShift to avoid overflow.
func leftShift(a *decimal, k uint) { func leftShift(a *decimal, k uint) {
delta := leftcheats[k].delta; delta := leftcheats[k].delta;
if prefixIsLessThan(a.d[0 : a.nd], leftcheats[k].cutoff) { if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
delta-- delta--
} }
@ -252,20 +252,20 @@ func leftShift(a *decimal, k uint) {
// Pick up a digit, put down a digit. // Pick up a digit, put down a digit.
for r--; r >= 0; r-- { for r--; r >= 0; r-- {
n += (int(a.d[r])-'0')<<k; n += (int(a.d[r]) - '0') << k;
quo := n/10; quo := n / 10;
rem := n - 10*quo; rem := n - 10*quo;
w--; w--;
a.d[w] = byte(rem+'0'); a.d[w] = byte(rem + '0');
n = quo; n = quo;
} }
// Put down extra digits. // Put down extra digits.
for n > 0 { for n > 0 {
quo := n/10; quo := n / 10;
rem := n - 10*quo; rem := n - 10*quo;
w--; w--;
a.d[w] = byte(rem+'0'); a.d[w] = byte(rem + '0');
n = quo; n = quo;
} }
@ -302,7 +302,7 @@ func shouldRoundUp(a *decimal, nd int) bool {
return false return false
} }
if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
return (a.d[nd-1] - '0')%2 != 0 return (a.d[nd-1]-'0')%2 != 0
} }
// not halfway - digit tells all // not halfway - digit tells all
return a.d[nd] >= '5'; return a.d[nd] >= '5';
@ -339,11 +339,11 @@ func (a *decimal) RoundUp(nd int) *decimal {
} }
// round up // round up
for i := nd-1; i >= 0; i-- { for i := nd - 1; i >= 0; i-- {
c := a.d[i]; c := a.d[i];
if c < '9' { // can stop after this digit if c < '9' { // can stop after this digit
a.d[i]++; a.d[i]++;
a.nd = i+1; a.nd = i + 1;
return a; return a;
} }
} }
@ -365,7 +365,7 @@ func (a *decimal) RoundedInteger() uint64 {
var i int; var i int;
n := uint64(0); n := uint64(0);
for i = 0; i < a.dp && i < a.nd; i++ { for i = 0; i < a.dp && i < a.nd; i++ {
n = n*10 + uint64(a.d[i] - '0') n = n*10 + uint64(a.d[i]-'0')
} }
for ; i < a.dp; i++ { for ; i < a.dp; i++ {
n *= 10 n *= 10

View file

@ -16,13 +16,13 @@ import (
func pow2(i int) float64 { func pow2(i int) float64 {
switch { switch {
case i < 0: case i < 0:
return 1/pow2(-i) return 1 / pow2(-i)
case i == 0: case i == 0:
return 1 return 1
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)
@ -60,7 +60,7 @@ func myatof64(s string) (f float64, ok bool) {
} }
return v, true; return v, true;
} }
return v*pow2(e), true; return v * pow2(e), true;
} }
f1, err := strconv.Atof64(s); f1, err := strconv.Atof64(s);
if err != nil { if err != nil {
@ -84,7 +84,7 @@ func myatof32(s string) (f float32, ok bool) {
println("bad p", a[1]); println("bad p", a[1]);
return 0, false; return 0, false;
} }
return float32(float64(n)*pow2(e)), true; return float32(float64(n) * pow2(e)), true;
} }
f1, err1 := strconv.Atof32(s); f1, err1 := strconv.Atof32(s);
if err1 != nil { if err1 != nil {

View file

@ -73,12 +73,12 @@ func Ftoa(f float, fmt byte, prec int) string {
} }
func genericFtoa(bits uint64, fmt byte, prec int, flt *floatInfo) string { func genericFtoa(bits uint64, fmt byte, prec int, flt *floatInfo) string {
neg := bits >> flt.expbits >> flt.mantbits != 0; neg := bits>>flt.expbits>>flt.mantbits != 0;
exp := int(bits >> flt.mantbits)&(1 << flt.expbits - 1); exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1);
mant := bits&(uint64(1) << flt.mantbits - 1); mant := bits & (uint64(1)<<flt.mantbits - 1);
switch exp { switch exp {
case 1 << flt.expbits - 1: case 1<<flt.expbits - 1:
// Inf, NaN // Inf, NaN
if mant != 0 { if mant != 0 {
return "NaN" return "NaN"
@ -107,7 +107,7 @@ func genericFtoa(bits uint64, fmt byte, prec int, flt *floatInfo) string {
// The shift is exp - flt.mantbits because mant is a 1-bit integer // The shift is exp - flt.mantbits because mant is a 1-bit integer
// followed by a flt.mantbits fraction, and we are treating it as // followed by a flt.mantbits fraction, and we are treating it as
// a 1+flt.mantbits-bit integer. // a 1+flt.mantbits-bit integer.
d := newDecimal(mant).Shift(exp-int(flt.mantbits)); d := newDecimal(mant).Shift(exp - int(flt.mantbits));
// Round appropriately. // Round appropriately.
// Negative precision means "only as much as needed to be exact." // Negative precision means "only as much as needed to be exact."
@ -119,14 +119,14 @@ func genericFtoa(bits uint64, fmt byte, prec int, flt *floatInfo) string {
case 'e', 'E': case 'e', 'E':
prec = d.nd - 1 prec = d.nd - 1
case 'f': case 'f':
prec = max(d.nd - d.dp, 0) prec = max(d.nd-d.dp, 0)
case 'g', 'G': case 'g', 'G':
prec = d.nd prec = d.nd
} }
} else { } else {
switch fmt { switch fmt {
case 'e', 'E': case 'e', 'E':
d.Round(prec+1) d.Round(prec + 1)
case 'f': case 'f':
d.Round(d.dp + prec) d.Round(d.dp + prec)
case 'g', 'G': case 'g', 'G':
@ -158,10 +158,10 @@ func genericFtoa(bits uint64, fmt byte, prec int, flt *floatInfo) string {
if exp < -4 || exp >= eprec { if exp < -4 || exp >= eprec {
return fmtE(neg, d, prec-1, fmt+'e'-'g') return fmtE(neg, d, prec-1, fmt+'e'-'g')
} }
return fmtF(neg, d, max(prec - d.dp, 0)); return fmtF(neg, d, max(prec-d.dp, 0));
} }
return "%"+string(fmt); return "%" + string(fmt);
} }
// Round d (= mant * 2^exp) to the shortest number of digits // Round d (= mant * 2^exp) to the shortest number of digits
@ -186,7 +186,7 @@ func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) {
// d = mant << (exp - mantbits) // d = mant << (exp - mantbits)
// Next highest floating point number is mant+1 << exp-mantbits. // Next highest floating point number is mant+1 << exp-mantbits.
// Our upper bound is halfway inbetween, mant*2+1 << exp-mantbits-1. // Our upper bound is halfway inbetween, mant*2+1 << exp-mantbits-1.
upper := newDecimal(mant*2 + 1).Shift(exp-int(flt.mantbits)-1); upper := newDecimal(mant*2 + 1).Shift(exp - int(flt.mantbits) - 1);
// d = mant << (exp - mantbits) // d = mant << (exp - mantbits)
// Next lowest floating point number is mant-1 << exp-mantbits, // Next lowest floating point number is mant-1 << exp-mantbits,
@ -197,14 +197,14 @@ func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) {
minexp := flt.bias + 1; // minimum possible exponent minexp := flt.bias + 1; // minimum possible exponent
var mantlo uint64; var mantlo uint64;
var explo int; var explo int;
if mant > 1 << flt.mantbits || exp == minexp { if mant > 1<<flt.mantbits || exp == minexp {
mantlo = mant-1; mantlo = mant - 1;
explo = exp; explo = exp;
} else { } else {
mantlo = mant*2 - 1; mantlo = mant*2 - 1;
explo = exp-1; explo = exp - 1;
} }
lower := newDecimal(mantlo*2 + 1).Shift(explo-int(flt.mantbits)-1); lower := newDecimal(mantlo*2 + 1).Shift(explo - int(flt.mantbits) - 1);
// The upper and lower bounds are possible outputs only if // The upper and lower bounds are possible outputs only if
// the original mantissa is even, so that IEEE round-to-even // the original mantissa is even, so that IEEE round-to-even
@ -239,13 +239,13 @@ func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) {
// If it's okay to do only one, do it. // If it's okay to do only one, do it.
switch { switch {
case okdown && okup: case okdown && okup:
d.Round(i+1); d.Round(i + 1);
return; return;
case okdown: case okdown:
d.RoundDown(i+1); d.RoundDown(i + 1);
return; return;
case okup: case okup:
d.RoundUp(i+1); d.RoundUp(i + 1);
return; return;
} }
} }
@ -253,8 +253,8 @@ func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) {
// %e: -d.ddddde±dd // %e: -d.ddddde±dd
func fmtE(neg bool, d *decimal, prec int, fmt byte) string { func fmtE(neg bool, d *decimal, prec int, fmt byte) string {
buf := make([]byte, 3 + max(prec, 0) + 30); // "-0." + prec digits + exp buf := make([]byte, 3+max(prec, 0)+30); // "-0." + prec digits + exp
w := 0; // write index w := 0; // write index
// sign // sign
if neg { if neg {
@ -323,7 +323,7 @@ func fmtE(neg bool, d *decimal, prec int, fmt byte) string {
// %f: -ddddddd.ddddd // %f: -ddddddd.ddddd
func fmtF(neg bool, d *decimal, prec int) string { func fmtF(neg bool, d *decimal, prec int) string {
buf := make([]byte, 1 + max(d.dp, 1) + 1 + max(prec, 0)); buf := make([]byte, 1+max(d.dp, 1)+1+max(prec, 0));
w := 0; w := 0;
// sign // sign
@ -353,10 +353,10 @@ func fmtF(neg bool, d *decimal, prec int) string {
buf[w] = '.'; buf[w] = '.';
w++; w++;
for i := 0; i < prec; i++ { for i := 0; i < prec; i++ {
if d.dp + i < 0 || d.dp + i >= d.nd { if d.dp+i < 0 || d.dp+i >= d.nd {
buf[w] = '0' buf[w] = '0'
} else { } else {
buf[w] = d.d[d.dp + i] buf[w] = d.d[d.dp+i]
} }
w++; w++;
} }

View file

@ -17,7 +17,7 @@ type ftoaTest struct {
s string; s string;
} }
func fdiv(a, b float64) float64 { return a/b } // keep compiler in the dark func fdiv(a, b float64) float64 { return a / b } // keep compiler in the dark
const ( const (
below1e23 = 99999999999999974834176; below1e23 = 99999999999999974834176;

View file

@ -22,30 +22,30 @@ var itob64tests = []itob64Test{
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"},
@ -53,8 +53,8 @@ var itob64tests = []itob64Test{
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) {
@ -131,7 +131,7 @@ type uitob64Test struct {
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"},

View file

@ -53,12 +53,12 @@ func Quote(s string) string {
if r < 0x10000 { if r < 0x10000 {
buf.WriteString(`\u`); buf.WriteString(`\u`);
for j := uint(0); j < 4; j++ { for j := uint(0); j < 4; j++ {
buf.WriteByte(lowerhex[(r>>(12 - 4*j))&0xF]) buf.WriteByte(lowerhex[(r>>(12-4*j))&0xF])
} }
} else { } else {
buf.WriteString(`\U`); buf.WriteString(`\U`);
for j := uint(0); j < 8; j++ { for j := uint(0); j < 8; j++ {
buf.WriteByte(lowerhex[(r>>(28 - 4*j))&0xF]) buf.WriteByte(lowerhex[(r>>(28-4*j))&0xF])
} }
} }
@ -88,11 +88,11 @@ func unhex(b byte) (v int, ok bool) {
c := int(b); c := int(b);
switch { switch {
case '0' <= c && c <= '9': case '0' <= c && c <= '9':
return c-'0', true return c - '0', true
case 'a' <= c && c <= 'f': case 'a' <= c && c <= 'f':
return c-'a'+10, true return c - 'a' + 10, true
case 'A' <= c && c <= 'F': case 'A' <= c && c <= 'F':
return c-'A'+10, true return c - 'A' + 10, true
} }
return; return;
} }
@ -182,17 +182,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 {

View file

@ -41,9 +41,9 @@ func Count(s, sep string) int {
c := sep[0]; c := sep[0];
n := 0; n := 0;
for i := 0; i+len(sep) <= len(s); i++ { for i := 0; i+len(sep) <= len(s); i++ {
if s[i] == c && (len(sep) == 1 || s[i : i+len(sep)] == sep) { if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {
n++; n++;
i += len(sep)-1; i += len(sep) - 1;
} }
} }
return n; return n;
@ -57,7 +57,7 @@ func Index(s, sep string) int {
} }
c := sep[0]; c := sep[0];
for i := 0; i+n <= len(s); i++ { for i := 0; i+n <= len(s); i++ {
if s[i] == c && (n == 1 || s[i : i+n] == sep) { if s[i] == c && (n == 1 || s[i:i+n] == sep) {
return i return i
} }
} }
@ -71,8 +71,8 @@ func LastIndex(s, sep string) int {
return len(s) return len(s)
} }
c := sep[0]; c := sep[0];
for i := len(s)-n; i >= 0; i-- { for i := len(s) - n; i >= 0; i-- {
if s[i] == c && (n == 1 || s[i : i+n] == sep) { if s[i] == c && (n == 1 || s[i:i+n] == sep) {
return i return i
} }
} }
@ -93,11 +93,11 @@ func genSplit(s, sep string, sepSave, n int) []string {
a := make([]string, n); a := make([]string, n);
na := 0; na := 0;
for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
if s[i] == c && (len(sep) == 1 || s[i : i+len(sep)] == sep) { if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {
a[na] = s[start : i+sepSave]; a[na] = s[start : i+sepSave];
na++; na++;
start = i+len(sep); start = i + len(sep);
i += len(sep)-1; i += len(sep) - 1;
} }
} }
a[na] = s[start:len(s)]; a[na] = s[start:len(s)];
@ -125,7 +125,7 @@ func Join(a []string, sep string) string {
if len(a) == 1 { if len(a) == 1 {
return a[0] return a[0]
} }
n := len(sep)*(len(a)-1); n := len(sep) * (len(a) - 1);
for i := 0; i < len(a); i++ { for i := 0; i < len(a); i++ {
n += len(a[i]) n += len(a[i])
} }
@ -156,7 +156,7 @@ func HasPrefix(s, prefix string) bool {
// HasSuffix tests whether the string s ends with suffix. // HasSuffix tests whether the string s ends with suffix.
func HasSuffix(s, suffix string) bool { func HasSuffix(s, suffix string) bool {
return len(s) >= len(suffix) && s[len(s)-len(suffix) : len(s)] == suffix return len(s) >= len(suffix) && s[len(s)-len(suffix):len(s)] == suffix
} }
// Map returns a copy of the string s with all its characters modified // Map returns a copy of the string s with all its characters modified

View file

@ -208,7 +208,7 @@ 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"},
@ -272,7 +272,7 @@ 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
} }
@ -282,10 +282,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) {

View file

@ -23,7 +23,7 @@ type Mutex struct {
func xadd(val *uint32, delta int32) (new uint32) { func xadd(val *uint32, delta int32) (new uint32) {
for { for {
v := *val; v := *val;
nv := v+uint32(delta); nv := v + uint32(delta);
if cas(val, v, nv) { if cas(val, v, nv) {
return nv return nv
} }

View file

@ -7,22 +7,22 @@ package syscall
func str(val int) string { // do it here rather than with fmt to avoid dependency func str(val int) string { // do it here rather than with fmt to avoid dependency
if val < 0 { if val < 0 {
return "-"+str(-val) return "-" + str(-val)
} }
var buf [32]byte; // big enough for int64 var buf [32]byte; // big enough for int64
i := len(buf)-1; i := len(buf) - 1;
for val >= 10 { for val >= 10 {
buf[i] = byte(val%10 + '0'); buf[i] = byte(val%10 + '0');
i--; i--;
val /= 10; val /= 10;
} }
buf[i] = byte(val+'0'); buf[i] = byte(val + '0');
return string(buf[i:len(buf)]); return string(buf[i:len(buf)]);
} }
func Errstr(errno int) string { func Errstr(errno int) string {
if errno < 0 || errno >= int(len(errors)) { if errno < 0 || errno >= int(len(errors)) {
return "error "+str(errno) return "error " + str(errno)
} }
return errors[errno]; return errors[errno];
} }

View file

@ -94,13 +94,13 @@ func (w WaitStatus) ExitStatus() int {
if w&mask != exited { if w&mask != exited {
return -1 return -1
} }
return int(w>>shift); return int(w >> shift);
} }
func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
func (w WaitStatus) Signal() int { func (w WaitStatus) Signal() int {
sig := int(w&mask); sig := int(w & mask);
if sig == stopped || sig == 0 { if sig == stopped || sig == 0 {
return -1 return -1
} }
@ -117,7 +117,7 @@ func (w WaitStatus) StopSignal() int {
if !w.Stopped() { if !w.Stopped() {
return -1 return -1
} }
return int(w>>shift)&0xFF; return int(w>>shift) & 0xFF;
} }
func (w WaitStatus) TrapCause() int { func (w WaitStatus) TrapCause() int {
@ -220,7 +220,7 @@ func (sa *SockaddrUnix) sockaddr() (uintptr, _Socklen, int) {
if n >= len(sa.raw.Path) || n == 0 { if n >= len(sa.raw.Path) || n == 0 {
return 0, 0, EINVAL return 0, 0, EINVAL
} }
sa.raw.Len = byte(3+n); // 2 for Family, Len; 1 for NUL sa.raw.Len = byte(3 + n); // 2 for Family, Len; 1 for NUL
sa.raw.Family = AF_UNIX; sa.raw.Family = AF_UNIX;
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
sa.raw.Path[i] = int8(name[i]) sa.raw.Path[i] = int8(name[i])
@ -236,7 +236,7 @@ func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, int) {
return nil, EINVAL return nil, EINVAL
} }
sa := new(SockaddrUnix); sa := new(SockaddrUnix);
n := int(pp.Len)-3; // subtract leading Family, Len, terminating NUL n := int(pp.Len) - 3; // subtract leading Family, Len, terminating NUL
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
if pp.Path[i] == 0 { if pp.Path[i] == 0 {
// found early NUL; assume Len is overestimating // found early NUL; assume Len is overestimating
@ -392,7 +392,7 @@ func nametomib(name string) (mib []_C_int, errno int) {
// will silently write 2 words farther than we specify // will silently write 2 words farther than we specify
// and we'll get memory corruption. // and we'll get memory corruption.
var buf [CTL_MAXNAME + 2]_C_int; var buf [CTL_MAXNAME + 2]_C_int;
n := uintptr(CTL_MAXNAME)*siz; n := uintptr(CTL_MAXNAME) * siz;
p := (*byte)(unsafe.Pointer(&buf[0])); p := (*byte)(unsafe.Pointer(&buf[0]));
bytes := StringByteSlice(name); bytes := StringByteSlice(name);

View file

@ -9,8 +9,8 @@ func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) { func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = int32(nsec/1e9); ts.Sec = int32(nsec / 1e9);
ts.Nsec = int32(nsec%1e9); ts.Nsec = int32(nsec % 1e9);
return; return;
} }
@ -18,8 +18,8 @@ func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)
func NsecToTimeval(nsec int64) (tv Timeval) { func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999; // round up to microsecond nsec += 999; // round up to microsecond
tv.Usec = int32(nsec%1e9/1e3); tv.Usec = int32(nsec % 1e9 / 1e3);
tv.Sec = int32(nsec/1e9); tv.Sec = int32(nsec / 1e9);
return; return;
} }

View file

@ -9,8 +9,8 @@ func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) { func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = nsec/1e9; ts.Sec = nsec / 1e9;
ts.Nsec = nsec%1e9; ts.Nsec = nsec % 1e9;
return; return;
} }
@ -18,8 +18,8 @@ func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)
func NsecToTimeval(nsec int64) (tv Timeval) { func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999; // round up to microsecond nsec += 999; // round up to microsecond
tv.Usec = int32(nsec%1e9/1e3); tv.Usec = int32(nsec % 1e9 / 1e3);
tv.Sec = int64(nsec/1e9); tv.Sec = int64(nsec / 1e9);
return; return;
} }

View file

@ -134,28 +134,28 @@ func (w WaitStatus) ExitStatus() int {
if !w.Exited() { if !w.Exited() {
return -1 return -1
} }
return int(w>>shift)&0xFF; return int(w>>shift) & 0xFF;
} }
func (w WaitStatus) Signal() int { func (w WaitStatus) Signal() int {
if !w.Signaled() { if !w.Signaled() {
return -1 return -1
} }
return int(w&mask); return int(w & mask);
} }
func (w WaitStatus) StopSignal() int { func (w WaitStatus) StopSignal() int {
if !w.Stopped() { if !w.Stopped() {
return -1 return -1
} }
return int(w>>shift)&0xFF; return int(w>>shift) & 0xFF;
} }
func (w WaitStatus) TrapCause() int { func (w WaitStatus) TrapCause() int {
if w.StopSignal() != SIGTRAP { if w.StopSignal() != SIGTRAP {
return -1 return -1
} }
return int(w>>shift)>>8; return int(w>>shift) >> 8;
} }
//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, errno int) //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, errno int)
@ -242,7 +242,7 @@ func (sa *SockaddrUnix) sockaddr() (uintptr, _Socklen, int) {
} }
// length is family, name, NUL. // length is family, name, NUL.
return uintptr(unsafe.Pointer(&sa.raw)), 1+_Socklen(n)+1, 0; return uintptr(unsafe.Pointer(&sa.raw)), 1 + _Socklen(n) + 1, 0;
} }
func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, int) { func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, int) {
@ -411,12 +411,12 @@ func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, errno in
// boundary and not get the bytes leading up to the page // boundary and not get the bytes leading up to the page
// boundary. // boundary.
n := 0; n := 0;
if addr % sizeofPtr != 0 { if addr%sizeofPtr != 0 {
errno = ptrace(req, pid, addr - addr % sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))); errno = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])));
if errno != 0 { if errno != 0 {
return 0, errno return 0, errno
} }
n += bytesCopy(out, buf[addr % sizeofPtr : len(buf)]); n += bytesCopy(out, buf[addr%sizeofPtr:len(buf)]);
out = out[n:len(out)]; out = out[n:len(out)];
} }
@ -450,15 +450,15 @@ func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (c
// Leading edge. // Leading edge.
n := 0; n := 0;
if addr % sizeofPtr != 0 { if addr%sizeofPtr != 0 {
var buf [sizeofPtr]byte; var buf [sizeofPtr]byte;
errno = ptrace(peekReq, pid, addr - addr % sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))); errno = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])));
if errno != 0 { if errno != 0 {
return 0, errno return 0, errno
} }
n += bytesCopy(buf[addr % sizeofPtr : len(buf)], data); n += bytesCopy(buf[addr%sizeofPtr:len(buf)], data);
word := *((*uintptr)(unsafe.Pointer(&buf[0]))); word := *((*uintptr)(unsafe.Pointer(&buf[0])));
errno = ptrace(pokeReq, pid, addr - addr % sizeofPtr, word); errno = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word);
if errno != 0 { if errno != 0 {
return 0, errno return 0, errno
} }
@ -473,7 +473,7 @@ func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (c
return n, errno return n, errno
} }
n += sizeofPtr; n += sizeofPtr;
data = data[sizeofPtr : len(data)]; data = data[sizeofPtr:len(data)];
} }
// Trailing edge. // Trailing edge.

View file

@ -11,8 +11,8 @@ func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) { func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = int32(nsec/1e9); ts.Sec = int32(nsec / 1e9);
ts.Nsec = int32(nsec%1e9); ts.Nsec = int32(nsec % 1e9);
return; return;
} }
@ -20,8 +20,8 @@ func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)
func NsecToTimeval(nsec int64) (tv Timeval) { func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999; // round up to microsecond nsec += 999; // round up to microsecond
tv.Sec = int32(nsec/1e9); tv.Sec = int32(nsec / 1e9);
tv.Usec = int32(nsec%1e9/1e3); tv.Usec = int32(nsec % 1e9 / 1e3);
return; return;
} }

View file

@ -47,8 +47,8 @@ func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) { func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = nsec/1e9; ts.Sec = nsec / 1e9;
ts.Nsec = nsec%1e9; ts.Nsec = nsec % 1e9;
return; return;
} }
@ -56,8 +56,8 @@ func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)
func NsecToTimeval(nsec int64) (tv Timeval) { func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999; // round up to microsecond nsec += 999; // round up to microsecond
tv.Sec = nsec/1e9; tv.Sec = nsec / 1e9;
tv.Usec = nsec%1e9/1e3; tv.Usec = nsec % 1e9 / 1e3;
return; return;
} }

View file

@ -9,15 +9,15 @@ func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) { func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = int32(nsec/1e9); ts.Sec = int32(nsec / 1e9);
ts.Nsec = int32(nsec%1e9); ts.Nsec = int32(nsec % 1e9);
return; return;
} }
func NsecToTimeval(nsec int64) (tv Timeval) { func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999; // round up to microsecond nsec += 999; // round up to microsecond
tv.Sec = int32(nsec/1e9); tv.Sec = int32(nsec / 1e9);
tv.Usec = int32(nsec%1e9/1e3); tv.Usec = int32(nsec % 1e9 / 1e3);
return; return;
} }

View file

@ -219,7 +219,7 @@ type SockaddrUnix struct {
func (*SockaddrUnix) sockaddr() {} func (*SockaddrUnix) sockaddr() {}
const ( const (
AF_INET = 1+iota; AF_INET = 1 + iota;
AF_INET6; AF_INET6;
AF_UNIX; AF_UNIX;
IPPROTO_TCP; IPPROTO_TCP;

Some files were not shown because too many files have changed in this diff Show more