villa

package module
Version: v0.0.0-...-68107af Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2020 License: BSD-2-Clause-Views Imports: 19 Imported by: 77

README

go-villa GoSearch

Package villa contains some helper types for Go: priority queue, slice wrapper, binary-search, merge-sort.

GoDoc Link: http://godoc.org/github.com/daviddengcn/go-villa (packages that import villa)

Priority Queues

A generic struct, named PriorityQueue, whose element is an interface{} and some structs whose element is a specific number type.

Using a priority queue requires a less function, with two elements to be compared as the arguments.

PriorityQueue

It encapsulates the heap package using the Slice struct.

Usage:

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

vl := pq.Pop()
IntPriorityQueue

It reimplements the algorithm in heap package. Integers are internally stored in an int slice. Usage:

pq := villa.NewIntPriorityQueue(villa.IntValueCompare)
pq.Push(10)
pq.Push(20)

vl := pq.Pop()

Slice Wrappers

Slice is a wrapper for go slices. It is useful when one needs some modification options on a slice. Implemented methods include: Add, AddSlice, Insert, Swap, Remove, RemoveRange, Fill, Clear

Slice

Usage:

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()
StringSlice

StringSlice is a wrapper for []string. Using Add/Insert/InsertSlice methods, the values of other type can be converted and added to the string slice. Usage:

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()
IntSlice/FloatSlice/ComplexSlice

The following int can be replace with float or complex types(complex compare function needs rewriting). Usage(of IntSlice):

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()

Comparator functions

The common comparator function which compares elements and return the value <0, =0 or >0, if a < b, a==b, or a > b respectively.

Some algorithms that needs a comparator are defined in their methods, including sort(using build-in sort package algorithm), binary-search, and merge. Cast your own comparator function to the corresponding comparator type to use them:

func MyCmp(a, b int) int {
   ...
}

var s, l []int
cmp := IntCmpFunc(MyCmp)
cmp.Sort(s)
cmp.BinarySearch(s, e)

cmp.Sort(l)
sl := cmp.Merge(s, l)

Two comparators are defined for natual orders of ints and floats.

var IntValueCompare IntCmpFunc
var FloatValueCompare FloatCmpFunc
IntMatrix

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

LICENSE

This library is distributed under BSD license.

Documentation

Overview

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

Constants

This section is empty.

Variables

View Source
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
	})
)
View Source
var ErrInvalidRune = errors.New("villa.ByteSlice: invalid rune")
View Source
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).

Functions

func DeepestNested

func DeepestNested(err error) error

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

func Error

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

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

func ErrorN

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

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

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

func ErrorfN

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

func Fatal(v ...interface{})

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

func Fatalf

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

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

func LinePos

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

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 SortF

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

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

Types

type AtomicBox

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

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

func (*AtomicBox) Get

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

Get fetches the object from the box atomically

func (*AtomicBox) Set

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

Set stores the object into the box atomically

type ByteSlice

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

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

NewPByteSlice returns a *ByteSlice.

func (ByteSlice) Close

func (s ByteSlice) Close() error

Close implements io.Closer interface. It does nothing.

func (*ByteSlice) Read

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

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

ReadByte implements io.ByteReader interface

func (*ByteSlice) ReadFrom

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

ReadFrom implements io.ReaderFrom interface.

func (*ByteSlice) ReadRune

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

ReadRune implements io.RuneReader interface.

func (*ByteSlice) Skip

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

func (*ByteSlice) Write

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

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

WriteByte implements io.ByteWriter interface

func (*ByteSlice) WriteItoa

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

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

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

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

WriteTo implements io.WriterTo interface.

type CmpFunc

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

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

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

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

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

type ComplexCmpFunc

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

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

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

func (ComplexCmpFunc) Sort

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

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

type ComplexSlice

type ComplexSlice []complex128

ComplexSlice is wrapper to a slice of complex128.

See examples of IntSlice for reference.

func (*ComplexSlice) Add

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

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

func (*ComplexSlice) Clear

func (s *ComplexSlice) Clear()

Clear removes all of the elements from this slice.

func (ComplexSlice) Equals

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

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

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

func (s *ComplexSlice) Pop() complex128

Pop removes and returns the last element in the slice

func (*ComplexSlice) Remove

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

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

func (*ComplexSlice) RemoveRange

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

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

The Swap method in sort.Interface.

type Empty

type Empty struct{}

An variable of zero-size bytes

type FloatCmpFunc

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

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

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

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

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

type FloatSlice

type FloatSlice []float64

FloatSlice is wrapper to a slice of float64.

See examples of IntSlice for reference.

func (*FloatSlice) Add

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

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

func (*FloatSlice) Clear

func (s *FloatSlice) Clear()

Clear removes all of the elements from this slice.

func (FloatSlice) Equals

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

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

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

func (s *FloatSlice) Pop() float64

Pop removes and returns the last element in the slice

func (*FloatSlice) Remove

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

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

func (*FloatSlice) RemoveRange

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

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

The Swap method in sort.Interface.

type IntCmpFunc

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

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

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

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

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

type IntMatrix

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

func NewIntMatrix(nRow, nCol int) IntMatrix

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

func (IntMatrix) Clone

func (m IntMatrix) Clone() IntMatrix

Clone clones an IntMatrix

func (IntMatrix) Cols

func (m IntMatrix) Cols() int

Cols returns the number of columns

func (IntMatrix) Fill

func (m IntMatrix) Fill(vl int)

Fill sets all elements of the matrix to a specified value

func (IntMatrix) PrettyString

func (m IntMatrix) PrettyString() string

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

func (IntMatrix) Rows

func (m IntMatrix) Rows() int

Rows returns the number of rows

type IntPriorityQueue

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

func NewIntPriorityQueue(cmp IntCmpFunc) *IntPriorityQueue

NewIntPriorityQueue creates a IntPriorityQueue instance with a specified campare function.

func NewIntPriorityQueueCap

func NewIntPriorityQueueCap(cmp IntCmpFunc, cap int) *IntPriorityQueue

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

func (*IntPriorityQueue) Len

func (pq *IntPriorityQueue) Len() int

Len returns the number of elements in this queue.

func (*IntPriorityQueue) Peek

func (pq *IntPriorityQueue) Peek() int

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

func (*IntPriorityQueue) Pop

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

func (pq *IntPriorityQueue) Push(x int)

Push inserts the specified element into this priority queue.

func (*IntPriorityQueue) Remove

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

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

func (*IntPriorityQueue) String

func (pq *IntPriorityQueue) String() string

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

type IntSlice

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]
Example (Direct)
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]
[]
Example (Typecnv)
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

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

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

func (*IntSlice) Clear

func (s *IntSlice) Clear()

Clear removes all of the elements from this slice.

func (IntSlice) Equals

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

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

func (IntSlice) Fill

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

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

func (s *IntSlice) Pop() int

Pop removes and returns the last element in the slice

func (*IntSlice) Remove

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

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

func (*IntSlice) RemoveRange

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

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

The Swap method in sort.Interface.

type NestedError

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

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

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

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

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 Paths

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

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

func (Path) Abs

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

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

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

func (Path) Base

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

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

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

Command is a wrappter to exec.Command

func (Path) Create

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

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

func (p Path) Exists() bool

Exists checks whether the file exists

func (Path) Ext

func (p Path) Ext() string

Ext is a wrapper to filepath.Ext

func (Path) FromSlash

func (p Path) FromSlash() Path

FromSlash is a wrapper to filepath.FromSlash

func (Path) IsAbs

func (p Path) IsAbs() bool

IsAbs is a wrapper to filepath.IsAbs

IsAbs returns true if the path is absolute.

func (Path) IsDir

func (p Path) IsDir() bool

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

func (Path) Join

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

Join connect elems to the tail of path

func (Path) Mkdir

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

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

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

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

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

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

ReadFile is a wrappter to ioutil.ReadFile

func (Path) Readdir

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

Readdir opens and reads the directory at the path.

func (Path) Rel

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

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

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

func (p Path) Rename(newname Path) error

Rename is a wrappter to os.Rename

func (Path) S

func (p Path) S() string

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

func (Path) Split

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

Split is a wrapper to filepath.Split

func (Path) SplitList

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

SplitList is a wrapper to filepath.SplitList

func (Path) Stat

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

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

func (p Path) ToSlash() string

ToSlash is a wrapper to filepath.ToSlash

func (Path) VolumeName

func (p Path) VolumeName() string

VolumeName is a wrapper to filepath.VolumeName

func (Path) Walk

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

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

WriteFile is a wrappter to ioutil.WriteFile

type PriorityQueue

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

func NewPriorityQueue(cmp CmpFunc) *PriorityQueue

NewPriorityQueue creates a PriorityQueue instance with a specified compare function.

func NewPriorityQueueCap

func NewPriorityQueueCap(cmp CmpFunc, cap int) *PriorityQueue

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

func (*PriorityQueue) Len

func (pq *PriorityQueue) Len() int

Len returns the number of elements in this queue.

func (*PriorityQueue) Peek

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

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

func (*PriorityQueue) Pop

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

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

Push inserts the specified element into this priority queue.

func (*PriorityQueue) Remove

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

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

func (*PriorityQueue) String

func (pq *PriorityQueue) String() string

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

type Slice

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]
Example (Direct)
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]
[]
Example (Typecnv)
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

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

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

func (*Slice) Clear

func (s *Slice) Clear()

Clear sets the slice to an zero-length slice.

func (Slice) Equals

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

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

func (Slice) Fill

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

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

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

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

Pop removes and returns the last element in the slice

func (*Slice) Remove

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

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

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

The Swap method in sort.Interface.

type Stop

type Stop chan Empty

A channel for signaling stop

func NewStop

func NewStop() Stop

Create a Stop with buffer size 1

func (Stop) Stop

func (stop Stop) Stop()

Signal to stop

type StrCmpFunc

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

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

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

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

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

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

type StrSet

type StrSet map[string]struct{}

StrSet is a set of strings

func NewStrSet

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

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

Delete removes elements from the set

func (StrSet) Elements

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

func (s StrSet) Equals(t StrSet) bool

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

func (StrSet) In

func (s StrSet) In(el string) bool

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

func (*StrSet) Put

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

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

func (StrSet) String

func (s StrSet) String() string

String returns the string presentation of the set

type StringSlice

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()
Example (Direct)
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]
[]
Example (Typecnv)
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

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

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

func (*StringSlice) Clear

func (s *StringSlice) Clear()

Clear sets the slice to an zero-length slice.

func (StringSlice) Equals

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

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

func (StringSlice) Fill

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

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

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

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

func (*StringSlice) Pop

func (s *StringSlice) Pop() string

Pop removes and returns the last element in the slice

func (*StringSlice) Remove

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

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

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

The Swap method in sort.Interface.

type WalkFunc

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

Path Synopsis
Package 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 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL