go-villa: github.com/daviddengcn/go-villa Index | Examples | Files | Directories

package villa

import "github.com/daviddengcn/go-villa"

Package villa contains some helper data structures: priority queue(interface{} and int as elements), slice wrapper(interface{}, int, float and complex as elements), Sort, binary search and merge with customized comparator.

By using Slice, IntSlice, FloatSlice or ComplexSlice types, some mutable list can be easily maintained.

The priority queue related structs provides a ready to use interface instead of the standard interface.

Index

Examples

Package Files

byteslice.go cmp.go complexslice.go floatslice.go fmt.go intmat.go intpq.go intslice.go log.go map.go misc.go path.go pq.go slice.go sort.go strset.go strslice.go sync.go villa.go

Variables

var (
    // StrValueCompare compares the input strings a and b, returns -1 if a < b,
    // 1 if a > b, and 0 otherwise.
    //
    // This is a natural StrCmpFunc.
    StrValueCompare = StrCmpFunc(func(a, b string) int {
        if a < b {
            return -1
        } else if a > b {
            return 1
        }

        return 0
    })

    // IntValueCompare compares the input int values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
    // This is a natural IntCmpFunc.
    IntValueCompare = IntCmpFunc(func(a, b int) int {
        if a < b {
            return -1
        } else if a > b {
            return 1
        }

        return 0
    })

    // FloatValueCompare compares the input float64 values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
    // This is a natural FloatCmpFunc.
    FloatValueCompare = FloatCmpFunc(func(a, b float64) int {
        if a < b {
            return -1
        } else if a > b {
            return 1
        }

        return 0
    })
)
var ErrInvalidRune = errors.New("villa.ByteSlice: invalid rune")
var N [int(^uint32(0) >> 1)]struct{}

N is a very long slice of elements with size of zero-bytes. It is useful for generating a serial of numbers in a for-range clause. e.g.

for i := range villa.N[:200] { ... }

The above i in the above for clause will range from 0 to 200(exclusive).

func DeepestNested Uses

func DeepestNested(err error) error

DeepestNested returns the deepest nested error. If err is not *NestedError, it is directly returned.

func Error Uses

func Error(v ...interface{}) error

Error is similar to fmt.Error with caller's position in the source

func ErrorN Uses

func ErrorN(n int, v ...interface{}) error

ErrorN is similar to villa.Error with a specified line-pos depth. when n == 1, it is equivalent to villa.Error.

func Errorf Uses

func Errorf(format string, a ...interface{}) error

Errorf is similar to fmt.Errorf with caller's position in the source

func ErrorfN Uses

func ErrorfN(n int, format string, a ...interface{}) error

ErrorfN is similar to villa.Errorf with a specified line-pos depth. when n == 1, it is equivalent to villa.Errorf.

func Fatal Uses

func Fatal(v ...interface{})

Fatalf is similar to log.Fatal with caller's position in the source

func Fatalf Uses

func Fatalf(format string, v ...interface{})

Fatalf is similar to log.Fatalf with caller's position in the source

func LinePos Uses

func LinePos(skip int) string

LinePos returns a string of format "filename:pos" of a position in the source. For skip == 0, it returns the position of the caller (the line call LinePos).

func MapKeyAsStrings Uses

func MapKeyAsStrings(m interface{}) []string

MapKeyAsStrings returns the keys of a map as a string slice. if m is not a map, it panics. Keys are extracted by reflection which doesn't guarentee the efficiency. So this function is mainly used for debugging or error message showing.

func Paths Uses

func Paths(strs ...string) (paths []Path)

Paths returns an array of Path's given a list of strings.

func SortF Uses

func SortF(Len int, Less func(int, int) bool, Swap func(int, int))

Deprecated. Use sortp.SortF in "github.com/golangplus/sort" instead.

type AtomicBox Uses

type AtomicBox struct {
    sync.RWMutex
    // contains filtered or unexported fields
}

AtomicBox is a place atomically storing an object(typed interface{})

func (*AtomicBox) Get Uses

func (b *AtomicBox) Get() interface{}

Get fetches the object from the box atomically

func (*AtomicBox) Set Uses

func (b *AtomicBox) Set(val interface{})

Set stores the object into the box atomically

type ByteSlice Uses

type ByteSlice []byte

Deprecated. Use "github.com/golangplus/bytes".ByteSlice instead.

ByteSlice is a wrapper type for []byte. Its pointer form, *ByteSlice, satisfies io.Reader, io.Writer, io.ByteReader, io.ByteWriter, io.Closer, io.ReaderFrom, io.WriterTo and io.RuneReader interfaces.

When reading from a constant bytes and no need for seeking, *ByteSlice is a better choice then bytes.Buffer, since it needs less extra resource. You can use NewPByteSlice to create a *ByteSlice without declaring a variable.

func NewPByteSlice Uses

func NewPByteSlice(bytes []byte) (s *ByteSlice)

NewPByteSlice returns a *ByteSlice.

func (ByteSlice) Close Uses

func (s ByteSlice) Close() error

Close implements io.Closer interface. It does nothing.

func (*ByteSlice) Read Uses

func (s *ByteSlice) Read(p []byte) (n int, err error)

Read implements io.Reader interface. After some bytes are read, the slice shrinks.

func (*ByteSlice) ReadByte Uses

func (s *ByteSlice) ReadByte() (c byte, err error)

ReadByte implements io.ByteReader interface

func (*ByteSlice) ReadFrom Uses

func (s *ByteSlice) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom interface.

func (*ByteSlice) ReadRune Uses

func (s *ByteSlice) ReadRune() (r rune, size int, err error)

ReadRune implements io.RuneReader interface.

func (*ByteSlice) Skip Uses

func (s *ByteSlice) Skip(n int64) (int64, error)

func (*ByteSlice) Write Uses

func (s *ByteSlice) Write(p []byte) (n int, err error)

Write implements io.Writer interface Bytes are appended to the tail of the slice.

func (*ByteSlice) WriteByte Uses

func (s *ByteSlice) WriteByte(c byte) error

WriteByte implements io.ByteWriter interface

func (*ByteSlice) WriteItoa Uses

func (s *ByteSlice) WriteItoa(i int64, base int) (size int, err error)

WriteItoa converts i into text of the specified base and write to s.

func (*ByteSlice) WriteRune Uses

func (s *ByteSlice) WriteRune(r rune) (size int, err error)

WriteRune writes a single Unicode code point, returning the number of bytes written and any error.

func (*ByteSlice) WriteString Uses

func (s *ByteSlice) WriteString(str string) (size int, err error)

WriteString appends the contents of str to the slice, growing the slice as needed. The return value n is the length of str; err is always nil.

func (ByteSlice) WriteTo Uses

func (s ByteSlice) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo interface.

type CmpFunc Uses

type CmpFunc func(a, b interface{}) int

CmpFunc is a function comparing two elements. The function returns a positive value if a > b, a negative value if a < b, and 0 otherwise.

Sort, BinarySearch and Merge methods are defined. Usage:

s := []interface{}{...}
cmp := CmpFunc(func (a, b interface{}) int {
        if a.(int) < b.(int) {
            return -1
        } else if a.(int) > b.(int) {
            return 1
        } // else if
        return 0
})
cmp.Sort(s)
p, found := cmp.BinarySearch(s, e)

l := []interface{}{...}
cmp.Sort(l)
t := cmp.Merge(s, l)

func (CmpFunc) BinarySearch Uses

func (cmp CmpFunc) BinarySearch(s []interface{}, e interface{}) (pos int, found bool)

BinarySearch searchs a specified element e in a *sorted* list with binary search algorithm. If the list values are not sorted, the return values are undefined.

If the element is found in the list, found equals true and pos is the index of the found element in the list. Otherwise found returns false and pos is the position where e is going to be inserted(and the resulting list is still in order)

func (CmpFunc) Merge Uses

func (cmp CmpFunc) Merge(a, b []interface{}) []interface{}

Merge merges the current *sorted* elements with another *sorted* slice of elements. All elements should be sorted by the same comparator.

func (CmpFunc) Sort Uses

func (cmp CmpFunc) Sort(s []interface{})

Sort calls the build-in sort.Sort to sort data in the slice.

type ComplexCmpFunc Uses

type ComplexCmpFunc func(a, b complex128) int

ComplexCmpFunc is a function comparing two complex128 elements. The function returns a positive value if a > b, a negative value if a < b, and 0 otherwise.

Sort, BinarySearch and Merge methods are defined. Usage:

s := []complex128{}{...}
cmp := CmpFunc(func (a, b complex128) int {
    if cmplx.Abs(a) < cmplx.Abs(b) {
        return -1
    } else if cmplx.Abs(a) > cmplx.Abs(b) {
        return 1
    } // else if
    return 0
})
cmp.Sort(s)
p, found := cmp.BinarySearch(s, e)

l := []complex128{}{...}
cmp.Sort(l)
t := cmp.Merge(s, l)

func (ComplexCmpFunc) BinarySearch Uses

func (cmp ComplexCmpFunc) BinarySearch(s []complex128, e complex128) (pos int, found bool)

BinarySearch searchs a specified element e in a *sorted* list with binary search algorithm. If the list values are not sorted, the return values are undefined. If the element is found in the list, found equals true and pos is the index of the found element in the list. Otherwise found returns false and pos is the position where e is going to be inserted(and the resulting list is still in order)

func (ComplexCmpFunc) Merge Uses

func (cmp ComplexCmpFunc) Merge(a, b []complex128) []complex128

func (ComplexCmpFunc) Sort Uses

func (cmp ComplexCmpFunc) Sort(s []complex128)

Sort calls the build-in sort.Sort to sort data in the slice.

type ComplexSlice Uses

type ComplexSlice []complex128

ComplexSlice is wrapper to a slice of complex128.

See examples of IntSlice for reference.

func (*ComplexSlice) Add Uses

func (s *ComplexSlice) Add(e ...complex128) *ComplexSlice

Add appends the specified element to the end of this slice.

func (*ComplexSlice) Clear Uses

func (s *ComplexSlice) Clear()

Clear removes all of the elements from this slice.

func (ComplexSlice) Equals Uses

func (s ComplexSlice) Equals(t []complex128, epsilon float64) bool

Equals returns true if a given slice has the same contents (with maximum error of epsilon) with the slice

func (ComplexSlice) Fill Uses

func (s ComplexSlice) Fill(from, to int, vl complex128)

Fill sets the elements between from, inclusive, and to, exclusive, to a speicified value.

func (*ComplexSlice) Insert Uses

func (s *ComplexSlice) Insert(index int, e ...complex128)

Insert inserts the specified element at the specified position. NOTE: the insertion algorithm is much better than the slice-trick in go community wiki

func (*ComplexSlice) Pop Uses

func (s *ComplexSlice) Pop() complex128

Pop removes and returns the last element in the slice

func (*ComplexSlice) Remove Uses

func (s *ComplexSlice) Remove(index int) complex128

Remove removes the element at the specified position in this slice.

func (*ComplexSlice) RemoveRange Uses

func (s *ComplexSlice) RemoveRange(from, to int)

RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice.

func (ComplexSlice) Swap Uses

func (s ComplexSlice) Swap(i, j int)

The Swap method in sort.Interface.

type Empty Uses

type Empty struct{}

An variable of zero-size bytes

type FloatCmpFunc Uses

type FloatCmpFunc func(a, b float64) int

FloatCmpFunc is a function comparing two float elements. The function returns a positive value if a > b, a negative value if a < b, and 0 otherwise.

Sort, BinarySearch and Merge methods are defined. Usage:

s := []float64{}{...}
cmp := CmpFunc(func (a, b float64) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if
    return 0
})
cmp.Sort(s)
p, found := cmp.BinarySearch(s, e)

l := []float64{}{...}
cmp.Sort(l)
t := cmp.Merge(s, l)

func (FloatCmpFunc) BinarySearch Uses

func (cmp FloatCmpFunc) BinarySearch(s []float64, e float64) (pos int, found bool)

BinarySearch searchs a specified element e in a *sorted* list with binary search algorithm. If the list values are not sorted, the return values are undefined. If the element is found in the list, found equals true and pos is the index of the found element in the list. Otherwise found returns false and pos is the position where e is going to be inserted(and the resulting list is still in order)

func (FloatCmpFunc) Merge Uses

func (cmp FloatCmpFunc) Merge(a, b []float64) []float64

Merge merges the current *sorted* elements with another *sorted* slice of elements. All elements should be sorted by the same comparator.

func (FloatCmpFunc) Sort Uses

func (cmp FloatCmpFunc) Sort(s []float64)

Sort calls the build-in sort.Sort to sort data in the slice.

type FloatSlice Uses

type FloatSlice []float64

FloatSlice is wrapper to a slice of float64.

See examples of IntSlice for reference.

func (*FloatSlice) Add Uses

func (s *FloatSlice) Add(e ...float64) *FloatSlice

Add appends the specified element to the end of this slice.

func (*FloatSlice) Clear Uses

func (s *FloatSlice) Clear()

Clear removes all of the elements from this slice.

func (FloatSlice) Equals Uses

func (s FloatSlice) Equals(t []float64, epsilon float64) bool

Equals returns true if a given slice has the same contents (with maximum error of epsilon) with the slice

func (FloatSlice) Fill Uses

func (s FloatSlice) Fill(from, to int, vl float64)

Fill sets the elements between from, inclusive, and to, exclusive, to a speicified value.

func (*FloatSlice) Insert Uses

func (s *FloatSlice) Insert(index int, e ...float64)

Insert inserts the specified element at the specified position. NOTE: the insertion algorithm is much better than the slice-trick in go community wiki

func (*FloatSlice) Pop Uses

func (s *FloatSlice) Pop() float64

Pop removes and returns the last element in the slice

func (*FloatSlice) Remove Uses

func (s *FloatSlice) Remove(index int) float64

Remove removes the element at the specified position in this slice.

func (*FloatSlice) RemoveRange Uses

func (s *FloatSlice) RemoveRange(from, to int)

RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice.

func (FloatSlice) Swap Uses

func (s FloatSlice) Swap(i, j int)

The Swap method in sort.Interface.

type IntCmpFunc Uses

type IntCmpFunc func(a, b int) int

IntCmpFunc is a function comparing two int elements. The function returns a positive value if a > b, a negative value if a < b, and 0 otherwise.

Sort, BinarySearch and Merge methods are defined. Usage:

s := []int{}{...}
cmp := CmpFunc(func (a, b int) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if
    return 0
})
cmp.Sort(s)
p, found := cmp.BinarySearch(s, e)

l := []int{}{...}
cmp.Sort(l)
t := cmp.Merge(s, l)

func (IntCmpFunc) BinarySearch Uses

func (cmp IntCmpFunc) BinarySearch(s []int, e int) (pos int, found bool)

BinarySearch searchs a specified element e in a *sorted* list with binary search algorithm. If the list values are not sorted, the return values are undefined. If the element is found in the list, found equals true and pos is the index of the found element in the list. Otherwise found returns false and pos is the position where e is going to be inserted(and the resulting list is still in order)

func (IntCmpFunc) Merge Uses

func (cmp IntCmpFunc) Merge(a, b []int) []int

Merge merges the current *sorted* elements with another *sorted* slice of elements. All elements should be sorted by the same comparator.

func (IntCmpFunc) Sort Uses

func (cmp IntCmpFunc) Sort(s []int)

Sort calls the build-in sort.Sort to sort data in the slice.

type IntMatrix Uses

type IntMatrix [][]int

IntMatrix is 2D array of integers. Elements are store in a single int slice and slices of each row are created.

NOTE the matrix can be sized of 0x0, but never 0x10 or 10x0.

func NewIntMatrix Uses

func NewIntMatrix(nRow, nCol int) IntMatrix

NewIntMatrix creates a new IntMatrix instance with specified number of rows and columns

func (IntMatrix) Clone Uses

func (m IntMatrix) Clone() IntMatrix

Clone clones an IntMatrix

func (IntMatrix) Cols Uses

func (m IntMatrix) Cols() int

Cols returns the number of columns

func (IntMatrix) Fill Uses

func (m IntMatrix) Fill(vl int)

Fill sets all elements of the matrix to a specified value

func (IntMatrix) PrettyString Uses

func (m IntMatrix) PrettyString() string

PrettyString returns a pretty text form of the matrix. This function is mainly for debugging.

func (IntMatrix) Rows Uses

func (m IntMatrix) Rows() int

Rows returns the number of rows

type IntPriorityQueue Uses

type IntPriorityQueue struct {
    // contains filtered or unexported fields
}

IntPriorityQueue is an unbounded priority queue based on a priority heap.

A compare function, typed IntCmpFunc, needs to be specified. Usage:

pq := villa.NewIntPriorityQueue(
    func (a, b int) int {
        if a < b {
            return -1
        } else if a < b {
            return 1
        } // else if
        return 0
    })
pq.Push(10)
pq.Push(20)

vl := pq.Pop()

func NewIntPriorityQueue Uses

func NewIntPriorityQueue(cmp IntCmpFunc) *IntPriorityQueue

NewIntPriorityQueue creates a IntPriorityQueue instance with a specified campare function.

func NewIntPriorityQueueCap Uses

func NewIntPriorityQueueCap(cmp IntCmpFunc, cap int) *IntPriorityQueue

NewIntPriorityQueueCap creates a IntPriorityQueue instance with a specified compare function and a capacity

func (*IntPriorityQueue) Len Uses

func (pq *IntPriorityQueue) Len() int

Len returns the number of elements in this queue.

func (*IntPriorityQueue) Peek Uses

func (pq *IntPriorityQueue) Peek() int

Peek retrieves the head of this queue, or returns 0 if this queue is empty.

func (*IntPriorityQueue) Pop Uses

func (pq *IntPriorityQueue) Pop() int

Pop retrieves and removes the head of this queue, or returns nil if this queue is empty.

func (*IntPriorityQueue) Push Uses

func (pq *IntPriorityQueue) Push(x int)

Push inserts the specified element into this priority queue.

func (*IntPriorityQueue) Remove Uses

func (pq *IntPriorityQueue) Remove(i int) int

Remove removes the element at index i from the priority queue.

func (*IntPriorityQueue) String Uses

func (pq *IntPriorityQueue) String() string

String returns a string with value of "IntPriorityQueue(#)" where # is the number of elements in the queue

type IntSlice Uses

type IntSlice []int

IntSlice is a wrapper to a slice of int.

You can either create an IntSlice instance directly, or converting the type when necessary.

Usage 1:

var s IntSlice
s.Add(10, 20, 30)
s.Insert(1, 40, 50)
s.Swap(1, len(s) - 1)
s.RemoveRange(1, 3)
s.Fill(0, len(s), 55)
s.Clear()

Usage 2:

var s []int
s = append(s, 10, 20, 30)
(*IntSlice)(&s).Insert(1, 40, 50)
IntSlice(s).Swap(1, len(s) - 1)
(*IntSlice)(&s).RemoveRange(1, 3)
IntSlice(s).Fill(0, len(s), 55)
s = s[:0]

Code:

var s IntSlice
s.Add(10, 20, 30)
fmt.Println(s)
s.Insert(1, 40, 50)
fmt.Println(s)
s.Swap(1, len(s)-1)
fmt.Println(s)
s.RemoveRange(1, 3)
fmt.Println(s)
s.Fill(0, len(s), 55)
fmt.Println(s)
s.Clear()
fmt.Println(s)

Output:

[10 20 30]
[10 40 50 20 30]
[10 30 50 20 40]
[10 20 40]
[55 55 55]
[]

Code:

var s []int
s = append(s, 10, 20, 30)
fmt.Println(s)
(*IntSlice)(&s).Insert(1, 40, 50)
fmt.Println(s)
IntSlice(s).Swap(1, len(s)-1)
fmt.Println(s)
(*IntSlice)(&s).RemoveRange(1, 3)
fmt.Println(s)
IntSlice(s).Fill(0, len(s), 55)
fmt.Println(s)
s = s[:0]
fmt.Println(s)

Output:

[10 20 30]
[10 40 50 20 30]
[10 30 50 20 40]
[10 20 40]
[55 55 55]
[]

func (*IntSlice) Add Uses

func (s *IntSlice) Add(e ...int) *IntSlice

Add appends the specified element to the end of this slice.

func (*IntSlice) Clear Uses

func (s *IntSlice) Clear()

Clear removes all of the elements from this slice.

func (IntSlice) Equals Uses

func (s IntSlice) Equals(t []int) bool

Equals returns true if a given slice has the same contents with the slice

func (IntSlice) Fill Uses

func (s IntSlice) Fill(from, to int, vl int)

Fill sets the elements between from, inclusive, and to, exclusive, to a speicified value.

func (*IntSlice) Insert Uses

func (s *IntSlice) Insert(index int, e ...int)

Insert inserts the specified element at the specified position. NOTE: the insertion algorithm is much better than the slice-trick in go community wiki

func (*IntSlice) Pop Uses

func (s *IntSlice) Pop() int

Pop removes and returns the last element in the slice

func (*IntSlice) Remove Uses

func (s *IntSlice) Remove(index int) int

Remove removes the element at the specified position in this slice.

func (*IntSlice) RemoveRange Uses

func (s *IntSlice) RemoveRange(from, to int)

RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice.

func (IntSlice) Swap Uses

func (s IntSlice) Swap(i, j int)

The Swap method in sort.Interface.

type NestedError Uses

type NestedError interface {
    error
    // Message returns the messsage of this error
    Message() string
    // Nested returns the nested error
    Nested() error
    /*
    	Deepest returns the deepest non-NestedError error, which is the
    	original cause error.
    */
    Deepest() error
}

NestedError is an error with current message and nested error.

Use NestErrorf to generate a NestedError. It returns a nil for a nil nested error.

Use NestedError.Deepest() to fetch the cause error.

func NestErrorf Uses

func NestErrorf(err error, fmtstr string, args ...interface{}) NestedError

NestErrorf returns nil if err == nil, otherwise it returns a *NestedError error with a formatted message

type Once Uses

type Once struct {
    F func()
    // contains filtered or unexported fields
}

Once is an object that will perform exactly one action. Different from build-in sync.Once, the function is defined in the Once struct.

func (*Once) Do Uses

func (o *Once) Do()

Do calls the function f if and only if the method is being called for the first time with this receiver. In other words, given

var once Once{F: f}

if once.Do() is called multiple times, only the first call will invoke f.

Do is intended for initialization that must be run exactly once.

Because no call to Do returns until the one call to f returns, if f causes Do to be called, it will deadlock.

type Path Uses

type Path string

Path is a wrapper for a path in the OS. Some commonly used functions are wrapped as methods of Path, and results, if any, are converted back to Path

func (Path) Abs Uses

func (p Path) Abs() (pth Path, err error)

Abs is a wrapper to filepath.Abs It returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique.

func (Path) AbsPath Uses

func (p Path) AbsPath() (ap Path)

AbsPath returns the absolute path returned by Path.Abs() if no error found, panic otherwise.

func (Path) Base Uses

func (p Path) Base() Path

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

func (Path) Clean Uses

func (p Path) Clean() Path

Clean is a wrapper to filepath.Clean.

It returns the shortest path name equivalent to path by purely lexically processing.

func (Path) Command Uses

func (p Path) Command(arg ...string) *exec.Cmd

Command is a wrappter to exec.Command

func (Path) Create Uses

func (p Path) Create() (file *os.File, err error)

Create is a wrapper to os.Create.

It creates the named file mode 0666 (before umask), truncating it if it already exists. If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

func (Path) Dir Uses

func (p Path) Dir() Path

Dir is a wrapper to filepath.Dir. It returns all but the last element of path, typically the path's directory. Trailing path separators are removed before processing. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

func (p Path) EvalSymlinks() (Path, error)

EvalSymlinks is a wrapper to filepath.EvalSymlinks

func (Path) Exists Uses

func (p Path) Exists() bool

Exists checks whether the file exists

func (Path) Ext Uses

func (p Path) Ext() string

Ext is a wrapper to filepath.Ext

func (Path) FromSlash Uses

func (p Path) FromSlash() Path

FromSlash is a wrapper to filepath.FromSlash

func (Path) IsAbs Uses

func (p Path) IsAbs() bool

IsAbs is a wrapper to filepath.IsAbs

IsAbs returns true if the path is absolute.

func (Path) IsDir Uses

func (p Path) IsDir() bool

IsDir returns true only if the path exists and indicates a directory

func (Path) Join Uses

func (p Path) Join(elem ...interface{}) Path

Join connect elems to the tail of path

func (Path) Mkdir Uses

func (p Path) Mkdir(perm os.FileMode) error

Mkdir is a wrappter to os.Mkdir.

It creates a new directory with the specified name and permission bits. If there is an error, it will be of type *PathError.

func (Path) MkdirAll Uses

func (p Path) MkdirAll(perm os.FileMode) error

MkdirAll is a wrappter to os.MkdirAll.

It creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

func (Path) Open Uses

func (p Path) Open() (file *os.File, err error)

Open is a wrapper to os.Open.

It opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

func (Path) OpenFile Uses

func (p Path) OpenFile(flag int, perm os.FileMode) (file *os.File, err error)

OpenFile is a wrapper to os.OpenFile.

It is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

func (Path) ReadDir Uses

func (p Path) ReadDir() (fi []os.FileInfo, err error)

ReadDir is a wrappter to ioutil.ReadDir

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

func (Path) ReadFile Uses

func (p Path) ReadFile() ([]byte, error)

ReadFile is a wrappter to ioutil.ReadFile

func (Path) Readdir Uses

func (p Path) Readdir(n int) (fi []os.FileInfo, err error)

Readdir opens and reads the directory at the path.

func (Path) Rel Uses

func (p Path) Rel(targetpath Path) (Path, error)

Rel is a wrapper to filepath.Rel. It returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it.

func (Path) Remove Uses

func (p Path) Remove() error

Remove is a wrappter to os.Remove

Remove removes the named file or directory. If there is an error, it will be of type *PathError.

func (Path) RemoveAll Uses

func (p Path) RemoveAll() error

RemoveAll is a wrappter to os.RemoveAll RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error).

func (Path) Rename Uses

func (p Path) Rename(newname Path) error

Rename is a wrappter to os.Rename

func (Path) S Uses

func (p Path) S() string

S converts Path back to string. This is sometimes more concise than string(p)

func (Path) Split Uses

func (p Path) Split() (dir, file Path)

Split is a wrapper to filepath.Split

func (Path) SplitList Uses

func (p Path) SplitList() (lst []Path)

SplitList is a wrapper to filepath.SplitList

func (Path) Stat Uses

func (p Path) Stat() (fi os.FileInfo, err error)

Stat is a wrappter to os.Stat

func (p Path) Symlink(dst Path) error

Symlink is a wrappter to os.Symlink

func (Path) TempDir Uses

func (p Path) TempDir(prefix string) (name Path, err error)

TempDir is a wrappter to ioutil.TempDir. It creates a new temporary directory in the directory dir with a name beginning with prefix and returns the path of the new directory. If dir is the empty string, TempDir uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempDir simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when no longer needed.

func (Path) ToSlash Uses

func (p Path) ToSlash() string

ToSlash is a wrapper to filepath.ToSlash

func (Path) VolumeName Uses

func (p Path) VolumeName() string

VolumeName is a wrapper to filepath.VolumeName

func (Path) Walk Uses

func (p Path) Walk(walkFn WalkFunc) error

Walk is a wrapper to filepath.Walk Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root. All errors that arise visiting files and directories are filtered by walkFn. The files are walked in lexical order, which makes the output deterministic but means that for very large directories Walk can be inefficient. Walk does not follow symbolic links.

func (Path) WriteFile Uses

func (p Path) WriteFile(data []byte, perm os.FileMode) error

WriteFile is a wrappter to ioutil.WriteFile

type PriorityQueue Uses

type PriorityQueue struct {
    // contains filtered or unexported fields
}

PriorityQueue is an unbounded priority queue based on a priority heap.

A compare function, typed CmpFunc, needs to be specified. This struct is a better encapsulation of the "container/heap" package provided by go standard library. Usage:

pq := villa.NewPriorityQueue(
   func (a, b interface{}) int {
       if a.(int) < b.(int) {
           return -1
       } else if a.(int) < b.(int) {
           return 1
       } // else if
       return 0
   })
pq.Push(10)
pq.Push(20)

vl := pq.Pop()

func NewPriorityQueue Uses

func NewPriorityQueue(cmp CmpFunc) *PriorityQueue

NewPriorityQueue creates a PriorityQueue instance with a specified compare function.

func NewPriorityQueueCap Uses

func NewPriorityQueueCap(cmp CmpFunc, cap int) *PriorityQueue

NewPriorityQueue creates a PriorityQueue instance with a specified compare function and a capacity

func (*PriorityQueue) Len Uses

func (pq *PriorityQueue) Len() int

Len returns the number of elements in this queue.

func (*PriorityQueue) Peek Uses

func (pq *PriorityQueue) Peek() interface{}

Peek retrieves the head of this queue, or returns nil if this queue is empty.

func (*PriorityQueue) Pop Uses

func (pq *PriorityQueue) Pop() interface{}

Pop retrieves and removes the head of this queue, or returns nil if this queue is empty.

func (*PriorityQueue) Push Uses

func (pq *PriorityQueue) Push(x interface{})

Push inserts the specified element into this priority queue.

func (*PriorityQueue) Remove Uses

func (pq *PriorityQueue) Remove(i int) interface{}

Remove removes the element at index i from the priority queue.

func (*PriorityQueue) String Uses

func (pq *PriorityQueue) String() string

String returns a string with value of "PriorityQueue(Len())"

type Slice Uses

type Slice []interface{}

Slice is a wrapper to a slice of interface{}.

You can either create a Slice instance directly, or converting the type when necessary.

Usage 1:

type A struct {
    B, C int
}

var s Slice
s.Add(10, "20", 30)
s.InsertSlice(len(s), []A{A{50, 60}, A{70, 80}})
s.Insert(1, 40, 50)
s.Swap(1, len(s) - 1)
s.RemoveRange(1, 3)
s.Fill(0, len(s), 55)
s.Clear()

Usage 2:

type A struct {
    B, C int
}

var s []interface{}
s = append(s, 10, "20", 30)
(*Slice)(&s).InsertSlice(len(s), []A{A{50, 60}, A{70, 80}})
(*Slice)(&s).Insert(1, 40, 50)
Slice(s).Swap(1, len(s) - 1)
(*Slice)(&s).RemoveRange(1, 3)
Slice(s).Fill(0, len(s), 55)
s = s[:0]

Code:

type A struct {
    B, C int
}

var s Slice
s.Add(10, "20", 30)
fmt.Println(s)
s.InsertSlice(len(s), []A{A{50, 60}, A{70, 80}})
fmt.Println(s)
s.Insert(1, 40, 50)
fmt.Println(s)
s.Swap(1, len(s)-1)
fmt.Println(s)
s.RemoveRange(1, 3)
fmt.Println(s)
s.Fill(0, len(s), 55)
fmt.Println(s)
s.Clear()
fmt.Println(s)

Output:

[10 20 30]
[10 20 30 {50 60} {70 80}]
[10 40 50 20 30 {50 60} {70 80}]
[10 {70 80} 50 20 30 {50 60} 40]
[10 20 30 {50 60} 40]
[55 55 55 55 55]
[]

Code:

type A struct {
    B, C int
}

var s []interface{}
s = append(s, 10, "20", 30)
fmt.Println(s)
(*Slice)(&s).InsertSlice(len(s), []A{A{50, 60}, A{70, 80}})
fmt.Println(s)
(*Slice)(&s).Insert(1, 40, 50)
fmt.Println(s)
Slice(s).Swap(1, len(s)-1)
fmt.Println(s)
(*Slice)(&s).RemoveRange(1, 3)
fmt.Println(s)
Slice(s).Fill(0, len(s), 55)
fmt.Println(s)
s = s[:0]
fmt.Println(s)

Output:

[10 20 30]
[10 20 30 {50 60} {70 80}]
[10 40 50 20 30 {50 60} {70 80}]
[10 {70 80} 50 20 30 {50 60} 40]
[10 20 30 {50 60} 40]
[55 55 55 55 55]
[]

func (*Slice) Add Uses

func (s *Slice) Add(e ...interface{}) *Slice

Add appends the specified element to the end of this slice.

func (*Slice) Clear Uses

func (s *Slice) Clear()

Clear sets the slice to an zero-length slice.

func (Slice) Equals Uses

func (s Slice) Equals(t []interface{}) bool

Equals returns true if a given slice has the same contents with the slice

func (Slice) Fill Uses

func (s Slice) Fill(from, to int, vl interface{})

Fill sets the elements between from, inclusive, and to, exclusive, to a speicified value.

func (*Slice) Insert Uses

func (s *Slice) Insert(index int, e ...interface{})

Insert inserts specified elements at the specified position. NOTE: the insertion algorithm is much better than the slice-trick in go community wiki

func (*Slice) InsertSlice Uses

func (s *Slice) InsertSlice(index int, src interface{})

InsertSlice inserts the elements of a slice at the specified position. This method is useful when some elements in a slice *NOT* of type []interface{} are to be inserted.

func (*Slice) Pop Uses

func (s *Slice) Pop() interface{}

Pop removes and returns the last element in the slice

func (*Slice) Remove Uses

func (s *Slice) Remove(index int) interface{}

Remove removes the element at the specified position in this slice. The hole in the original slice is filled with a nil value.

func (*Slice) RemoveRange Uses

func (s *Slice) RemoveRange(from, to int)

RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice. The holes in the original slice are filled with nil values.

func (Slice) Swap Uses

func (s Slice) Swap(i, j int)

The Swap method in sort.Interface.

type Stop Uses

type Stop chan Empty

A channel for signaling stop

func NewStop Uses

func NewStop() Stop

Create a Stop with buffer size 1

func (Stop) Stop Uses

func (stop Stop) Stop()

Signal to stop

type StrCmpFunc Uses

type StrCmpFunc func(a, b string) int

StrCmpFunc is a function comparing two string elements. The function returns a positive value if a > b, a negative value if a < b, and 0 otherwise.

Sort, BinarySearch and Merge methods are defined. Usage:

s := []string{}{...}
cmp := CmpFunc(func (a, b string) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if
    return 0
})
cmp.Sort(s)
p, found := cmp.BinarySearch(s, e)

l := []string{}{...}
cmp.Sort(l)
t := cmp.Merge(s, l)

func (StrCmpFunc) BinarySearch Uses

func (cmp StrCmpFunc) BinarySearch(s []string, e string) (pos int, found bool)

BinarySearch searchs a specified element e in a *sorted* list with binary search algorithm. If the list values are not sorted, the return values are undefined.

If the element is found in the list, found equals true and pos is the index of the found element in the list. Otherwise found returns false and pos is the position where e is going to be inserted(and the resulting list is still in order)

func (StrCmpFunc) DiffSlicePair Uses

func (cmp StrCmpFunc) DiffSlicePair(s1, s2 []string) (d1, d2 []string)

DiffSlicePair compares two sorted slices, returns the difference of each relative to the other.

func (StrCmpFunc) Merge Uses

func (cmp StrCmpFunc) Merge(a, b []string) []string

Merge merges the current *sorted* elements with another *sorted* slice of elements.

All elements should be sorted by the same comparator.

func (StrCmpFunc) Sort Uses

func (cmp StrCmpFunc) Sort(s []string)

Sort calls the build-in sort.Sort to sort data in the slice.

type StrSet Uses

type StrSet map[string]struct{}

StrSet is a set of strings

func NewStrSet Uses

func NewStrSet(els ...string) (s StrSet)

NewStrSet creates a string set with specified elements. You need to use this function only when you want to create a StrSet with intial elements. Different from map, a nil value of StrSet is ok to put elemnents.

func (StrSet) Delete Uses

func (s StrSet) Delete(els ...string) StrSet

Delete removes elements from the set

func (StrSet) Elements Uses

func (s StrSet) Elements() (els StringSlice)

Elements returns all elements in the set as a string slice. NOTE the order of elements may change even if the set doesnot change.

func (StrSet) Equals Uses

func (s StrSet) Equals(t StrSet) bool

Equals checks whether the set has same elements with another set.

func (StrSet) In Uses

func (s StrSet) In(el string) bool

In returns true if the specified element is in the set, false otherwise

func (*StrSet) Put Uses

func (s *StrSet) Put(els ...string) StrSet

Put adds elements to the set. The set can be nil

func (StrSet) String Uses

func (s StrSet) String() string

String returns the string presentation of the set

type StringSlice Uses

type StringSlice []string

StringSlice is a wrapper to a slice of interface{}.

You can either create an StringSlice instance directly, or converting the type when necessary.

Usage 1:

type A struct {
    B string
    C int
}

var s StringSlice
s.Add(10, "B", 30)
s.InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}})
s.Insert(1, "D", "E")
s.Swap(1, len(s) - 1)
s.RemoveRange(1, 3)
s.Fill(0, len(s), "EE")
s.Clear()

Usage 2:

type A struct {
    B string
    C int
}

var s []string
(*StringSlice)(&s).Add(10, "B", 30)
(*StringSlice)(&s).InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}})
(*StringSlice)(&s).Insert(1, "D", "E")
StringSlice(s).Swap(1, len(s) - 1)
(*StringSlice)(&s).RemoveRange(1, 3)
StringSlice(s).Fill(0, len(s), "EE")
(*StringSlice)(&s).Clear()

Code:

type A struct {
    B   string
    C   int
}

var s StringSlice
s.Add(10, "B", 30)
fmt.Println(s)
s.InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}})
fmt.Println(s)
s.Insert(1, "D", "E")
fmt.Println(s)
s.Swap(1, len(s)-1)
fmt.Println(s)
s.RemoveRange(1, 3)
fmt.Println(s)
s.Fill(0, len(s), "EE")
fmt.Println(s)
s.Clear()
fmt.Println(s)

Output:

[10 B 30]
[10 B 30 {E 60} {G 80}]
[10 D E B 30 {E 60} {G 80}]
[10 {G 80} E B 30 {E 60} D]
[10 B 30 {E 60} D]
[EE EE EE EE EE]
[]

Code:

type A struct {
    B   string
    C   int
}

var s []string
(*StringSlice)(&s).Add(10, "B", 30)
fmt.Println(s)
(*StringSlice)(&s).InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}})
fmt.Println(s)
(*StringSlice)(&s).Insert(1, "D", "E")
fmt.Println(s)
StringSlice(s).Swap(1, len(s)-1)
fmt.Println(s)
(*StringSlice)(&s).RemoveRange(1, 3)
fmt.Println(s)
StringSlice(s).Fill(0, len(s), "EE")
fmt.Println(s)
(*StringSlice)(&s).Clear()
fmt.Println(s)

Output:

[10 B 30]
[10 B 30 {E 60} {G 80}]
[10 D E B 30 {E 60} {G 80}]
[10 {G 80} E B 30 {E 60} D]
[10 B 30 {E 60} D]
[EE EE EE EE EE]
[]

func (*StringSlice) Add Uses

func (s *StringSlice) Add(e ...interface{}) *StringSlice

Add appends string presentation of the specified elements to the end of this slice.

func (*StringSlice) Clear Uses

func (s *StringSlice) Clear()

Clear sets the slice to an zero-length slice.

func (StringSlice) Equals Uses

func (s StringSlice) Equals(t []string) bool

Equals returns true if a given slice has the same contents with the slice

func (StringSlice) Fill Uses

func (s StringSlice) Fill(from, to int, vl string)

Fill sets the elements between from, inclusive, and to, exclusive, to a speicified value.

func (*StringSlice) Insert Uses

func (s *StringSlice) Insert(index int, e ...interface{})

Insert inserts string presentation of the specified elements at the specified position. NOTE: the insertion algorithm is much better than the slice-trick in go community wiki

func (*StringSlice) InsertSlice Uses

func (s *StringSlice) InsertSlice(index int, src interface{})

InsertSlice inserts string presentation of elements of a slice at the specified position.

func (*StringSlice) Pop Uses

func (s *StringSlice) Pop() string

Pop removes and returns the last element in the slice

func (*StringSlice) Remove Uses

func (s *StringSlice) Remove(index int) string

Remove removes the element at the specified position in this slice. The hole in the original slice is filled with a zero value.

func (*StringSlice) RemoveRange Uses

func (s *StringSlice) RemoveRange(from, to int)

RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice. The holes in the original slice are filled with nil values.

func (StringSlice) Swap Uses

func (s StringSlice) Swap(i, j int)

The Swap method in sort.Interface.

type WalkFunc Uses

type WalkFunc func(path Path, info os.FileInfo, err error) error

WalkFunc is a wrapper to filepath.WalkFunc WalkFunc is the type of the function called for each file or directory visited by Walk. The path argument contains the argument to Walk as a prefix; that is, if Walk is called with "dir", which is a directory containing the file "a", the walk function will be called with argument "dir/a". The info argument is the os.FileInfo for the named path.

If there was a problem walking to the file or directory named by path, the incoming error will describe the problem and the function can decide how to handle that error (and Walk will not descend into that directory). If an error is returned, processing stops. The sole exception is that if path is a directory and the function returns the special value filepath.SkipDir, the contents of the directory are skipped and processing continues as usual on the next file.

Directories

PathSynopsis
heapPackage heap implements a very similar function to the builtin heap(priority queue) package except the elements are not necessarily interface{}, but can be any type.

Package villa imports 19 packages (graph) and is imported by 82 packages. Updated 2018-01-30. Refresh now. Tools for package owners.