Commit 90564a92 authored by Robert Griesemer's avatar Robert Griesemer

go/printer: changed max. number of newlines from 3 to 2

manual changes in src/pkg/go/printer, src/cmd/gofix/signal_test.go
(cd src/cmd/gofix/testdata; gofmt -w *.in *.out)
(cd src/pkg/go/printer; gotest -update)
gofmt -w misc src

runs all tests

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4715041
parent 58e19aa4
......@@ -211,7 +211,6 @@ func (z *Int) destroy() {
z.init = false
}
/*
* arithmetic
*/
......@@ -300,7 +299,6 @@ func (z *Int) Int64() int64 {
return int64(C.mpz_get_si(&z.i[0]))
}
// Neg sets z = -x and returns z.
func (z *Int) Neg(x *Int) *Int {
x.doinit()
......@@ -317,7 +315,6 @@ func (z *Int) Abs(x *Int) *Int {
return z
}
/*
* functions without a clear receiver
*/
......
......@@ -16,31 +16,26 @@ import (
"path/filepath"
)
var fset = token.NewFileSet()
var start = flag.String("start", "Start", "name of start production")
func usage() {
fmt.Fprintf(os.Stderr, "usage: ebnflint [flags] [filename]\n")
flag.PrintDefaults()
os.Exit(1)
}
// Markers around EBNF sections in .html files
var (
open = []byte(`<pre class="ebnf">`)
close = []byte(`</pre>`)
)
func report(err os.Error) {
scanner.PrintError(os.Stderr, err)
os.Exit(1)
}
func extractEBNF(src []byte) []byte {
var buf bytes.Buffer
......@@ -77,7 +72,6 @@ func extractEBNF(src []byte) []byte {
return buf.Bytes()
}
func main() {
flag.Parse()
......
......@@ -28,7 +28,6 @@ import (
"xml"
)
// Handler for /doc/codewalk/ and below.
func codewalk(w http.ResponseWriter, r *http.Request) {
relpath := r.URL.Path[len("/doc/codewalk/"):]
......@@ -71,7 +70,6 @@ func codewalk(w http.ResponseWriter, r *http.Request) {
servePage(w, "Codewalk: "+cw.Title, "", "", b)
}
// A Codewalk represents a single codewalk read from an XML file.
type Codewalk struct {
Title string `xml:"attr"`
......@@ -79,7 +77,6 @@ type Codewalk struct {
Step []*Codestep
}
// A Codestep is a single step in a codewalk.
type Codestep struct {
// Filled in from XML
......@@ -97,7 +94,6 @@ type Codestep struct {
Data []byte
}
// String method for printing in template.
// Formats file address nicely.
func (st *Codestep) String() string {
......@@ -111,7 +107,6 @@ func (st *Codestep) String() string {
return s
}
// loadCodewalk reads a codewalk from the named XML file.
func loadCodewalk(filename string) (*Codewalk, os.Error) {
f, err := fs.Open(filename)
......@@ -173,7 +168,6 @@ func loadCodewalk(filename string) (*Codewalk, os.Error) {
return cw, nil
}
// codewalkDir serves the codewalk directory listing.
// It scans the directory for subdirectories or files named *.xml
// and prepares a table.
......@@ -207,7 +201,6 @@ func codewalkDir(w http.ResponseWriter, r *http.Request, relpath, abspath string
servePage(w, "Codewalks", "", "", b)
}
// codewalkFileprint serves requests with ?fileprint=f&lo=lo&hi=hi.
// The filename f has already been retrieved and is passed as an argument.
// Lo and hi are the numbers of the first and last line to highlight
......@@ -256,7 +249,6 @@ func codewalkFileprint(w http.ResponseWriter, r *http.Request, f string) {
io.WriteString(w, "</pre>")
}
// addrToByte evaluates the given address starting at offset start in data.
// It returns the lo and hi byte offset of the matched region within data.
// See http://plan9.bell-labs.com/sys/doc/sam/sam.html Table II
......@@ -351,7 +343,6 @@ func addrToByteRange(addr string, start int, data []byte) (lo, hi int, err os.Er
return lo, hi, nil
}
// addrNumber applies the given dir, n, and charOffset to the address lo, hi.
// dir is '+' or '-', n is the count, and charOffset is true if the syntax
// used was #n. Applying +n (or +#n) means to advance n lines
......@@ -437,7 +428,6 @@ func addrNumber(data []byte, lo, hi int, dir byte, n int, charOffset bool) (int,
return 0, 0, os.NewError("address out of range")
}
// addrRegexp searches for pattern in the given direction starting at lo, hi.
// The direction dir is '+' (search forward from hi) or '-' (search backward from lo).
// Backward searches are unimplemented.
......@@ -465,7 +455,6 @@ func addrRegexp(data []byte, lo, hi int, dir byte, pattern string) (int, int, os
return m[0], m[1], nil
}
// lineToByte returns the byte index of the first byte of line n.
// Line numbers begin at 1.
func lineToByte(data []byte, n int) int {
......@@ -483,7 +472,6 @@ func lineToByte(data []byte, n int) int {
return len(data)
}
// byteToLine returns the number of the line containing the byte at index i.
func byteToLine(data []byte, i int) int {
l := 1
......
......@@ -17,7 +17,6 @@ import (
"unicode"
)
type Directory struct {
Depth int
Path string // includes Name
......@@ -26,7 +25,6 @@ type Directory struct {
Dirs []*Directory // subdirectories
}
func isGoFile(fi FileInfo) bool {
name := fi.Name()
return fi.IsRegular() &&
......@@ -34,20 +32,17 @@ func isGoFile(fi FileInfo) bool {
filepath.Ext(name) == ".go"
}
func isPkgFile(fi FileInfo) bool {
return isGoFile(fi) &&
!strings.HasSuffix(fi.Name(), "_test.go") // ignore test files
}
func isPkgDir(fi FileInfo) bool {
name := fi.Name()
return fi.IsDirectory() && len(name) > 0 &&
name[0] != '_' && name[0] != '.' // ignore _files and .files
}
func firstSentence(s string) string {
i := -1 // index+1 of first terminator (punctuation ending a sentence)
j := -1 // index+1 of first terminator followed by white space
......@@ -83,13 +78,11 @@ func firstSentence(s string) string {
return s[0:j]
}
type treeBuilder struct {
pathFilter func(string) bool
maxDepth int
}
func (b *treeBuilder) newDirTree(fset *token.FileSet, path, name string, depth int) *Directory {
if b.pathFilter != nil && !b.pathFilter(path) {
return nil
......@@ -185,7 +178,6 @@ func (b *treeBuilder) newDirTree(fset *token.FileSet, path, name string, depth i
return &Directory{depth, path, name, synopsis, dirs}
}
// newDirectory creates a new package directory tree with at most maxDepth
// levels, anchored at root. The result tree is pruned such that it only
// contains directories that contain package files or that contain
......@@ -218,7 +210,6 @@ func newDirectory(root string, pathFilter func(string) bool, maxDepth int) *Dire
return b.newDirTree(token.NewFileSet(), root, d.Name(), 0)
}
func (dir *Directory) writeLeafs(buf *bytes.Buffer) {
if dir != nil {
if len(dir.Dirs) == 0 {
......@@ -233,7 +224,6 @@ func (dir *Directory) writeLeafs(buf *bytes.Buffer) {
}
}
func (dir *Directory) walk(c chan<- *Directory, skipRoot bool) {
if dir != nil {
if !skipRoot {
......@@ -245,7 +235,6 @@ func (dir *Directory) walk(c chan<- *Directory, skipRoot bool) {
}
}
func (dir *Directory) iter(skipRoot bool) <-chan *Directory {
c := make(chan *Directory)
go func() {
......@@ -255,7 +244,6 @@ func (dir *Directory) iter(skipRoot bool) <-chan *Directory {
return c
}
func (dir *Directory) lookupLocal(name string) *Directory {
for _, d := range dir.Dirs {
if d.Name == name {
......@@ -265,7 +253,6 @@ func (dir *Directory) lookupLocal(name string) *Directory {
return nil
}
// lookup looks for the *Directory for a given path, relative to dir.
func (dir *Directory) lookup(path string) *Directory {
d := strings.Split(dir.Path, string(filepath.Separator))
......@@ -284,7 +271,6 @@ func (dir *Directory) lookup(path string) *Directory {
return dir
}
// DirEntry describes a directory entry. The Depth and Height values
// are useful for presenting an entry in an indented fashion.
//
......@@ -296,13 +282,11 @@ type DirEntry struct {
Synopsis string
}
type DirList struct {
MaxHeight int // directory tree height, > 0
List []DirEntry
}
// listing creates a (linear) directory listing from a directory tree.
// If skipRoot is set, the root directory itself is excluded from the list.
//
......
......@@ -15,7 +15,6 @@ import (
"os"
)
// The FileInfo interface provides access to file information.
type FileInfo interface {
Name() string
......@@ -24,7 +23,6 @@ type FileInfo interface {
IsDirectory() bool
}
// The FileSystem interface specifies the methods godoc is using
// to access the file system for which it serves documentation.
type FileSystem interface {
......@@ -35,24 +33,20 @@ type FileSystem interface {
ReadFile(path string) ([]byte, os.Error)
}
// ----------------------------------------------------------------------------
// OS-specific FileSystem implementation
var OS FileSystem = osFS{}
// osFI is the OS-specific implementation of FileInfo.
type osFI struct {
*os.FileInfo
}
func (fi osFI) Name() string {
return fi.FileInfo.Name
}
func (fi osFI) Size() int64 {
if fi.IsDirectory() {
return 0
......@@ -60,7 +54,6 @@ func (fi osFI) Size() int64 {
return fi.FileInfo.Size
}
// osFS is the OS-specific implementation of FileSystem
type osFS struct{}
......@@ -79,19 +72,16 @@ func (osFS) Open(path string) (io.ReadCloser, os.Error) {
return f, nil
}
func (osFS) Lstat(path string) (FileInfo, os.Error) {
fi, err := os.Lstat(path)
return osFI{fi}, err
}
func (osFS) Stat(path string) (FileInfo, os.Error) {
fi, err := os.Stat(path)
return osFI{fi}, err
}
func (osFS) ReadDir(path string) ([]FileInfo, os.Error) {
l0, err := ioutil.ReadDir(path) // l0 is sorted
if err != nil {
......@@ -104,7 +94,6 @@ func (osFS) ReadDir(path string) ([]FileInfo, os.Error) {
return l1, nil
}
func (osFS) ReadFile(path string) ([]byte, os.Error) {
return ioutil.ReadFile(path)
}
......@@ -20,7 +20,6 @@ import (
"template"
)
// ----------------------------------------------------------------------------
// Implementation of FormatSelections
......@@ -34,13 +33,11 @@ import (
//
type Selection func() []int
// A LinkWriter writes some start or end "tag" to w for the text offset offs.
// It is called by FormatSelections at the start or end of each link segment.
//
type LinkWriter func(w io.Writer, offs int, start bool)
// A SegmentWriter formats a text according to selections and writes it to w.
// The selections parameter is a bit set indicating which selections provided
// to FormatSelections overlap with the text segment: If the n'th bit is set
......@@ -49,7 +46,6 @@ type LinkWriter func(w io.Writer, offs int, start bool)
//
type SegmentWriter func(w io.Writer, text []byte, selections int)
// FormatSelections takes a text and writes it to w using link and segment
// writers lw and sw as follows: lw is invoked for consecutive segment starts
// and ends as specified through the links selection, and sw is invoked for
......@@ -138,7 +134,6 @@ func FormatSelections(w io.Writer, text []byte, lw LinkWriter, links Selection,
flush()
}
// A merger merges a slice of Selections and produces a sequence of
// consecutive segment change events through repeated next() calls.
//
......@@ -147,7 +142,6 @@ type merger struct {
segments [][]int // segments[i] is the next segment of selections[i]
}
const infinity int = 2e9
func newMerger(selections []Selection) *merger {
......@@ -163,7 +157,6 @@ func newMerger(selections []Selection) *merger {
return &merger{selections, segments}
}
// next returns the next segment change: index specifies the Selection
// to which the segment belongs, offs is the segment start or end offset
// as determined by the start value. If there are no more segment changes,
......@@ -208,7 +201,6 @@ func (m *merger) next() (index, offs int, start bool) {
return
}
// ----------------------------------------------------------------------------
// Implementation of FormatText
......@@ -232,7 +224,6 @@ func lineSelection(text []byte) Selection {
}
}
// commentSelection returns the sequence of consecutive comments
// in the Go src text as a Selection.
//
......@@ -257,7 +248,6 @@ func commentSelection(src []byte) Selection {
}
}
// makeSelection is a helper function to make a Selection from a slice of pairs.
func makeSelection(matches [][]int) Selection {
return func() (seg []int) {
......@@ -269,7 +259,6 @@ func makeSelection(matches [][]int) Selection {
}
}
// regexpSelection computes the Selection for the regular expression expr in text.
func regexpSelection(text []byte, expr string) Selection {
var matches [][]int
......@@ -279,7 +268,6 @@ func regexpSelection(text []byte, expr string) Selection {
return makeSelection(matches)
}
var selRx = regexp.MustCompile(`^([0-9]+):([0-9]+)`)
// rangeSelection computes the Selection for a text range described
......@@ -298,7 +286,6 @@ func rangeSelection(str string) Selection {
return nil
}
// Span tags for all the possible selection combinations that may
// be generated by FormatText. Selections are indicated by a bitset,
// and the value of the bitset specifies the tag to be used.
......@@ -320,7 +307,6 @@ var startTags = [][]byte{
var endTag = []byte(`</span>`)
func selectionTag(w io.Writer, text []byte, selections int) {
if selections < len(startTags) {
if tag := startTags[selections]; len(tag) > 0 {
......@@ -333,7 +319,6 @@ func selectionTag(w io.Writer, text []byte, selections int) {
template.HTMLEscape(w, text)
}
// FormatText HTML-escapes text and writes it to w.
// Consecutive text segments are wrapped in HTML spans (with tags as
// defined by startTags and endTag) as follows:
......
This diff is collapsed.
This diff is collapsed.
......@@ -69,14 +69,12 @@ var (
query = flag.Bool("q", false, "arguments are considered search queries")
)
func serveError(w http.ResponseWriter, r *http.Request, relpath string, err os.Error) {
contents := applyTemplate(errorHTML, "errorHTML", err) // err may contain an absolute path!
w.WriteHeader(http.StatusNotFound)
servePage(w, "File "+relpath, "", "", contents)
}
func exec(rw http.ResponseWriter, args []string) (status int) {
r, w, err := os.Pipe()
if err != nil {
......@@ -124,7 +122,6 @@ func exec(rw http.ResponseWriter, args []string) (status int) {
return
}
func dosync(w http.ResponseWriter, r *http.Request) {
args := []string{"/bin/sh", "-c", *syncCmd}
switch exec(w, args) {
......@@ -146,7 +143,6 @@ func dosync(w http.ResponseWriter, r *http.Request) {
}
}
func usage() {
fmt.Fprintf(os.Stderr,
"usage: godoc package [name ...]\n"+
......@@ -155,7 +151,6 @@ func usage() {
os.Exit(2)
}
func loggingHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("%s\t%s", req.RemoteAddr, req.URL)
......@@ -163,7 +158,6 @@ func loggingHandler(h http.Handler) http.Handler {
})
}
func remoteSearch(query string) (res *http.Response, err os.Error) {
search := "/search?f=text&q=" + http.URLEscape(query)
......@@ -195,13 +189,11 @@ func remoteSearch(query string) (res *http.Response, err os.Error) {
return
}
// Does s look like a regular expression?
func isRegexp(s string) bool {
return strings.IndexAny(s, ".(|)*+?^$[]") >= 0
}
// Make a regular expression of the form
// names[0]|names[1]|...names[len(names)-1].
// Returns nil if the regular expression is illegal.
......@@ -223,7 +215,6 @@ func makeRx(names []string) (rx *regexp.Regexp) {
return
}
func main() {
flag.Usage = usage
flag.Parse()
......
......@@ -15,7 +15,6 @@ import (
"strings"
)
// A Mapping object maps relative paths (e.g. from URLs)
// to absolute paths (of the file system) and vice versa.
//
......@@ -52,13 +51,11 @@ type Mapping struct {
prefixes []string // lazily computed from list
}
type mapping struct {
prefix, path string
value *RWValue
}
// Init initializes the Mapping from a list of paths.
// Empty paths are ignored; relative paths are assumed to be relative to
// the current working directory and converted to absolute paths.
......@@ -93,11 +90,9 @@ func (m *Mapping) Init(paths []string) {
m.list = list
}
// IsEmpty returns true if there are no mappings specified.
func (m *Mapping) IsEmpty() bool { return len(m.list) == 0 }
// PrefixList returns a list of all prefixes, with duplicates removed.
// For instance, for the mapping:
//
......@@ -137,7 +132,6 @@ func (m *Mapping) PrefixList() []string {
return m.prefixes
}
// Fprint prints the mapping.
func (m *Mapping) Fprint(w io.Writer) {
for _, e := range m.list {
......@@ -145,7 +139,6 @@ func (m *Mapping) Fprint(w io.Writer) {
}
}
func splitFirst(path string) (head, tail string) {
i := strings.Index(path, string(filepath.Separator))
if i > 0 {
......@@ -155,7 +148,6 @@ func splitFirst(path string) (head, tail string) {
return "", path
}
// ToAbsolute maps a slash-separated relative path to an absolute filesystem
// path using the Mapping specified by the receiver. If the path cannot
// be mapped, the empty string is returned.
......@@ -181,7 +173,6 @@ func (m *Mapping) ToAbsolute(spath string) string {
return "" // no match
}
// ToRelative maps an absolute filesystem path to a relative slash-separated
// path using the Mapping specified by the receiver. If the path cannot
// be mapped, the empty string is returned.
......@@ -197,7 +188,6 @@ func (m *Mapping) ToRelative(fpath string) string {
return "" // no match
}
// Iterate calls f for each path and RWValue in the mapping (in uspecified order)
// until f returns false.
//
......
......@@ -48,7 +48,6 @@ func parseFiles(fset *token.FileSet, filenames []string) (pkgs map[string]*ast.P
return
}
func parseDir(fset *token.FileSet, path string, filter func(FileInfo) bool) (map[string]*ast.Package, os.Error) {
list, err := fs.ReadDir(path)
if err != nil {
......
......@@ -16,13 +16,11 @@ import (
"fmt"
)
type Snippet struct {
Line int
Text []byte
}
func newSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet {
// TODO instead of pretty-printing the node, should use the original source instead
var buf1 bytes.Buffer
......@@ -35,7 +33,6 @@ func newSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet {
return &Snippet{fset.Position(id.Pos()).Line, buf2.Bytes()}
}
func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec {
for _, spec := range list {
switch s := spec.(type) {
......@@ -58,7 +55,6 @@ func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec {
return nil
}
func genSnippet(fset *token.FileSet, d *ast.GenDecl, id *ast.Ident) *Snippet {
s := findSpec(d.Specs, id)
if s == nil {
......@@ -71,7 +67,6 @@ func genSnippet(fset *token.FileSet, d *ast.GenDecl, id *ast.Ident) *Snippet {
return newSnippet(fset, dd, id)
}
func funcSnippet(fset *token.FileSet, d *ast.FuncDecl, id *ast.Ident) *Snippet {
if d.Name != id {
return nil // declaration doesn't contain id - exit gracefully
......@@ -83,7 +78,6 @@ func funcSnippet(fset *token.FileSet, d *ast.FuncDecl, id *ast.Ident) *Snippet {
return newSnippet(fset, dd, id)
}
// NewSnippet creates a text snippet from a declaration decl containing an
// identifier id. Parts of the declaration not containing the identifier
// may be removed for a more compact snippet.
......
......@@ -18,7 +18,6 @@ import (
"io"
)
type ebnfParser struct {
out io.Writer // parser output
src []byte // parser source
......@@ -30,14 +29,12 @@ type ebnfParser struct {
lit string // token literal
}
func (p *ebnfParser) flush() {
offs := p.file.Offset(p.pos)
p.out.Write(p.src[p.prev:offs])
p.prev = offs
}
func (p *ebnfParser) next() {
if p.pos.IsValid() {
p.flush()
......@@ -50,12 +47,10 @@ func (p *ebnfParser) next() {
}
}
func (p *ebnfParser) Error(pos token.Position, msg string) {
fmt.Fprintf(p.out, `<span class="alert">error: %s</span>`, msg)
}
func (p *ebnfParser) errorExpected(pos token.Pos, msg string) {
msg = "expected " + msg
if pos == p.pos {
......@@ -69,7 +64,6 @@ func (p *ebnfParser) errorExpected(pos token.Pos, msg string) {
p.Error(p.file.Position(pos), msg)
}
func (p *ebnfParser) expect(tok token.Token) token.Pos {
pos := p.pos
if p.tok != tok {
......@@ -79,7 +73,6 @@ func (p *ebnfParser) expect(tok token.Token) token.Pos {
return pos
}
func (p *ebnfParser) parseIdentifier(def bool) {
name := p.lit
p.expect(token.IDENT)
......@@ -91,7 +84,6 @@ func (p *ebnfParser) parseIdentifier(def bool) {
p.prev += len(name) // skip identifier when calling flush
}
func (p *ebnfParser) parseTerm() bool {
switch p.tok {
case token.IDENT:
......@@ -127,7 +119,6 @@ func (p *ebnfParser) parseTerm() bool {
return true
}
func (p *ebnfParser) parseSequence() {
if !p.parseTerm() {
p.errorExpected(p.pos, "term")
......@@ -136,7 +127,6 @@ func (p *ebnfParser) parseSequence() {
}
}
func (p *ebnfParser) parseExpression() {
for {
p.parseSequence()
......@@ -147,7 +137,6 @@ func (p *ebnfParser) parseExpression() {
}
}
func (p *ebnfParser) parseProduction() {
p.parseIdentifier(true)
p.expect(token.ASSIGN)
......@@ -157,7 +146,6 @@ func (p *ebnfParser) parseProduction() {
p.expect(token.PERIOD)
}
func (p *ebnfParser) parse(fset *token.FileSet, out io.Writer, src []byte) {
// initialize ebnfParser
p.out = out
......@@ -173,14 +161,12 @@ func (p *ebnfParser) parse(fset *token.FileSet, out io.Writer, src []byte) {
p.flush()
}
// Markers around EBNF sections
var (
openTag = []byte(`<pre class="ebnf">`)
closeTag = []byte(`</pre>`)
)
func linkify(out io.Writer, src []byte) {
fset := token.NewFileSet()
for len(src) > 0 {
......
......@@ -18,7 +18,6 @@ import (
"utf8"
)
// An RWValue wraps a value and permits mutually exclusive
// access to it and records the time the value was last set.
//
......@@ -28,7 +27,6 @@ type RWValue struct {
timestamp int64 // time of last set(), in seconds since epoch
}
func (v *RWValue) set(value interface{}) {
v.mutex.Lock()
v.value = value
......@@ -36,14 +34,12 @@ func (v *RWValue) set(value interface{}) {
v.mutex.Unlock()
}
func (v *RWValue) get() (interface{}, int64) {
v.mutex.RLock()
defer v.mutex.RUnlock()
return v.value, v.timestamp
}
// TODO(gri) For now, using os.Getwd() is ok here since the functionality
// based on this code is not invoked for the appengine version,
// but this is fragile. Determine what the right thing to do is,
......@@ -94,7 +90,6 @@ func canonicalizePaths(list []string, filter func(path string) bool) []string {
return list[0:i]
}
// writeFileAtomically writes data to a temporary file and then
// atomically renames that file to the file named by filename.
//
......@@ -115,7 +110,6 @@ func writeFileAtomically(filename string, data []byte) os.Error {
return os.Rename(f.Name(), filename)
}
// isText returns true if a significant prefix of s looks like correct UTF-8;
// that is, if it is likely that s is human-readable text.
//
......@@ -137,7 +131,6 @@ func isText(s []byte) bool {
return true
}
// TODO(gri): Should have a mapping from extension to handler, eventually.
// textExt[x] is true if the extension x indicates a text file, and false otherwise.
......@@ -146,7 +139,6 @@ var textExt = map[string]bool{
".js": false, // must be served raw
}
// isTextFile returns true if the file has a known extension indicating
// a text file, or if a significant chunk of the specified file looks like
// correct UTF-8; that is, if it is likely that the file contains human-
......
......@@ -29,19 +29,16 @@ import (
"strings"
)
// zipFI is the zip-file based implementation of FileInfo
type zipFI struct {
name string // directory-local name
file *zip.File // nil for a directory
}
func (fi zipFI) Name() string {
return fi.name
}
func (fi zipFI) Size() int64 {
if fi.file != nil {
return int64(fi.file.UncompressedSize)
......@@ -49,30 +46,25 @@ func (fi zipFI) Size() int64 {
return 0 // directory
}
func (fi zipFI) IsDirectory() bool {
return fi.file == nil
}
func (fi zipFI) IsRegular() bool {
return fi.file != nil
}
// zipFS is the zip-file based implementation of FileSystem
type zipFS struct {
*zip.ReadCloser
list zipList
}
func (fs *zipFS) Close() os.Error {
fs.list = nil
return fs.ReadCloser.Close()
}
func zipPath(name string) string {
if !path.IsAbs(name) {
panic(fmt.Sprintf("stat: not an absolute path: %s", name))
......@@ -80,7 +72,6 @@ func zipPath(name string) string {
return name[1:] // strip '/'
}
func (fs *zipFS) stat(abspath string) (int, zipFI, os.Error) {
i := fs.list.lookup(abspath)
if i < 0 {
......@@ -94,7 +85,6 @@ func (fs *zipFS) stat(abspath string) (int, zipFI, os.Error) {
return i, zipFI{name, file}, nil
}
func (fs *zipFS) Open(abspath string) (io.ReadCloser, os.Error) {
_, fi, err := fs.stat(zipPath(abspath))
if err != nil {
......@@ -106,19 +96,16 @@ func (fs *zipFS) Open(abspath string) (io.ReadCloser, os.Error) {
return fi.file.Open()
}
func (fs *zipFS) Lstat(abspath string) (FileInfo, os.Error) {
_, fi, err := fs.stat(zipPath(abspath))
return fi, err
}
func (fs *zipFS) Stat(abspath string) (FileInfo, os.Error) {
_, fi, err := fs.stat(zipPath(abspath))
return fi, err
}
func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, os.Error) {
path := zipPath(abspath)
i, fi, err := fs.stat(path)
......@@ -157,7 +144,6 @@ func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, os.Error) {
return list, nil
}
func (fs *zipFS) ReadFile(abspath string) ([]byte, os.Error) {
rc, err := fs.Open(abspath)
if err != nil {
......@@ -166,7 +152,6 @@ func (fs *zipFS) ReadFile(abspath string) ([]byte, os.Error) {
return ioutil.ReadAll(rc)
}
func NewZipFS(rc *zip.ReadCloser) FileSystem {
list := make(zipList, len(rc.File))
copy(list, rc.File) // sort a copy of rc.File
......@@ -174,7 +159,6 @@ func NewZipFS(rc *zip.ReadCloser) FileSystem {
return &zipFS{rc, list}
}
type zipList []*zip.File
// zipList implements sort.Interface
......@@ -182,7 +166,6 @@ func (z zipList) Len() int { return len(z) }
func (z zipList) Less(i, j int) bool { return z[i].Name < z[j].Name }
func (z zipList) Swap(i, j int) { z[i], z[j] = z[j], z[i] }
// lookup returns the first index in the zipList
// of a path equal to name or beginning with name/.
func (z zipList) lookup(name string) int {
......
......@@ -62,7 +62,6 @@ func oserrorstring(f *ast.File) bool {
return fixed
}
// callExpr returns the call expression if x is a call to pkg.name with one argument;
// otherwise it returns nil.
func callExpr(x interface{}, pkg, name string) *ast.CallExpr {
......
......@@ -63,7 +63,6 @@ func f() {
import "os"
func f() {
var _ os.Error
_ = os.SIGHUP
......@@ -86,7 +85,6 @@ func f() {
import "os"
func f() {
var _ os.Error
_ = os.SIGHUP
......
......@@ -17,7 +17,6 @@ func init() {
})
}
func sorthelpers(f *ast.File) (fixed bool) {
if !imports(f, "sort") {
return
......
......@@ -20,7 +20,6 @@ http://codereview.appspot.com/4639041
})
}
func sortslice(f *ast.File) (fixed bool) {
if !imports(f, "sort") {
return
......
......@@ -198,7 +198,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) {
// An Enumerated is represented as a plain int.
type Enumerated int
// FLAG
// A Flag accepts any data and is set to true if present.
......
......@@ -198,7 +198,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) {
// An Enumerated is represented as a plain int.
type Enumerated int
// FLAG
// A Flag accepts any data and is set to true if present.
......
......@@ -211,7 +211,6 @@ import (
"runtime"
)
// ----------------------------------------------------------------------------
// Format representation
......@@ -228,13 +227,11 @@ import (
//
type Formatter func(state *State, value interface{}, ruleName string) bool
// A FormatterMap is a set of custom formatters.
// It maps a rule name to a formatter function.
//
type FormatterMap map[string]Formatter
// A parsed format expression is built from the following nodes.
//
type (
......@@ -269,13 +266,11 @@ type (
}
)
// A Format is the result of parsing a format specification.
// The format may be applied repeatedly to format values.
//
type Format map[string]expr
// ----------------------------------------------------------------------------
// Formatting
......@@ -293,7 +288,6 @@ type Environment interface {
Copy() Environment
}
// State represents the current formatting state.
// It is provided as argument to custom formatters.
//
......@@ -309,7 +303,6 @@ type State struct {
separator expr // possibly nil
}
func newState(fmt Format, env Environment, errors chan os.Error) *State {
s := new(State)
s.fmt = fmt
......@@ -330,17 +323,14 @@ func newState(fmt Format, env Environment, errors chan os.Error) *State {
return s
}
// Env returns the environment passed to Format.Apply.
func (s *State) Env() interface{} { return s.env }
// LinePos returns the position of the current line beginning
// in the state's output buffer. Line numbers start at 1.
//
func (s *State) LinePos() token.Position { return s.linePos }
// Pos returns the position of the next byte to be written to the
// output buffer. Line numbers start at 1.
//
......@@ -349,7 +339,6 @@ func (s *State) Pos() token.Position {
return token.Position{Line: s.linePos.Line, Column: offs - s.linePos.Offset, Offset: offs}
}
// Write writes data to the output buffer, inserting the indentation
// string after each newline or form feed character. It cannot return an error.
//
......@@ -371,7 +360,6 @@ func (s *State) Write(data []byte) (int, os.Error) {
return n + n3, nil
}
type checkpoint struct {
env Environment
hasOutput bool
......@@ -379,7 +367,6 @@ type checkpoint struct {
linePos token.Position
}
func (s *State) save() checkpoint {
saved := checkpoint{nil, s.hasOutput, s.output.Len(), s.linePos}
if s.env != nil {
......@@ -388,19 +375,16 @@ func (s *State) save() checkpoint {
return saved
}
func (s *State) restore(m checkpoint) {
s.env = m.env
s.output.Truncate(m.outputLen)
}
func (s *State) error(msg string) {
s.errors <- os.NewError(msg)
runtime.Goexit()
}
// TODO At the moment, unnamed types are simply mapped to the default
// names below. For instance, all unnamed arrays are mapped to
// 'array' which is not really sufficient. Eventually one may want
......@@ -440,7 +424,6 @@ func (s *State) getFormat(name string) expr {
return nil
}
// eval applies a format expression fexpr to a value. If the expression
// evaluates internally to a non-nil []byte, that slice is appended to
// the state's output buffer and eval returns true. Otherwise, eval
......@@ -653,7 +636,6 @@ func (s *State) eval(fexpr expr, value reflect.Value, index int) bool {
return false
}
// Eval formats each argument according to the format
// f and returns the resulting []byte and os.Error. If
// an error occurred, the []byte contains the partially
......@@ -688,7 +670,6 @@ func (f Format) Eval(env Environment, args ...interface{}) ([]byte, os.Error) {
return s.output.Bytes(), err
}
// ----------------------------------------------------------------------------
// Convenience functions
......@@ -705,7 +686,6 @@ func (f Format) Fprint(w io.Writer, env Environment, args ...interface{}) (int,
return w.Write(data)
}
// Print formats each argument according to the format f
// and writes to standard output. The result is the total
// number of bytes written and an os.Error, if any.
......@@ -714,7 +694,6 @@ func (f Format) Print(args ...interface{}) (int, os.Error) {
return f.Fprint(os.Stdout, nil, args...)
}
// Sprint formats each argument according to the format f
// and returns the resulting string. If an error occurs
// during formatting, the result string contains the
......
......@@ -211,7 +211,6 @@ import (
"runtime"
)
// ----------------------------------------------------------------------------
// Format representation
......@@ -228,13 +227,11 @@ import (
//
type Formatter func(state *State, value interface{}, ruleName string) bool
// A FormatterMap is a set of custom formatters.
// It maps a rule name to a formatter function.
//
type FormatterMap map[string]Formatter
// A parsed format expression is built from the following nodes.
//
type (
......@@ -269,13 +266,11 @@ type (
}
)
// A Format is the result of parsing a format specification.
// The format may be applied repeatedly to format values.
//
type Format map[string]expr
// ----------------------------------------------------------------------------
// Formatting
......@@ -293,7 +288,6 @@ type Environment interface {
Copy() Environment
}
// State represents the current formatting state.
// It is provided as argument to custom formatters.
//
......@@ -309,7 +303,6 @@ type State struct {
separator expr // possibly nil
}
func newState(fmt Format, env Environment, errors chan os.Error) *State {
s := new(State)
s.fmt = fmt
......@@ -330,17 +323,14 @@ func newState(fmt Format, env Environment, errors chan os.Error) *State {
return s
}
// Env returns the environment passed to Format.Apply.
func (s *State) Env() interface{} { return s.env }
// LinePos returns the position of the current line beginning
// in the state's output buffer. Line numbers start at 1.
//
func (s *State) LinePos() token.Position { return s.linePos }
// Pos returns the position of the next byte to be written to the
// output buffer. Line numbers start at 1.
//
......@@ -349,7 +339,6 @@ func (s *State) Pos() token.Position {
return token.Position{Line: s.linePos.Line, Column: offs - s.linePos.Offset, Offset: offs}
}
// Write writes data to the output buffer, inserting the indentation
// string after each newline or form feed character. It cannot return an error.
//
......@@ -371,7 +360,6 @@ func (s *State) Write(data []byte) (int, os.Error) {
return n + n3, nil
}
type checkpoint struct {
env Environment
hasOutput bool
......@@ -379,7 +367,6 @@ type checkpoint struct {
linePos token.Position
}
func (s *State) save() checkpoint {
saved := checkpoint{nil, s.hasOutput, s.output.Len(), s.linePos}
if s.env != nil {
......@@ -388,19 +375,16 @@ func (s *State) save() checkpoint {
return saved
}
func (s *State) restore(m checkpoint) {
s.env = m.env
s.output.Truncate(m.outputLen)
}
func (s *State) error(msg string) {
s.errors <- os.NewError(msg)
runtime.Goexit()
}
// TODO At the moment, unnamed types are simply mapped to the default
// names below. For instance, all unnamed arrays are mapped to
// 'array' which is not really sufficient. Eventually one may want
......@@ -440,7 +424,6 @@ func (s *State) getFormat(name string) expr {
return nil
}
// eval applies a format expression fexpr to a value. If the expression
// evaluates internally to a non-nil []byte, that slice is appended to
// the state's output buffer and eval returns true. Otherwise, eval
......@@ -653,7 +636,6 @@ func (s *State) eval(fexpr expr, value reflect.Value, index int) bool {
return false
}
// Eval formats each argument according to the format
// f and returns the resulting []byte and os.Error. If
// an error occurred, the []byte contains the partially
......@@ -688,7 +670,6 @@ func (f Format) Eval(env Environment, args ...interface{}) ([]byte, os.Error) {
return s.output.Bytes(), err
}
// ----------------------------------------------------------------------------
// Convenience functions
......@@ -705,7 +686,6 @@ func (f Format) Fprint(w io.Writer, env Environment, args ...interface{}) (int,
return w.Write(data)
}
// Print formats each argument according to the format f
// and writes to standard output. The result is the total
// number of bytes written and an os.Error, if any.
......@@ -714,7 +694,6 @@ func (f Format) Print(args ...interface{}) (int, os.Error) {
return f.Fprint(os.Stdout, nil, args...)
}
// Sprint formats each argument according to the format f
// and returns the resulting string. If an error occurs
// during formatting, the result string contains the
......
......@@ -71,7 +71,6 @@ type Unmarshaler interface {
UnmarshalJSON([]byte) os.Error
}
// An UnmarshalTypeError describes a JSON value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
......@@ -732,7 +731,6 @@ func (d *decodeState) objectInterface() map[string]interface{} {
return m
}
// literalInterface is like literal but returns an interface value.
func (d *decodeState) literalInterface() interface{} {
// All bytes inside literal return scanContinue op code.
......
......@@ -71,7 +71,6 @@ type Unmarshaler interface {
UnmarshalJSON([]byte) os.Error
}
// An UnmarshalTypeError describes a JSON value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
......@@ -735,7 +734,6 @@ func (d *decodeState) objectInterface() map[string]interface{} {
return m
}
// literalInterface is like literal but returns an interface value.
func (d *decodeState) literalInterface() interface{} {
// All bytes inside literal return scanContinue op code.
......
......@@ -117,7 +117,6 @@ type dnsRR interface {
Header() *dnsRR_Header
}
// Specific DNS RR formats for each query type.
type dnsRR_CNAME struct {
......@@ -645,7 +644,6 @@ type dnsMsg struct {
extra []dnsRR
}
func (dns *dnsMsg) Pack() (msg []byte, ok bool) {
var dh dnsHeader
......
......@@ -117,7 +117,6 @@ type dnsRR interface {
Header() *dnsRR_Header
}
// Specific DNS RR formats for each query type.
type dnsRR_CNAME struct {
......@@ -645,7 +644,6 @@ type dnsMsg struct {
extra []dnsRR
}
func (dns *dnsMsg) Pack() (msg []byte, ok bool) {
var dh dnsHeader
......
......@@ -252,7 +252,6 @@ func Sprintln(a ...interface{}) string {
return s
}
// Get the i'th arg of the struct value.
// If the arg itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
......
......@@ -252,7 +252,6 @@ func Sprintln(a ...interface{}) string {
return s
}
// Get the i'th arg of the struct value.
// If the arg itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
......
......@@ -324,7 +324,6 @@ func (r *readRune) ReadRune() (rune int, size int, err os.Error) {
return
}
var ssFree = newCache(func() interface{} { return new(ss) })
// Allocate a new ss struct or grab a cached one.
......@@ -398,7 +397,6 @@ func (s *ss) skipSpace(stopAtNewline bool) {
}
}
// token returns the next space-delimited string from the input. It
// skips white space. For Scanln, it stops at newlines. For Scan,
// newlines are treated as spaces.
......
......@@ -324,7 +324,6 @@ func (r *readRune) ReadRune() (rune int, size int, err os.Error) {
return
}
var ssFree = newCache(func() interface{} { return new(ss) })
// Allocate a new ss struct or grab a cached one.
......@@ -398,7 +397,6 @@ func (s *ss) skipSpace(stopAtNewline bool) {
}
}
// token returns the next space-delimited string from the input. It
// skips white space. For Scanln, it stops at newlines. For Scan,
// newlines are treated as spaces.
......
......@@ -22,7 +22,6 @@ import (
"strings"
)
var (
// main operation modes
list = flag.Bool("l", false, "list files whose formatting differs from gofmt's")
......@@ -41,7 +40,6 @@ var (
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
)
var (
fset = token.NewFileSet()
exitCode = 0
......@@ -50,20 +48,17 @@ var (
printerMode uint
)
func report(err os.Error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n")
flag.PrintDefaults()
os.Exit(2)
}
func initParserMode() {
parserMode = uint(0)
if *comments {
......@@ -71,7 +66,6 @@ func initParserMode() {
}
}
func initPrinterMode() {
printerMode = uint(0)
if *tabIndent {
......@@ -82,13 +76,11 @@ func initPrinterMode() {
}
}
func isGoFile(f *os.FileInfo) bool {
// ignore non-Go files
return f.IsRegular() && !strings.HasPrefix(f.Name, ".") && strings.HasSuffix(f.Name, ".go")
}
// If in == nil, the source is the contents of the file with the given filename.
func processFile(filename string, in io.Reader, out io.Writer) os.Error {
if in == nil {
......@@ -153,14 +145,12 @@ func processFile(filename string, in io.Reader, out io.Writer) os.Error {
return err
}
type fileVisitor chan os.Error
func (v fileVisitor) VisitDir(path string, f *os.FileInfo) bool {
return true
}
func (v fileVisitor) VisitFile(path string, f *os.FileInfo) {
if isGoFile(f) {
v <- nil // synchronize error handler
......@@ -170,7 +160,6 @@ func (v fileVisitor) VisitFile(path string, f *os.FileInfo) {
}
}
func walkDir(path string) {
v := make(fileVisitor)
go func() {
......@@ -184,7 +173,6 @@ func walkDir(path string) {
}
}
func main() {
// call gofmtMain in a separate function
// so that it can use defer and have them
......@@ -193,7 +181,6 @@ func main() {
os.Exit(exitCode)
}
func gofmtMain() {
flag.Usage = usage
flag.Parse()
......@@ -241,7 +228,6 @@ func gofmtMain() {
}
}
func diff(b1, b2 []byte) (data []byte, err os.Error) {
f1, err := ioutil.TempFile("", "gofmt")
if err != nil {
......
......@@ -12,7 +12,6 @@ import (
"testing"
)
func runTest(t *testing.T, dirname, in, out, flags string) {
in = filepath.Join(dirname, in)
out = filepath.Join(dirname, out)
......@@ -62,7 +61,6 @@ func runTest(t *testing.T, dirname, in, out, flags string) {
}
}
// TODO(gri) Add more test cases!
var tests = []struct {
dirname, in, out, flags string
......@@ -74,7 +72,6 @@ var tests = []struct {
{"testdata", "rewrite2.input", "rewrite2.golden", "-r=int->bool"},
}
func TestRewrite(t *testing.T) {
for _, test := range tests {
runTest(t, test.dirname, test.in, test.out, test.flags)
......
......@@ -16,7 +16,6 @@ import (
"utf8"
)
func initRewrite() {
if *rewriteRule == "" {
rewrite = nil // disable any previous rewrite
......@@ -32,7 +31,6 @@ func initRewrite() {
rewrite = func(p *ast.File) *ast.File { return rewriteFile(pattern, replace, p) }
}
// parseExpr parses s as an expression.
// It might make sense to expand this to allow statement patterns,
// but there are problems with preserving formatting and also
......@@ -46,7 +44,6 @@ func parseExpr(s string, what string) ast.Expr {
return x
}
// Keep this function for debugging.
/*
func dump(msg string, val reflect.Value) {
......@@ -56,7 +53,6 @@ func dump(msg string, val reflect.Value) {
}
*/
// rewriteFile applies the rewrite rule 'pattern -> replace' to an entire file.
func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File {
m := make(map[string]reflect.Value)
......@@ -80,7 +76,6 @@ func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File {
return apply(f, reflect.ValueOf(p)).Interface().(*ast.File)
}
// setValue is a wrapper for x.SetValue(y); it protects
// the caller from panics if x cannot be changed to y.
func setValue(x, y reflect.Value) {
......@@ -100,7 +95,6 @@ func setValue(x, y reflect.Value) {
x.Set(y)
}
// Values/types for special cases.
var (
objectPtrNil = reflect.ValueOf((*ast.Object)(nil))
......@@ -112,7 +106,6 @@ var (
scopePtrType = reflect.TypeOf((*ast.Scope)(nil))
)
// apply replaces each AST field x in val with f(x), returning val.
// To avoid extra conversions, f operates on the reflect.Value form.
func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value {
......@@ -150,13 +143,11 @@ func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value
return val
}
func isWildcard(s string) bool {
rune, size := utf8.DecodeRuneInString(s)
return size == len(s) && unicode.IsLower(rune)
}
// match returns true if pattern matches val,
// recording wildcard submatches in m.
// If m == nil, match checks whether pattern == val.
......@@ -238,7 +229,6 @@ func match(m map[string]reflect.Value, pattern, val reflect.Value) bool {
return p.Interface() == v.Interface()
}
// subst returns a copy of pattern with values from m substituted in place
// of wildcards and pos used as the position of tokens from the pattern.
// if m == nil, subst returns a copy of pattern and doesn't change the line
......
......@@ -9,7 +9,6 @@ import (
"reflect"
)
type simplifier struct{}
func (s *simplifier) Visit(node ast.Node) ast.Visitor {
......@@ -60,7 +59,6 @@ func (s *simplifier) Visit(node ast.Node) ast.Visitor {
return s
}
func simplify(node ast.Node) {
var s simplifier
ast.Walk(&s, node)
......
......@@ -254,7 +254,6 @@ func install(pkg, parent string) {
return
}
// Is this a standard package path? strings container/vector etc.
// Assume that if the first element has a dot, it's a domain name
// and is not the standard package path.
......
......@@ -18,7 +18,6 @@ import (
"strings"
)
var (
// main operation modes
pkgName = flag.String("p", "", "process only those files in package pkgName")
......@@ -30,23 +29,19 @@ var (
printAST = flag.Bool("ast", false, "print AST")
)
var exitCode = 0
func usage() {
fmt.Fprintf(os.Stderr, "usage: gotype [flags] [path ...]\n")
flag.PrintDefaults()
os.Exit(2)
}
func report(err os.Error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
// parse returns the AST for the Go source src.
// The filename is for error reporting only.
// The result is nil if there were errors or if
......@@ -88,7 +83,6 @@ func parse(fset *token.FileSet, filename string, src []byte) *ast.File {
return file
}
func parseStdin(fset *token.FileSet) (files map[string]*ast.File) {
files = make(map[string]*ast.File)
src, err := ioutil.ReadAll(os.Stdin)
......@@ -103,7 +97,6 @@ func parseStdin(fset *token.FileSet) (files map[string]*ast.File) {
return
}
func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast.File) {
files = make(map[string]*ast.File)
for _, filename := range filenames {
......@@ -123,13 +116,11 @@ func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast.
return
}
func isGoFilename(filename string) bool {
// ignore non-Go files
return !strings.HasPrefix(filename, ".") && strings.HasSuffix(filename, ".go")
}
func processDirectory(dirname string) {
f, err := os.Open(dirname)
if err != nil {
......@@ -148,7 +139,6 @@ func processDirectory(dirname string) {
processFiles(filenames, false)
}
func processFiles(filenames []string, allFiles bool) {
i := 0
for _, filename := range filenames {
......@@ -170,7 +160,6 @@ func processFiles(filenames []string, allFiles bool) {
processPackage(fset, parseFiles(fset, filenames[0:i]))
}
func processPackage(fset *token.FileSet, files map[string]*ast.File) {
// make a package (resolve all identifiers)
pkg, err := ast.NewPackage(fset, files, types.GcImporter, types.Universe)
......@@ -184,7 +173,6 @@ func processPackage(fset *token.FileSet, files map[string]*ast.File) {
}
}
func main() {
flag.Usage = usage
flag.Parse()
......
......@@ -10,7 +10,6 @@ import (
"testing"
)
func runTest(t *testing.T, path, pkg string) {
exitCode = 0
*pkgName = pkg
......@@ -27,7 +26,6 @@ func runTest(t *testing.T, path, pkg string) {
}
}
var tests = []struct {
path string
pkg string
......@@ -44,7 +42,6 @@ var tests = []struct {
{filepath.Join(runtime.GOROOT(), "src/pkg/go/types"), "types"},
}
func Test(t *testing.T) {
for _, test := range tests {
runTest(t, test.path, test.pkg)
......
......@@ -348,7 +348,6 @@ FlagLoop:
return
}
// checkPrint checks a call to an unformatted print routine such as Println.
// The skip argument records how many arguments to ignore; that is,
// call.Args[skip] is the first argument to be printed.
......
......@@ -182,7 +182,6 @@ func main() {
}
}
// make parent directory for name, if necessary
func makeParent(name string) {
parent, _ := filepath.Split(name)
......@@ -240,7 +239,6 @@ func chk(err os.Error) {
}
}
// Undo log
type undo func() os.Error
......@@ -258,7 +256,6 @@ func runUndo() {
}
}
// hgRoot returns the root directory of the repository.
func hgRoot() (string, os.Error) {
out, err := run([]string{"hg", "root"}, nil)
......
......@@ -178,7 +178,6 @@ func TestPartialRead(t *testing.T) {
}
}
func TestIncrementalRead(t *testing.T) {
test := gnuTarTest
f, err := os.Open(test.file)
......
......@@ -220,7 +220,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) {
// An Enumerated is represented as a plain int.
type Enumerated int
// FLAG
// A Flag accepts any data and is set to true if present.
......
......@@ -27,7 +27,6 @@ const (
_M2 = _B2 - 1 // half digit mask
)
// ----------------------------------------------------------------------------
// Elementary operations on words
//
......@@ -43,7 +42,6 @@ func addWW_g(x, y, c Word) (z1, z0 Word) {
return
}
// z1<<_W + z0 = x-y-c, with c == 0 or 1
func subWW_g(x, y, c Word) (z1, z0 Word) {
yc := y + c
......@@ -54,7 +52,6 @@ func subWW_g(x, y, c Word) (z1, z0 Word) {
return
}
// z1<<_W + z0 = x*y
// Adapted from Warren, Hacker's Delight, p. 132.
func mulWW_g(x, y Word) (z1, z0 Word) {
......@@ -72,7 +69,6 @@ func mulWW_g(x, y Word) (z1, z0 Word) {
return
}
// z1<<_W + z0 = x*y + c
func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
z1, zz0 := mulWW(x, y)
......@@ -82,7 +78,6 @@ func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
return
}
// Length of x in bits.
func bitLen(x Word) (n int) {
for ; x >= 0x100; x >>= 8 {
......@@ -94,7 +89,6 @@ func bitLen(x Word) (n int) {
return
}
// log2 computes the integer binary logarithm of x.
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
......@@ -102,13 +96,11 @@ func log2(x Word) int {
return bitLen(x) - 1
}
// Number of leading zeros in x.
func leadingZeros(x Word) uint {
return uint(_W - bitLen(x))
}
// q = (u1<<_W + u0 - r)/y
// Adapted from Warren, Hacker's Delight, p. 152.
func divWW_g(u1, u0, v Word) (q, r Word) {
......@@ -153,7 +145,6 @@ again2:
return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s
}
func addVV_g(z, x, y []Word) (c Word) {
for i := range z {
c, z[i] = addWW_g(x[i], y[i], c)
......@@ -161,7 +152,6 @@ func addVV_g(z, x, y []Word) (c Word) {
return
}
func subVV_g(z, x, y []Word) (c Word) {
for i := range z {
c, z[i] = subWW_g(x[i], y[i], c)
......@@ -169,7 +159,6 @@ func subVV_g(z, x, y []Word) (c Word) {
return
}
func addVW_g(z, x []Word, y Word) (c Word) {
c = y
for i := range z {
......@@ -178,7 +167,6 @@ func addVW_g(z, x []Word, y Word) (c Word) {
return
}
func subVW_g(z, x []Word, y Word) (c Word) {
c = y
for i := range z {
......@@ -187,7 +175,6 @@ func subVW_g(z, x []Word, y Word) (c Word) {
return
}
func shlVU_g(z, x []Word, s uint) (c Word) {
if n := len(z); n > 0 {
ŝ := _W - s
......@@ -203,7 +190,6 @@ func shlVU_g(z, x []Word, s uint) (c Word) {
return
}
func shrVU_g(z, x []Word, s uint) (c Word) {
if n := len(z); n > 0 {
ŝ := _W - s
......@@ -219,7 +205,6 @@ func shrVU_g(z, x []Word, s uint) (c Word) {
return
}
func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
c = r
for i := range z {
......@@ -228,7 +213,6 @@ func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
return
}
func addMulVVW_g(z, x []Word, y Word) (c Word) {
for i := range z {
z1, z0 := mulAddWWW_g(x[i], y, z[i])
......@@ -238,7 +222,6 @@ func addMulVVW_g(z, x []Word, y Word) (c Word) {
return
}
func divWVW_g(z []Word, xn Word, x []Word, y Word) (r Word) {
r = xn
for i := len(z) - 1; i >= 0; i-- {
......
......@@ -6,7 +6,6 @@ package big
import "testing"
type funWW func(x, y, c Word) (z1, z0 Word)
type argWW struct {
x, y, c, z1, z0 Word
......@@ -26,7 +25,6 @@ var sumWW = []argWW{
{_M, _M, 1, 1, _M},
}
func testFunWW(t *testing.T, msg string, f funWW, a argWW) {
z1, z0 := f(a.x, a.y, a.c)
if z1 != a.z1 || z0 != a.z0 {
......@@ -34,7 +32,6 @@ func testFunWW(t *testing.T, msg string, f funWW, a argWW) {
}
}
func TestFunWW(t *testing.T) {
for _, a := range sumWW {
arg := a
......@@ -51,7 +48,6 @@ func TestFunWW(t *testing.T) {
}
}
type funVV func(z, x, y []Word) (c Word)
type argVV struct {
z, x, y nat
......@@ -70,7 +66,6 @@ var sumVV = []argVV{
{nat{0, 0, 0, 0}, nat{_M, 0, _M, 0}, nat{1, _M, 0, _M}, 1},
}
func testFunVV(t *testing.T, msg string, f funVV, a argVV) {
z := make(nat, len(a.z))
c := f(z, a.x, a.y)
......@@ -85,7 +80,6 @@ func testFunVV(t *testing.T, msg string, f funVV, a argVV) {
}
}
func TestFunVV(t *testing.T) {
for _, a := range sumVV {
arg := a
......@@ -106,7 +100,6 @@ func TestFunVV(t *testing.T) {
}
}
type funVW func(z, x []Word, y Word) (c Word)
type argVW struct {
z, x nat
......@@ -169,7 +162,6 @@ var rshVW = []argVW{
{nat{_M, _M, _M >> 20}, nat{_M, _M, _M}, 20, _M << (_W - 20) & _M},
}
func testFunVW(t *testing.T, msg string, f funVW, a argVW) {
z := make(nat, len(a.z))
c := f(z, a.x, a.y)
......@@ -184,14 +176,12 @@ func testFunVW(t *testing.T, msg string, f funVW, a argVW) {
}
}
func makeFunVW(f func(z, x []Word, s uint) (c Word)) funVW {
return func(z, x []Word, s Word) (c Word) {
return f(z, x, uint(s))
}
}
func TestFunVW(t *testing.T) {
for _, a := range sumVW {
arg := a
......@@ -220,7 +210,6 @@ func TestFunVW(t *testing.T) {
}
}
type funVWW func(z, x []Word, y, r Word) (c Word)
type argVWW struct {
z, x nat
......@@ -254,7 +243,6 @@ var prodVWW = []argVWW{
{nat{_M<<7&_M + 1<<6, _M, _M, _M}, nat{_M, _M, _M, _M}, 1 << 7, 1 << 6, _M >> (_W - 7)},
}
func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) {
z := make(nat, len(a.z))
c := f(z, a.x, a.y, a.r)
......@@ -269,7 +257,6 @@ func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) {
}
}
// TODO(gri) mulAddVWW and divWVW are symmetric operations but
// their signature is not symmetric. Try to unify.
......@@ -296,7 +283,6 @@ func testFunWVW(t *testing.T, msg string, f funWVW, a argWVW) {
}
}
func TestFunVWW(t *testing.T) {
for _, a := range prodVWW {
arg := a
......@@ -311,7 +297,6 @@ func TestFunVWW(t *testing.T) {
}
}
var mulWWTests = []struct {
x, y Word
q, r Word
......@@ -320,7 +305,6 @@ var mulWWTests = []struct {
// 32 bit only: {0xc47dfa8c, 50911, 0x98a4, 0x998587f4},
}
func TestMulWW(t *testing.T) {
for i, test := range mulWWTests {
q, r := mulWW_g(test.x, test.y)
......@@ -330,7 +314,6 @@ func TestMulWW(t *testing.T) {
}
}
var mulAddWWWTests = []struct {
x, y, c Word
q, r Word
......@@ -342,7 +325,6 @@ var mulAddWWWTests = []struct {
{_M, _M, _M, _M, 0},
}
func TestMulAddWWW(t *testing.T) {
for i, test := range mulAddWWWTests {
q, r := mulAddWWW_g(test.x, test.y, test.c)
......
......@@ -19,10 +19,8 @@ import (
"time"
)
var calibrate = flag.Bool("calibrate", false, "run calibration test")
// measure returns the time to run f
func measure(f func()) int64 {
const N = 100
......@@ -34,7 +32,6 @@ func measure(f func()) int64 {
return (stop - start) / N
}
func computeThresholds() {
fmt.Printf("Multiplication times for varying Karatsuba thresholds\n")
fmt.Printf("(run repeatedly for good results)\n")
......@@ -84,7 +81,6 @@ func computeThresholds() {
}
}
func TestCalibrate(t *testing.T) {
if *calibrate {
computeThresholds()
......
......@@ -13,13 +13,11 @@ import (
"testing"
)
type matrix struct {
n, m int
a []*Rat
}
func (a *matrix) at(i, j int) *Rat {
if !(0 <= i && i < a.n && 0 <= j && j < a.m) {
panic("index out of range")
......@@ -27,7 +25,6 @@ func (a *matrix) at(i, j int) *Rat {
return a.a[i*a.m+j]
}
func (a *matrix) set(i, j int, x *Rat) {
if !(0 <= i && i < a.n && 0 <= j && j < a.m) {
panic("index out of range")
......@@ -35,7 +32,6 @@ func (a *matrix) set(i, j int, x *Rat) {
a.a[i*a.m+j] = x
}
func newMatrix(n, m int) *matrix {
if !(0 <= n && 0 <= m) {
panic("illegal matrix")
......@@ -47,7 +43,6 @@ func newMatrix(n, m int) *matrix {
return a
}
func newUnit(n int) *matrix {
a := newMatrix(n, n)
for i := 0; i < n; i++ {
......@@ -62,7 +57,6 @@ func newUnit(n int) *matrix {
return a
}
func newHilbert(n int) *matrix {
a := newMatrix(n, n)
for i := 0; i < n; i++ {
......@@ -73,7 +67,6 @@ func newHilbert(n int) *matrix {
return a
}
func newInverseHilbert(n int) *matrix {
a := newMatrix(n, n)
for i := 0; i < n; i++ {
......@@ -98,7 +91,6 @@ func newInverseHilbert(n int) *matrix {
return a
}
func (a *matrix) mul(b *matrix) *matrix {
if a.m != b.n {
panic("illegal matrix multiply")
......@@ -116,7 +108,6 @@ func (a *matrix) mul(b *matrix) *matrix {
return c
}
func (a *matrix) eql(b *matrix) bool {
if a.n != b.n || a.m != b.m {
return false
......@@ -131,7 +122,6 @@ func (a *matrix) eql(b *matrix) bool {
return true
}
func (a *matrix) String() string {
s := ""
for i := 0; i < a.n; i++ {
......@@ -143,7 +133,6 @@ func (a *matrix) String() string {
return s
}
func doHilbert(t *testing.T, n int) {
a := newHilbert(n)
b := newInverseHilbert(n)
......@@ -160,12 +149,10 @@ func doHilbert(t *testing.T, n int) {
}
}
func TestHilbert(t *testing.T) {
doHilbert(t, 10)
}
func BenchmarkHilbert(b *testing.B) {
for i := 0; i < b.N; i++ {
doHilbert(nil, 10)
......
......@@ -21,10 +21,8 @@ type Int struct {
abs nat // absolute value of the integer
}
var intOne = &Int{false, natOne}
// Sign returns:
//
// -1 if x < 0
......@@ -41,7 +39,6 @@ func (x *Int) Sign() int {
return 1
}
// SetInt64 sets z to x and returns z.
func (z *Int) SetInt64(x int64) *Int {
neg := false
......@@ -54,13 +51,11 @@ func (z *Int) SetInt64(x int64) *Int {
return z
}
// NewInt allocates and returns a new Int set to x.
func NewInt(x int64) *Int {
return new(Int).SetInt64(x)
}
// Set sets z to x and returns z.
func (z *Int) Set(x *Int) *Int {
z.abs = z.abs.set(x.abs)
......@@ -68,7 +63,6 @@ func (z *Int) Set(x *Int) *Int {
return z
}
// Abs sets z to |x| (the absolute value of x) and returns z.
func (z *Int) Abs(x *Int) *Int {
z.abs = z.abs.set(x.abs)
......@@ -76,7 +70,6 @@ func (z *Int) Abs(x *Int) *Int {
return z
}
// Neg sets z to -x and returns z.
func (z *Int) Neg(x *Int) *Int {
z.abs = z.abs.set(x.abs)
......@@ -84,7 +77,6 @@ func (z *Int) Neg(x *Int) *Int {
return z
}
// Add sets z to the sum x+y and returns z.
func (z *Int) Add(x, y *Int) *Int {
neg := x.neg
......@@ -106,7 +98,6 @@ func (z *Int) Add(x, y *Int) *Int {
return z
}
// Sub sets z to the difference x-y and returns z.
func (z *Int) Sub(x, y *Int) *Int {
neg := x.neg
......@@ -128,7 +119,6 @@ func (z *Int) Sub(x, y *Int) *Int {
return z
}
// Mul sets z to the product x*y and returns z.
func (z *Int) Mul(x, y *Int) *Int {
// x * y == x * y
......@@ -140,7 +130,6 @@ func (z *Int) Mul(x, y *Int) *Int {
return z
}
// MulRange sets z to the product of all integers
// in the range [a, b] inclusively and returns z.
// If a > b (empty range), the result is 1.
......@@ -164,7 +153,6 @@ func (z *Int) MulRange(a, b int64) *Int {
return z
}
// Binomial sets z to the binomial coefficient of (n, k) and returns z.
func (z *Int) Binomial(n, k int64) *Int {
var a, b Int
......@@ -173,7 +161,6 @@ func (z *Int) Binomial(n, k int64) *Int {
return z.Quo(&a, &b)
}
// Quo sets z to the quotient x/y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See QuoRem for more details.
......@@ -183,7 +170,6 @@ func (z *Int) Quo(x, y *Int) *Int {
return z
}
// Rem sets z to the remainder x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See QuoRem for more details.
......@@ -193,7 +179,6 @@ func (z *Int) Rem(x, y *Int) *Int {
return z
}
// QuoRem sets z to the quotient x/y and r to the remainder x%y
// and returns the pair (z, r) for y != 0.
// If y == 0, a division-by-zero run-time panic occurs.
......@@ -211,7 +196,6 @@ func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
return z, r
}
// Div sets z to the quotient x/y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See DivMod for more details.
......@@ -229,7 +213,6 @@ func (z *Int) Div(x, y *Int) *Int {
return z
}
// Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See DivMod for more details.
......@@ -250,7 +233,6 @@ func (z *Int) Mod(x, y *Int) *Int {
return z
}
// DivMod sets z to the quotient x div y and m to the modulus x mod y
// and returns the pair (z, m) for y != 0.
// If y == 0, a division-by-zero run-time panic occurs.
......@@ -283,7 +265,6 @@ func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
return z, m
}
// Cmp compares x and y and returns:
//
// -1 if x < y
......@@ -309,7 +290,6 @@ func (x *Int) Cmp(y *Int) (r int) {
return
}
func (x *Int) String() string {
switch {
case x == nil:
......@@ -320,7 +300,6 @@ func (x *Int) String() string {
return x.abs.decimalString()
}
func charset(ch int) string {
switch ch {
case 'b':
......@@ -337,7 +316,6 @@ func charset(ch int) string {
return "" // unknown format
}
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x'
// (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
......@@ -424,7 +402,6 @@ func (x *Int) Format(s fmt.State, ch int) {
fmt.Fprint(s, t)
}
// scan sets z to the integer value corresponding to the longest possible prefix
// read from r representing a signed integer number in a given conversion base.
// It returns z, the actual conversion base used, and an error, if any. In the
......@@ -461,7 +438,6 @@ func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) {
return z, base, nil
}
// Scan is a support routine for fmt.Scanner; it sets z to the value of
// the scanned number. It accepts the formats 'b' (binary), 'o' (octal),
// 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
......@@ -486,7 +462,6 @@ func (z *Int) Scan(s fmt.ScanState, ch int) os.Error {
return err
}
// Int64 returns the int64 representation of x.
// If x cannot be represented in an int64, the result is undefined.
func (x *Int) Int64() int64 {
......@@ -503,7 +478,6 @@ func (x *Int) Int64() int64 {
return v
}
// SetString sets z to the value of s, interpreted in the given base,
// and returns z and a boolean indicating success. If SetString fails,
// the value of z is undefined.
......@@ -523,7 +497,6 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
return z, err == os.EOF // err == os.EOF => scan consumed all of s
}
// SetBytes interprets buf as the bytes of a big-endian unsigned
// integer, sets z to that value, and returns z.
func (z *Int) SetBytes(buf []byte) *Int {
......@@ -532,21 +505,18 @@ func (z *Int) SetBytes(buf []byte) *Int {
return z
}
// Bytes returns the absolute value of z as a big-endian byte slice.
func (z *Int) Bytes() []byte {
buf := make([]byte, len(z.abs)*_S)
return buf[z.abs.bytes(buf):]
}
// BitLen returns the length of the absolute value of z in bits.
// The bit length of 0 is 0.
func (z *Int) BitLen() int {
return z.abs.bitLen()
}
// Exp sets z = x**y mod m. If m is nil, z = x**y.
// See Knuth, volume 2, section 4.6.3.
func (z *Int) Exp(x, y, m *Int) *Int {
......@@ -567,7 +537,6 @@ func (z *Int) Exp(x, y, m *Int) *Int {
return z
}
// GcdInt sets d to the greatest common divisor of a and b, which must be
// positive numbers.
// If x and y are not nil, GcdInt sets x and y such that d = a*x + b*y.
......@@ -626,7 +595,6 @@ func GcdInt(d, x, y, a, b *Int) {
*d = *A
}
// ProbablyPrime performs n Miller-Rabin tests to check whether z is prime.
// If it returns true, z is prime with probability 1 - 1/4^n.
// If it returns false, z is not prime.
......@@ -634,7 +602,6 @@ func ProbablyPrime(z *Int, n int) bool {
return !z.neg && z.abs.probablyPrime(n)
}
// Rand sets z to a pseudo-random number in [0, n) and returns z.
func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
z.neg = false
......@@ -646,7 +613,6 @@ func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
return z
}
// ModInverse sets z to the multiplicative inverse of g in the group ℤ/pℤ (where
// p is a prime) and returns z.
func (z *Int) ModInverse(g, p *Int) *Int {
......@@ -660,7 +626,6 @@ func (z *Int) ModInverse(g, p *Int) *Int {
return z
}
// Lsh sets z = x << n and returns z.
func (z *Int) Lsh(x *Int, n uint) *Int {
z.abs = z.abs.shl(x.abs, n)
......@@ -668,7 +633,6 @@ func (z *Int) Lsh(x *Int, n uint) *Int {
return z
}
// Rsh sets z = x >> n and returns z.
func (z *Int) Rsh(x *Int, n uint) *Int {
if x.neg {
......@@ -685,7 +649,6 @@ func (z *Int) Rsh(x *Int, n uint) *Int {
return z
}
// Bit returns the value of the i'th bit of z. That is, it
// returns (z>>i)&1. The bit index i must be >= 0.
func (z *Int) Bit(i int) uint {
......@@ -700,7 +663,6 @@ func (z *Int) Bit(i int) uint {
return z.abs.bit(uint(i))
}
// SetBit sets the i'th bit of z to bit and returns z.
// That is, if bit is 1 SetBit sets z = x | (1 << i);
// if bit is 0 it sets z = x &^ (1 << i). If bit is not 0 or 1,
......@@ -721,7 +683,6 @@ func (z *Int) SetBit(x *Int, i int, b uint) *Int {
return z
}
// And sets z = x & y and returns z.
func (z *Int) And(x, y *Int) *Int {
if x.neg == y.neg {
......@@ -752,7 +713,6 @@ func (z *Int) And(x, y *Int) *Int {
return z
}
// AndNot sets z = x &^ y and returns z.
func (z *Int) AndNot(x, y *Int) *Int {
if x.neg == y.neg {
......@@ -786,7 +746,6 @@ func (z *Int) AndNot(x, y *Int) *Int {
return z
}
// Or sets z = x | y and returns z.
func (z *Int) Or(x, y *Int) *Int {
if x.neg == y.neg {
......@@ -817,7 +776,6 @@ func (z *Int) Or(x, y *Int) *Int {
return z
}
// Xor sets z = x ^ y and returns z.
func (z *Int) Xor(x, y *Int) *Int {
if x.neg == y.neg {
......@@ -848,7 +806,6 @@ func (z *Int) Xor(x, y *Int) *Int {
return z
}
// Not sets z = ^x and returns z.
func (z *Int) Not(x *Int) *Int {
if x.neg {
......@@ -864,7 +821,6 @@ func (z *Int) Not(x *Int) *Int {
return z
}
// Gob codec version. Permits backward-compatible changes to the encoding.
const intGobVersion byte = 1
......@@ -880,7 +836,6 @@ func (z *Int) GobEncode() ([]byte, os.Error) {
return buf[i:], nil
}
// GobDecode implements the gob.GobDecoder interface.
func (z *Int) GobDecode(buf []byte) os.Error {
if len(buf) == 0 {
......
This diff is collapsed.
......@@ -24,7 +24,6 @@ import (
"rand"
)
// An unsigned integer x of the form
//
// x = x[n-1]*_B^(n-1) + x[n-2]*_B^(n-2) + ... + x[1]*_B + x[0]
......@@ -45,14 +44,12 @@ var (
natTen = nat{10}
)
func (z nat) clear() {
for i := range z {
z[i] = 0
}
}
func (z nat) norm() nat {
i := len(z)
for i > 0 && z[i-1] == 0 {
......@@ -61,7 +58,6 @@ func (z nat) norm() nat {
return z[0:i]
}
func (z nat) make(n int) nat {
if n <= cap(z) {
return z[0:n] // reuse z
......@@ -72,7 +68,6 @@ func (z nat) make(n int) nat {
return make(nat, n, n+e)
}
func (z nat) setWord(x Word) nat {
if x == 0 {
return z.make(0)
......@@ -82,7 +77,6 @@ func (z nat) setWord(x Word) nat {
return z
}
func (z nat) setUint64(x uint64) nat {
// single-digit values
if w := Word(x); uint64(w) == x {
......@@ -105,14 +99,12 @@ func (z nat) setUint64(x uint64) nat {
return z
}
func (z nat) set(x nat) nat {
z = z.make(len(x))
copy(z, x)
return z
}
func (z nat) add(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -139,7 +131,6 @@ func (z nat) add(x, y nat) nat {
return z.norm()
}
func (z nat) sub(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -168,7 +159,6 @@ func (z nat) sub(x, y nat) nat {
return z.norm()
}
func (x nat) cmp(y nat) (r int) {
m := len(x)
n := len(y)
......@@ -196,7 +186,6 @@ func (x nat) cmp(y nat) (r int) {
return
}
func (z nat) mulAddWW(x nat, y, r Word) nat {
m := len(x)
if m == 0 || y == 0 {
......@@ -210,7 +199,6 @@ func (z nat) mulAddWW(x nat, y, r Word) nat {
return z.norm()
}
// basicMul multiplies x and y and leaves the result in z.
// The (non-normalized) result is placed in z[0 : len(x) + len(y)].
func basicMul(z, x, y nat) {
......@@ -222,7 +210,6 @@ func basicMul(z, x, y nat) {
}
}
// Fast version of z[0:n+n>>1].add(z[0:n+n>>1], x[0:n]) w/o bounds checks.
// Factored out for readability - do not use outside karatsuba.
func karatsubaAdd(z, x nat, n int) {
......@@ -231,7 +218,6 @@ func karatsubaAdd(z, x nat, n int) {
}
}
// Like karatsubaAdd, but does subtract.
func karatsubaSub(z, x nat, n int) {
if c := subVV(z[0:n], z, x); c != 0 {
......@@ -239,7 +225,6 @@ func karatsubaSub(z, x nat, n int) {
}
}
// Operands that are shorter than karatsubaThreshold are multiplied using
// "grade school" multiplication; for longer operands the Karatsuba algorithm
// is used.
......@@ -344,13 +329,11 @@ func karatsuba(z, x, y nat) {
}
}
// alias returns true if x and y share the same base array.
func alias(x, y nat) bool {
return cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]
}
// addAt implements z += x*(1<<(_W*i)); z must be long enough.
// (we don't use nat.add because we need z to stay the same
// slice, and we don't need to normalize z after each addition)
......@@ -365,7 +348,6 @@ func addAt(z, x nat, i int) {
}
}
func max(x, y int) int {
if x > y {
return x
......@@ -373,7 +355,6 @@ func max(x, y int) int {
return y
}
// karatsubaLen computes an approximation to the maximum k <= n such that
// k = p<<i for a number p <= karatsubaThreshold and an i >= 0. Thus, the
// result is the largest number that can be divided repeatedly by 2 before
......@@ -387,7 +368,6 @@ func karatsubaLen(n int) int {
return n << i
}
func (z nat) mul(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -455,7 +435,6 @@ func (z nat) mul(x, y nat) nat {
return z.norm()
}
// mulRange computes the product of all the unsigned integers in the
// range [a, b] inclusively. If a > b (empty range), the result is 1.
func (z nat) mulRange(a, b uint64) nat {
......@@ -474,7 +453,6 @@ func (z nat) mulRange(a, b uint64) nat {
return z.mul(nat(nil).mulRange(a, m), nat(nil).mulRange(m+1, b))
}
// q = (x-r)/y, with 0 <= r < y
func (z nat) divW(x nat, y Word) (q nat, r Word) {
m := len(x)
......@@ -495,7 +473,6 @@ func (z nat) divW(x nat, y Word) (q nat, r Word) {
return
}
func (z nat) div(z2, u, v nat) (q, r nat) {
if len(v) == 0 {
panic("division by zero")
......@@ -523,7 +500,6 @@ func (z nat) div(z2, u, v nat) (q, r nat) {
return
}
// q = (uIn-r)/v, with 0 <= r < y
// Uses z as storage for q, and u as storage for r if possible.
// See Knuth, Volume 2, section 4.3.1, Algorithm D.
......@@ -602,7 +578,6 @@ func (z nat) divLarge(u, uIn, v nat) (q, r nat) {
return q, r
}
// Length of x in bits. x must be normalized.
func (x nat) bitLen() int {
if i := len(x) - 1; i >= 0 {
......@@ -611,7 +586,6 @@ func (x nat) bitLen() int {
return 0
}
// MaxBase is the largest number base accepted for string conversions.
const MaxBase = 'z' - 'a' + 10 + 1 // = hexValue('z') + 1
......@@ -629,7 +603,6 @@ func hexValue(ch int) Word {
return Word(d)
}
// scan sets z to the natural number corresponding to the longest possible prefix
// read from r representing an unsigned integer in a given conversion base.
// It returns z, the actual conversion base used, and an error, if any. In the
......@@ -727,21 +700,18 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z.norm(), int(b), nil
}
// Character sets for string conversion.
const (
lowercaseDigits = "0123456789abcdefghijklmnopqrstuvwxyz"
uppercaseDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
// decimalString returns a decimal representation of x.
// It calls x.string with the charset "0123456789".
func (x nat) decimalString() string {
return x.string(lowercaseDigits[0:10])
}
// string converts x to a string using digits from a charset; a digit with
// value d is represented by charset[d]. The conversion base is determined
// by len(charset), which must be >= 2.
......@@ -863,7 +833,6 @@ func (x nat) string(charset string) string {
return string(s[i:])
}
const deBruijn32 = 0x077CB531
var deBruijn32Lookup = []byte{
......@@ -880,7 +849,6 @@ var deBruijn64Lookup = []byte{
54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6,
}
// trailingZeroBits returns the number of consecutive zero bits on the right
// side of the given Word.
// See Knuth, volume 4, section 7.3.1
......@@ -905,7 +873,6 @@ func trailingZeroBits(x Word) int {
return 0
}
// z = x << s
func (z nat) shl(x nat, s uint) nat {
m := len(x)
......@@ -922,7 +889,6 @@ func (z nat) shl(x nat, s uint) nat {
return z.norm()
}
// z = x >> s
func (z nat) shr(x nat, s uint) nat {
m := len(x)
......@@ -938,7 +904,6 @@ func (z nat) shr(x nat, s uint) nat {
return z.norm()
}
func (z nat) setBit(x nat, i uint, b uint) nat {
j := int(i / _W)
m := Word(1) << (i % _W)
......@@ -966,7 +931,6 @@ func (z nat) setBit(x nat, i uint, b uint) nat {
panic("set bit is not 0 or 1")
}
func (z nat) bit(i uint) uint {
j := int(i / _W)
if j >= len(z) {
......@@ -975,7 +939,6 @@ func (z nat) bit(i uint) uint {
return uint(z[j] >> (i % _W) & 1)
}
func (z nat) and(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -992,7 +955,6 @@ func (z nat) and(x, y nat) nat {
return z.norm()
}
func (z nat) andNot(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -1010,7 +972,6 @@ func (z nat) andNot(x, y nat) nat {
return z.norm()
}
func (z nat) or(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -1030,7 +991,6 @@ func (z nat) or(x, y nat) nat {
return z.norm()
}
func (z nat) xor(x, y nat) nat {
m := len(x)
n := len(y)
......@@ -1050,13 +1010,11 @@ func (z nat) xor(x, y nat) nat {
return z.norm()
}
// greaterThan returns true iff (x1<<_W + x2) > (y1<<_W + y2)
func greaterThan(x1, x2, y1, y2 Word) bool {
return x1 > y1 || x1 == y1 && x2 > y2
}
// modW returns x % d.
func (x nat) modW(d Word) (r Word) {
// TODO(agl): we don't actually need to store the q value.
......@@ -1065,7 +1023,6 @@ func (x nat) modW(d Word) (r Word) {
return divWVW(q, 0, x, d)
}
// powersOfTwoDecompose finds q and k with x = q * 1<<k and q is odd, or q and k are 0.
func (x nat) powersOfTwoDecompose() (q nat, k int) {
if len(x) == 0 {
......@@ -1089,7 +1046,6 @@ func (x nat) powersOfTwoDecompose() (q nat, k int) {
return
}
// random creates a random integer in [0..limit), using the space in z if
// possible. n is the bit length of limit.
func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
......@@ -1120,7 +1076,6 @@ func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
return z.norm()
}
// If m != nil, expNN calculates x**y mod m. Otherwise it calculates x**y. It
// reuses the storage of z if possible.
func (z nat) expNN(x, y, m nat) nat {
......@@ -1189,7 +1144,6 @@ func (z nat) expNN(x, y, m nat) nat {
return z
}
// probablyPrime performs reps Miller-Rabin tests to check whether n is prime.
// If it returns true, n is prime with probability 1 - 1/4^reps.
// If it returns false, n is not prime.
......@@ -1272,7 +1226,6 @@ NextRandom:
return true
}
// bytes writes the value of z into buf using big-endian encoding.
// len(buf) must be >= len(z)*_S. The value of z is encoded in the
// slice buf[i:]. The number i of unused bytes at the beginning of
......@@ -1294,7 +1247,6 @@ func (z nat) bytes(buf []byte) (i int) {
return
}
// setBytes interprets buf as the bytes of a big-endian unsigned
// integer, sets z to that value, and returns z.
func (z nat) setBytes(buf []byte) nat {
......
......@@ -31,7 +31,6 @@ var cmpTests = []struct {
{nat{34986, 41, 105, 1957}, nat{56, 7458, 104, 1957}, 1},
}
func TestCmp(t *testing.T) {
for i, a := range cmpTests {
r := a.x.cmp(a.y)
......@@ -41,13 +40,11 @@ func TestCmp(t *testing.T) {
}
}
type funNN func(z, x, y nat) nat
type argNN struct {
z, x, y nat
}
var sumNN = []argNN{
{},
{nat{1}, nil, nat{1}},
......@@ -57,7 +54,6 @@ var sumNN = []argNN{
{nat{0, 0, 0, 1}, nat{0, 0, _M}, nat{0, 0, 1}},
}
var prodNN = []argNN{
{},
{nil, nil, nil},
......@@ -69,7 +65,6 @@ var prodNN = []argNN{
{nat{4, 11, 20, 30, 20, 11, 4}, nat{1, 2, 3, 4}, nat{4, 3, 2, 1}},
}
func TestSet(t *testing.T) {
for _, a := range sumNN {
z := nat(nil).set(a.z)
......@@ -79,7 +74,6 @@ func TestSet(t *testing.T) {
}
}
func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
z := f(nil, a.x, a.y)
if z.cmp(a.z) != 0 {
......@@ -87,7 +81,6 @@ func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
}
}
func TestFunNN(t *testing.T) {
for _, a := range sumNN {
arg := a
......@@ -112,7 +105,6 @@ func TestFunNN(t *testing.T) {
}
}
var mulRangesN = []struct {
a, b uint64
prod string
......@@ -135,7 +127,6 @@ var mulRangesN = []struct {
},
}
func TestMulRangeN(t *testing.T) {
for i, r := range mulRangesN {
prod := nat(nil).mulRange(r.a, r.b).decimalString()
......@@ -145,7 +136,6 @@ func TestMulRangeN(t *testing.T) {
}
}
var mulArg, mulTmp nat
func init() {
......@@ -156,7 +146,6 @@ func init() {
}
}
func benchmarkMulLoad() {
for j := 1; j <= 10; j++ {
x := mulArg[0 : j*100]
......@@ -164,14 +153,12 @@ func benchmarkMulLoad() {
}
}
func BenchmarkMul(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkMulLoad()
}
}
func toString(x nat, charset string) string {
base := len(charset)
......@@ -201,7 +188,6 @@ func toString(x nat, charset string) string {
return string(s[i:])
}
var strTests = []struct {
x nat // nat value to be converted
c string // conversion charset
......@@ -219,7 +205,6 @@ var strTests = []struct {
{nat{0x309663e6}, uppercaseDigits[0:32], "O9COV6"},
}
func TestString(t *testing.T) {
for _, a := range strTests {
s := a.x.string(a.c)
......@@ -240,7 +225,6 @@ func TestString(t *testing.T) {
}
}
var natScanTests = []struct {
s string // string to be scanned
base int // input base
......@@ -284,7 +268,6 @@ var natScanTests = []struct {
{"0XDEADBEEF", 0, nat{0xdeadbeef}, 16, true, 0},
}
func TestScanBase(t *testing.T) {
for _, a := range natScanTests {
r := strings.NewReader(a.s)
......@@ -315,7 +298,6 @@ func TestScanBase(t *testing.T) {
}
}
var pi = "3" +
"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" +
"32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" +
......@@ -369,7 +351,6 @@ var pi = "3" +
"88281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267" +
"94561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337"
// Test case for BenchmarkScanPi.
func TestScanPi(t *testing.T) {
var x nat
......@@ -382,7 +363,6 @@ func TestScanPi(t *testing.T) {
}
}
func BenchmarkScanPi(b *testing.B) {
for i := 0; i < b.N; i++ {
var x nat
......@@ -390,7 +370,6 @@ func BenchmarkScanPi(b *testing.B) {
}
}
const (
// 314**271
// base 2: 2249 digits
......@@ -417,67 +396,54 @@ const (
longExponent = 27182
)
func BenchmarkScanShort2(b *testing.B) {
ScanHelper(b, 2, shortBase, shortExponent)
}
func BenchmarkScanShort8(b *testing.B) {
ScanHelper(b, 8, shortBase, shortExponent)
}
func BenchmarkScanSort10(b *testing.B) {
ScanHelper(b, 10, shortBase, shortExponent)
}
func BenchmarkScanShort16(b *testing.B) {
ScanHelper(b, 16, shortBase, shortExponent)
}
func BenchmarkScanMedium2(b *testing.B) {
ScanHelper(b, 2, mediumBase, mediumExponent)
}
func BenchmarkScanMedium8(b *testing.B) {
ScanHelper(b, 8, mediumBase, mediumExponent)
}
func BenchmarkScanMedium10(b *testing.B) {
ScanHelper(b, 10, mediumBase, mediumExponent)
}
func BenchmarkScanMedium16(b *testing.B) {
ScanHelper(b, 16, mediumBase, mediumExponent)
}
func BenchmarkScanLong2(b *testing.B) {
ScanHelper(b, 2, longBase, longExponent)
}
func BenchmarkScanLong8(b *testing.B) {
ScanHelper(b, 8, longBase, longExponent)
}
func BenchmarkScanLong10(b *testing.B) {
ScanHelper(b, 10, longBase, longExponent)
}
func BenchmarkScanLong16(b *testing.B) {
ScanHelper(b, 16, longBase, longExponent)
}
func ScanHelper(b *testing.B, base int, xv, yv Word) {
b.StopTimer()
var x, y, z nat
......@@ -497,67 +463,54 @@ func ScanHelper(b *testing.B, base int, xv, yv Word) {
}
}
func BenchmarkStringShort2(b *testing.B) {
StringHelper(b, 2, shortBase, shortExponent)
}
func BenchmarkStringShort8(b *testing.B) {
StringHelper(b, 8, shortBase, shortExponent)
}
func BenchmarkStringShort10(b *testing.B) {
StringHelper(b, 10, shortBase, shortExponent)
}
func BenchmarkStringShort16(b *testing.B) {
StringHelper(b, 16, shortBase, shortExponent)
}
func BenchmarkStringMedium2(b *testing.B) {
StringHelper(b, 2, mediumBase, mediumExponent)
}
func BenchmarkStringMedium8(b *testing.B) {
StringHelper(b, 8, mediumBase, mediumExponent)
}
func BenchmarkStringMedium10(b *testing.B) {
StringHelper(b, 10, mediumBase, mediumExponent)
}
func BenchmarkStringMedium16(b *testing.B) {
StringHelper(b, 16, mediumBase, mediumExponent)
}
func BenchmarkStringLong2(b *testing.B) {
StringHelper(b, 2, longBase, longExponent)
}
func BenchmarkStringLong8(b *testing.B) {
StringHelper(b, 8, longBase, longExponent)
}
func BenchmarkStringLong10(b *testing.B) {
StringHelper(b, 10, longBase, longExponent)
}
func BenchmarkStringLong16(b *testing.B) {
StringHelper(b, 16, longBase, longExponent)
}
func StringHelper(b *testing.B, base int, xv, yv Word) {
b.StopTimer()
var x, y, z nat
......@@ -571,7 +524,6 @@ func StringHelper(b *testing.B, base int, xv, yv Word) {
}
}
func TestLeadingZeros(t *testing.T) {
var x Word = _B >> 1
for i := 0; i <= _W; i++ {
......@@ -582,14 +534,12 @@ func TestLeadingZeros(t *testing.T) {
}
}
type shiftTest struct {
in nat
shift uint
out nat
}
var leftShiftTests = []shiftTest{
{nil, 0, nil},
{nil, 1, nil},
......@@ -599,7 +549,6 @@ var leftShiftTests = []shiftTest{
{nat{1 << (_W - 1), 0}, 1, nat{0, 1}},
}
func TestShiftLeft(t *testing.T) {
for i, test := range leftShiftTests {
var z nat
......@@ -613,7 +562,6 @@ func TestShiftLeft(t *testing.T) {
}
}
var rightShiftTests = []shiftTest{
{nil, 0, nil},
{nil, 1, nil},
......@@ -624,7 +572,6 @@ var rightShiftTests = []shiftTest{
{nat{2, 1, 1}, 1, nat{1<<(_W-1) + 1, 1 << (_W - 1)}},
}
func TestShiftRight(t *testing.T) {
for i, test := range rightShiftTests {
var z nat
......@@ -638,24 +585,20 @@ func TestShiftRight(t *testing.T) {
}
}
type modWTest struct {
in string
dividend string
out string
}
var modWTests32 = []modWTest{
{"23492635982634928349238759823742", "252341", "220170"},
}
var modWTests64 = []modWTest{
{"6527895462947293856291561095690465243862946", "524326975699234", "375066989628668"},
}
func runModWTests(t *testing.T, tests []modWTest) {
for i, test := range tests {
in, _ := new(Int).SetString(test.in, 10)
......@@ -669,7 +612,6 @@ func runModWTests(t *testing.T, tests []modWTest) {
}
}
func TestModW(t *testing.T) {
if _W >= 32 {
runModWTests(t, modWTests32)
......@@ -679,7 +621,6 @@ func TestModW(t *testing.T) {
}
}
func TestTrailingZeroBits(t *testing.T) {
var x Word
x--
......@@ -708,7 +649,6 @@ var expNNTests = []struct {
},
}
func TestExpNN(t *testing.T) {
for i, test := range expNNTests {
x, _, _ := nat(nil).scan(strings.NewReader(test.x), 0)
......
......@@ -20,13 +20,11 @@ type Rat struct {
b nat
}
// NewRat creates a new Rat with numerator a and denominator b.
func NewRat(a, b int64) *Rat {
return new(Rat).SetFrac64(a, b)
}
// SetFrac sets z to a/b and returns z.
func (z *Rat) SetFrac(a, b *Int) *Rat {
z.a.Set(a)
......@@ -35,7 +33,6 @@ func (z *Rat) SetFrac(a, b *Int) *Rat {
return z.norm()
}
// SetFrac64 sets z to a/b and returns z.
func (z *Rat) SetFrac64(a, b int64) *Rat {
z.a.SetInt64(a)
......@@ -47,7 +44,6 @@ func (z *Rat) SetFrac64(a, b int64) *Rat {
return z.norm()
}
// SetInt sets z to x (by making a copy of x) and returns z.
func (z *Rat) SetInt(x *Int) *Rat {
z.a.Set(x)
......@@ -55,7 +51,6 @@ func (z *Rat) SetInt(x *Int) *Rat {
return z
}
// SetInt64 sets z to x and returns z.
func (z *Rat) SetInt64(x int64) *Rat {
z.a.SetInt64(x)
......@@ -63,7 +58,6 @@ func (z *Rat) SetInt64(x int64) *Rat {
return z
}
// Sign returns:
//
// -1 if x < 0
......@@ -74,13 +68,11 @@ func (x *Rat) Sign() int {
return x.a.Sign()
}
// IsInt returns true if the denominator of x is 1.
func (x *Rat) IsInt() bool {
return len(x.b) == 1 && x.b[0] == 1
}
// Num returns the numerator of z; it may be <= 0.
// The result is a reference to z's numerator; it
// may change if a new value is assigned to z.
......@@ -88,7 +80,6 @@ func (z *Rat) Num() *Int {
return &z.a
}
// Denom returns the denominator of z; it is always > 0.
// The result is a reference to z's denominator; it
// may change if a new value is assigned to z.
......@@ -96,7 +87,6 @@ func (z *Rat) Denom() *Int {
return &Int{false, z.b}
}
func gcd(x, y nat) nat {
// Euclidean algorithm.
var a, b nat
......@@ -111,7 +101,6 @@ func gcd(x, y nat) nat {
return a
}
func (z *Rat) norm() *Rat {
f := gcd(z.a.abs, z.b)
if len(z.a.abs) == 0 {
......@@ -127,7 +116,6 @@ func (z *Rat) norm() *Rat {
return z
}
func mulNat(x *Int, y nat) *Int {
var z Int
z.abs = z.abs.mul(x.abs, y)
......@@ -135,7 +123,6 @@ func mulNat(x *Int, y nat) *Int {
return &z
}
// Cmp compares x and y and returns:
//
// -1 if x < y
......@@ -146,7 +133,6 @@ func (x *Rat) Cmp(y *Rat) (r int) {
return mulNat(&x.a, y.b).Cmp(mulNat(&y.a, x.b))
}
// Abs sets z to |x| (the absolute value of x) and returns z.
func (z *Rat) Abs(x *Rat) *Rat {
z.a.Abs(&x.a)
......@@ -154,7 +140,6 @@ func (z *Rat) Abs(x *Rat) *Rat {
return z
}
// Add sets z to the sum x+y and returns z.
func (z *Rat) Add(x, y *Rat) *Rat {
a1 := mulNat(&x.a, y.b)
......@@ -164,7 +149,6 @@ func (z *Rat) Add(x, y *Rat) *Rat {
return z.norm()
}
// Sub sets z to the difference x-y and returns z.
func (z *Rat) Sub(x, y *Rat) *Rat {
a1 := mulNat(&x.a, y.b)
......@@ -174,7 +158,6 @@ func (z *Rat) Sub(x, y *Rat) *Rat {
return z.norm()
}
// Mul sets z to the product x*y and returns z.
func (z *Rat) Mul(x, y *Rat) *Rat {
z.a.Mul(&x.a, &y.a)
......@@ -182,7 +165,6 @@ func (z *Rat) Mul(x, y *Rat) *Rat {
return z.norm()
}
// Quo sets z to the quotient x/y and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
func (z *Rat) Quo(x, y *Rat) *Rat {
......@@ -197,7 +179,6 @@ func (z *Rat) Quo(x, y *Rat) *Rat {
return z.norm()
}
// Neg sets z to -x (by making a copy of x if necessary) and returns z.
func (z *Rat) Neg(x *Rat) *Rat {
z.a.Neg(&x.a)
......@@ -205,7 +186,6 @@ func (z *Rat) Neg(x *Rat) *Rat {
return z
}
// Set sets z to x (by making a copy of x if necessary) and returns z.
func (z *Rat) Set(x *Rat) *Rat {
z.a.Set(&x.a)
......@@ -213,12 +193,10 @@ func (z *Rat) Set(x *Rat) *Rat {
return z
}
func ratTok(ch int) bool {
return strings.IndexRune("+-/0123456789.eE", ch) >= 0
}
// Scan is a support routine for fmt.Scanner. It accepts the formats
// 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
func (z *Rat) Scan(s fmt.ScanState, ch int) os.Error {
......@@ -235,7 +213,6 @@ func (z *Rat) Scan(s fmt.ScanState, ch int) os.Error {
return nil
}
// SetString sets z to the value of s and returns z and a boolean indicating
// success. s can be given as a fraction "a/b" or as a floating-point number
// optionally followed by an exponent. If the operation failed, the value of z
......@@ -294,13 +271,11 @@ func (z *Rat) SetString(s string) (*Rat, bool) {
return z, true
}
// String returns a string representation of z in the form "a/b" (even if b == 1).
func (z *Rat) String() string {
return z.a.String() + "/" + z.b.decimalString()
}
// RatString returns a string representation of z in the form "a/b" if b != 1,
// and in the form "a" if b == 1.
func (z *Rat) RatString() string {
......@@ -310,7 +285,6 @@ func (z *Rat) RatString() string {
return z.String()
}
// FloatString returns a string representation of z in decimal form with prec
// digits of precision after the decimal point and the last digit rounded.
func (z *Rat) FloatString(prec int) string {
......@@ -356,7 +330,6 @@ func (z *Rat) FloatString(prec int) string {
return s
}
// Gob codec version. Permits backward-compatible changes to the encoding.
const ratGobVersion byte = 1
......@@ -380,7 +353,6 @@ func (z *Rat) GobEncode() ([]byte, os.Error) {
return buf[j:], nil
}
// GobDecode implements the gob.GobDecoder interface.
func (z *Rat) GobDecode(buf []byte) os.Error {
if len(buf) == 0 {
......
......@@ -11,7 +11,6 @@ import (
"testing"
)
var setStringTests = []struct {
in, out string
ok bool
......@@ -57,7 +56,6 @@ func TestRatSetString(t *testing.T) {
}
}
func TestRatScan(t *testing.T) {
var buf bytes.Buffer
for i, test := range setStringTests {
......@@ -80,7 +78,6 @@ func TestRatScan(t *testing.T) {
}
}
var floatStringTests = []struct {
in string
prec int
......@@ -113,7 +110,6 @@ func TestFloatString(t *testing.T) {
}
}
func TestRatSign(t *testing.T) {
zero := NewRat(0, 1)
for _, a := range setStringTests {
......@@ -127,7 +123,6 @@ func TestRatSign(t *testing.T) {
}
}
var ratCmpTests = []struct {
rat1, rat2 string
out int
......@@ -155,7 +150,6 @@ func TestRatCmp(t *testing.T) {
}
}
func TestIsInt(t *testing.T) {
one := NewInt(1)
for _, a := range setStringTests {
......@@ -169,7 +163,6 @@ func TestIsInt(t *testing.T) {
}
}
func TestRatAbs(t *testing.T) {
zero := NewRat(0, 1)
for _, a := range setStringTests {
......@@ -187,7 +180,6 @@ func TestRatAbs(t *testing.T) {
}
}
type ratBinFun func(z, x, y *Rat) *Rat
type ratBinArg struct {
x, y, z string
......@@ -204,7 +196,6 @@ func testRatBin(t *testing.T, i int, name string, f ratBinFun, a ratBinArg) {
}
}
var ratBinTests = []struct {
x, y string
sum, prod string
......@@ -261,7 +252,6 @@ func TestRatBin(t *testing.T) {
}
}
func TestIssue820(t *testing.T) {
x := NewRat(3, 1)
y := NewRat(2, 1)
......@@ -287,7 +277,6 @@ func TestIssue820(t *testing.T) {
}
}
var setFrac64Tests = []struct {
a, b int64
out string
......@@ -310,7 +299,6 @@ func TestRatSetFrac64Rat(t *testing.T) {
}
}
func TestRatGobEncoding(t *testing.T) {
var medium bytes.Buffer
enc := gob.NewEncoder(&medium)
......
......@@ -15,7 +15,6 @@ import (
"utf8"
)
const (
defaultBufSize = 4096
)
......@@ -42,7 +41,6 @@ func (b BufSizeError) String() string {
return "bufio: bad buffer size " + strconv.Itoa(int(b))
}
// Buffered input.
// Reader implements buffering for an io.Reader object.
......@@ -375,7 +373,6 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
return string(bytes), e
}
// buffered output
// Writer implements buffering for an io.Writer object.
......
......@@ -76,7 +76,6 @@ func TestReaderSimple(t *testing.T) {
}
}
type readMaker struct {
name string
fn func(io.Reader) io.Reader
......
......@@ -12,7 +12,6 @@ import (
"utf8"
)
const N = 10000 // make this bigger for a larger (and slower) test
var data string // test data for write tests
var bytes []byte // test data; same as data but as a slice.
......@@ -47,7 +46,6 @@ func check(t *testing.T, testname string, buf *Buffer, s string) {
}
}
// Fill buf through n writes of string fus.
// The initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string.
......@@ -67,7 +65,6 @@ func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus
return s
}
// Fill buf through n writes of byte slice fub.
// The initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string.
......@@ -87,19 +84,16 @@ func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub
return s
}
func TestNewBuffer(t *testing.T) {
buf := NewBuffer(bytes)
check(t, "NewBuffer", buf, data)
}
func TestNewBufferString(t *testing.T) {
buf := NewBufferString(data)
check(t, "NewBufferString", buf, data)
}
// Empty buf through repeated reads into fub.
// The initial contents of buf corresponds to the string s.
func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
......@@ -120,7 +114,6 @@ func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
check(t, testname+" (empty 4)", buf, "")
}
func TestBasicOperations(t *testing.T) {
var buf Buffer
......@@ -175,7 +168,6 @@ func TestBasicOperations(t *testing.T) {
}
}
func TestLargeStringWrites(t *testing.T) {
var buf Buffer
limit := 30
......@@ -189,7 +181,6 @@ func TestLargeStringWrites(t *testing.T) {
check(t, "TestLargeStringWrites (3)", &buf, "")
}
func TestLargeByteWrites(t *testing.T) {
var buf Buffer
limit := 30
......@@ -203,7 +194,6 @@ func TestLargeByteWrites(t *testing.T) {
check(t, "TestLargeByteWrites (3)", &buf, "")
}
func TestLargeStringReads(t *testing.T) {
var buf Buffer
for i := 3; i < 30; i += 3 {
......@@ -213,7 +203,6 @@ func TestLargeStringReads(t *testing.T) {
check(t, "TestLargeStringReads (3)", &buf, "")
}
func TestLargeByteReads(t *testing.T) {
var buf Buffer
for i := 3; i < 30; i += 3 {
......@@ -223,7 +212,6 @@ func TestLargeByteReads(t *testing.T) {
check(t, "TestLargeByteReads (3)", &buf, "")
}
func TestMixedReadsAndWrites(t *testing.T) {
var buf Buffer
s := ""
......@@ -243,7 +231,6 @@ func TestMixedReadsAndWrites(t *testing.T) {
empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
}
func TestNil(t *testing.T) {
var b *Buffer
if b.String() != "<nil>" {
......@@ -251,7 +238,6 @@ func TestNil(t *testing.T) {
}
}
func TestReadFrom(t *testing.T) {
var buf Buffer
for i := 3; i < 30; i += 3 {
......@@ -262,7 +248,6 @@ func TestReadFrom(t *testing.T) {
}
}
func TestWriteTo(t *testing.T) {
var buf Buffer
for i := 3; i < 30; i += 3 {
......@@ -273,7 +258,6 @@ func TestWriteTo(t *testing.T) {
}
}
func TestRuneIO(t *testing.T) {
const NRune = 1000
// Built a test array while we write the data
......@@ -323,7 +307,6 @@ func TestRuneIO(t *testing.T) {
}
}
func TestNext(t *testing.T) {
b := []byte{0, 1, 2, 3, 4}
tmp := make([]byte, 5)
......
......@@ -398,7 +398,6 @@ func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte {
return Map(func(r int) int { return _case.ToTitle(r) }, s)
}
// isSeparator reports whether the rune could mark a word boundary.
// TODO: update when package unicode captures more of the properties.
func isSeparator(rune int) bool {
......
......@@ -329,7 +329,6 @@ func TestExplode(t *testing.T) {
}
}
type SplitTest struct {
s string
sep string
......@@ -662,7 +661,6 @@ func TestRunes(t *testing.T) {
}
}
type TrimTest struct {
f func([]byte, string) []byte
in, cutset, out string
......
......@@ -225,7 +225,6 @@ func testSync(t *testing.T, level int, input []byte, name string) {
}
}
func testToFromWithLevel(t *testing.T, level int, input []byte, name string) os.Error {
buffer := bytes.NewBuffer(nil)
w := NewWriter(buffer, level)
......
......@@ -21,7 +21,6 @@ type Interface interface {
Pop() interface{}
}
// A heap must be initialized before any of the heap operations
// can be used. Init is idempotent with respect to the heap invariants
// and may be called whenever the heap invariants may have been invalidated.
......@@ -35,7 +34,6 @@ func Init(h Interface) {
}
}
// Push pushes the element x onto the heap. The complexity is
// O(log(n)) where n = h.Len().
//
......@@ -44,7 +42,6 @@ func Push(h Interface, x interface{}) {
up(h, h.Len()-1)
}
// Pop removes the minimum element (according to Less) from the heap
// and returns it. The complexity is O(log(n)) where n = h.Len().
// Same as Remove(h, 0).
......@@ -56,7 +53,6 @@ func Pop(h Interface) interface{} {
return h.Pop()
}
// Remove removes the element at index i from the heap.
// The complexity is O(log(n)) where n = h.Len().
//
......@@ -70,7 +66,6 @@ func Remove(h Interface, i int) interface{} {
return h.Pop()
}
func up(h Interface, j int) {
for {
i := (j - 1) / 2 // parent
......@@ -82,7 +77,6 @@ func up(h Interface, j int) {
}
}
func down(h Interface, i, n int) {
for {
j1 := 2*i + 1
......
......@@ -10,17 +10,14 @@ import (
. "container/heap"
)
type myHeap struct {
// A vector.Vector implements sort.Interface except for Less,
// and it implements Push and Pop as required for heap.Interface.
vector.Vector
}
func (h *myHeap) Less(i, j int) bool { return h.At(i).(int) < h.At(j).(int) }
func (h *myHeap) verify(t *testing.T, i int) {
n := h.Len()
j1 := 2*i + 1
......@@ -41,7 +38,6 @@ func (h *myHeap) verify(t *testing.T, i int) {
}
}
func TestInit0(t *testing.T) {
h := new(myHeap)
for i := 20; i > 0; i-- {
......@@ -59,7 +55,6 @@ func TestInit0(t *testing.T) {
}
}
func TestInit1(t *testing.T) {
h := new(myHeap)
for i := 20; i > 0; i-- {
......@@ -77,7 +72,6 @@ func TestInit1(t *testing.T) {
}
}
func Test(t *testing.T) {
h := new(myHeap)
h.verify(t, 0)
......@@ -105,7 +99,6 @@ func Test(t *testing.T) {
}
}
func TestRemove0(t *testing.T) {
h := new(myHeap)
for i := 0; i < 10; i++ {
......@@ -123,7 +116,6 @@ func TestRemove0(t *testing.T) {
}
}
func TestRemove1(t *testing.T) {
h := new(myHeap)
for i := 0; i < 10; i++ {
......@@ -140,7 +132,6 @@ func TestRemove1(t *testing.T) {
}
}
func TestRemove2(t *testing.T) {
N := 10
......
......@@ -16,14 +16,12 @@ type Ring struct {
Value interface{} // for use by client; untouched by this library
}
func (r *Ring) init() *Ring {
r.next = r
r.prev = r
return r
}
// Next returns the next ring element. r must not be empty.
func (r *Ring) Next() *Ring {
if r.next == nil {
......@@ -32,7 +30,6 @@ func (r *Ring) Next() *Ring {
return r.next
}
// Prev returns the previous ring element. r must not be empty.
func (r *Ring) Prev() *Ring {
if r.next == nil {
......@@ -41,7 +38,6 @@ func (r *Ring) Prev() *Ring {
return r.prev
}
// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)
// in the ring and returns that ring element. r must not be empty.
//
......@@ -62,7 +58,6 @@ func (r *Ring) Move(n int) *Ring {
return r
}
// New creates a ring of n elements.
func New(n int) *Ring {
if n <= 0 {
......@@ -79,7 +74,6 @@ func New(n int) *Ring {
return r
}
// Link connects ring r with with ring s such that r.Next()
// becomes s and returns the original value for r.Next().
// r must not be empty.
......@@ -110,7 +104,6 @@ func (r *Ring) Link(s *Ring) *Ring {
return n
}
// Unlink removes n % r.Len() elements from the ring r, starting
// at r.Next(). If n % r.Len() == 0, r remains unchanged.
// The result is the removed subring. r must not be empty.
......@@ -122,7 +115,6 @@ func (r *Ring) Unlink(n int) *Ring {
return r.Link(r.Move(n + 1))
}
// Len computes the number of elements in ring r.
// It executes in time proportional to the number of elements.
//
......@@ -137,7 +129,6 @@ func (r *Ring) Len() int {
return n
}
// Do calls function f on each element of the ring, in forward order.
// The behavior of Do is undefined if f changes *r.
func (r *Ring) Do(f func(interface{})) {
......
......@@ -9,7 +9,6 @@ import (
"testing"
)
// For debugging - keep around.
func dump(r *Ring) {
if r == nil {
......@@ -24,7 +23,6 @@ func dump(r *Ring) {
fmt.Println()
}
func verify(t *testing.T, r *Ring, N int, sum int) {
// Len
n := r.Len()
......@@ -96,7 +94,6 @@ func verify(t *testing.T, r *Ring, N int, sum int) {
}
}
func TestCornerCases(t *testing.T) {
var (
r0 *Ring
......@@ -118,7 +115,6 @@ func TestCornerCases(t *testing.T) {
verify(t, &r1, 1, 0)
}
func makeN(n int) *Ring {
r := New(n)
for i := 1; i <= n; i++ {
......@@ -130,7 +126,6 @@ func makeN(n int) *Ring {
func sumN(n int) int { return (n*n + n) / 2 }
func TestNew(t *testing.T) {
for i := 0; i < 10; i++ {
r := New(i)
......@@ -142,7 +137,6 @@ func TestNew(t *testing.T) {
}
}
func TestLink1(t *testing.T) {
r1a := makeN(1)
var r1b Ring
......@@ -163,7 +157,6 @@ func TestLink1(t *testing.T) {
verify(t, r2b, 1, 0)
}
func TestLink2(t *testing.T) {
var r0 *Ring
r1a := &Ring{Value: 42}
......@@ -183,7 +176,6 @@ func TestLink2(t *testing.T) {
verify(t, r10, 12, sumN(10)+42+77)
}
func TestLink3(t *testing.T) {
var r Ring
n := 1
......@@ -193,7 +185,6 @@ func TestLink3(t *testing.T) {
}
}
func TestUnlink(t *testing.T) {
r10 := makeN(10)
s10 := r10.Move(6)
......@@ -215,7 +206,6 @@ func TestUnlink(t *testing.T) {
verify(t, r10, 9, sum10-2)
}
func TestLinkUnlink(t *testing.T) {
for i := 1; i < 4; i++ {
ri := New(i)
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -33,7 +33,6 @@ const (
ocspUnauthorized = 5
)
type certID struct {
HashAlgorithm pkix.AlgorithmIdentifier
NameHash []byte
......
......@@ -30,7 +30,6 @@ func (r recordingHash) Size() int {
panic("shouldn't be called")
}
func testCanonicalText(t *testing.T, input, expected string) {
r := recordingHash{bytes.NewBuffer(nil)}
c := NewCanonicalTextHash(r)
......
......@@ -21,7 +21,6 @@ func bigFromBase10(s string) *big.Int {
return b
}
var encryptedKeyPub = rsa.PublicKey{
E: 65537,
N: bigFromBase10("115804063926007623305902631768113868327816898845124614648849934718568541074358183759250136204762053879858102352159854352727097033322663029387610959884180306668628526686121021235757016368038585212410610742029286439607686208110250133174279811431933746643015923132833417396844716207301518956640020862630546868823"),
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment