id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
162,300
boltdb/bolt
tx.go
forEachPage
func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { p := tx.page(pgid) // Execute function. fn(p, depth) // Recursively loop over children. if (p.flags & branchPageFlag) != 0 { for i := 0; i < int(p.count); i++ { elem := p.branchPageElement(uint16(i)) tx.forEachPage(elem.pgid, depth+1, fn) } } }
go
func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { p := tx.page(pgid) // Execute function. fn(p, depth) // Recursively loop over children. if (p.flags & branchPageFlag) != 0 { for i := 0; i < int(p.count); i++ { elem := p.branchPageElement(uint16(i)) tx.forEachPage(elem.pgid, depth+1, fn) } } }
[ "func", "(", "tx", "*", "Tx", ")", "forEachPage", "(", "pgid", "pgid", ",", "depth", "int", ",", "fn", "func", "(", "*", "page", ",", "int", ")", ")", "{", "p", ":=", "tx", ".", "page", "(", "pgid", ")", "\n\n", "// Execute function.", "fn", "(",...
// forEachPage iterates over every page within a given page and executes a function.
[ "forEachPage", "iterates", "over", "every", "page", "within", "a", "given", "page", "and", "executes", "a", "function", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L584-L597
162,301
boltdb/bolt
tx.go
Page
func (tx *Tx) Page(id int) (*PageInfo, error) { if tx.db == nil { return nil, ErrTxClosed } else if pgid(id) >= tx.meta.pgid { return nil, nil } // Build the page info. p := tx.db.page(pgid(id)) info := &PageInfo{ ID: id, Count: int(p.count), OverflowCount: int(p.overflow), } // Determine the type (or if it's free). if tx.db.freelist.freed(pgid(id)) { info.Type = "free" } else { info.Type = p.typ() } return info, nil }
go
func (tx *Tx) Page(id int) (*PageInfo, error) { if tx.db == nil { return nil, ErrTxClosed } else if pgid(id) >= tx.meta.pgid { return nil, nil } // Build the page info. p := tx.db.page(pgid(id)) info := &PageInfo{ ID: id, Count: int(p.count), OverflowCount: int(p.overflow), } // Determine the type (or if it's free). if tx.db.freelist.freed(pgid(id)) { info.Type = "free" } else { info.Type = p.typ() } return info, nil }
[ "func", "(", "tx", "*", "Tx", ")", "Page", "(", "id", "int", ")", "(", "*", "PageInfo", ",", "error", ")", "{", "if", "tx", ".", "db", "==", "nil", "{", "return", "nil", ",", "ErrTxClosed", "\n", "}", "else", "if", "pgid", "(", "id", ")", ">=...
// Page returns page information for a given page number. // This is only safe for concurrent use when used by a writable transaction.
[ "Page", "returns", "page", "information", "for", "a", "given", "page", "number", ".", "This", "is", "only", "safe", "for", "concurrent", "use", "when", "used", "by", "a", "writable", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L601-L624
162,302
boltdb/bolt
tx.go
Sub
func (s *TxStats) Sub(other *TxStats) TxStats { var diff TxStats diff.PageCount = s.PageCount - other.PageCount diff.PageAlloc = s.PageAlloc - other.PageAlloc diff.CursorCount = s.CursorCount - other.CursorCount diff.NodeCount = s.NodeCount - other.NodeCount diff.NodeDeref = s.NodeDeref - other.NodeDeref diff.Rebalance = s.Rebalance - other.Rebalance diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime diff.Split = s.Split - other.Split diff.Spill = s.Spill - other.Spill diff.SpillTime = s.SpillTime - other.SpillTime diff.Write = s.Write - other.Write diff.WriteTime = s.WriteTime - other.WriteTime return diff }
go
func (s *TxStats) Sub(other *TxStats) TxStats { var diff TxStats diff.PageCount = s.PageCount - other.PageCount diff.PageAlloc = s.PageAlloc - other.PageAlloc diff.CursorCount = s.CursorCount - other.CursorCount diff.NodeCount = s.NodeCount - other.NodeCount diff.NodeDeref = s.NodeDeref - other.NodeDeref diff.Rebalance = s.Rebalance - other.Rebalance diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime diff.Split = s.Split - other.Split diff.Spill = s.Spill - other.Spill diff.SpillTime = s.SpillTime - other.SpillTime diff.Write = s.Write - other.Write diff.WriteTime = s.WriteTime - other.WriteTime return diff }
[ "func", "(", "s", "*", "TxStats", ")", "Sub", "(", "other", "*", "TxStats", ")", "TxStats", "{", "var", "diff", "TxStats", "\n", "diff", ".", "PageCount", "=", "s", ".", "PageCount", "-", "other", ".", "PageCount", "\n", "diff", ".", "PageAlloc", "="...
// Sub calculates and returns the difference between two sets of transaction stats. // This is useful when obtaining stats at two different points and time and // you need the performance counters that occurred within that time span.
[ "Sub", "calculates", "and", "returns", "the", "difference", "between", "two", "sets", "of", "transaction", "stats", ".", "This", "is", "useful", "when", "obtaining", "stats", "at", "two", "different", "points", "and", "time", "and", "you", "need", "the", "pe...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L671-L686
162,303
boltdb/bolt
cmd/bolt/main.go
newCheckCommand
func newCheckCommand(m *Main) *CheckCommand { return &CheckCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newCheckCommand(m *Main) *CheckCommand { return &CheckCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newCheckCommand", "(", "m", "*", "Main", ")", "*", "CheckCommand", "{", "return", "&", "CheckCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}...
// NewCheckCommand returns a CheckCommand.
[ "NewCheckCommand", "returns", "a", "CheckCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L153-L159
162,304
boltdb/bolt
cmd/bolt/main.go
newInfoCommand
func newInfoCommand(m *Main) *InfoCommand { return &InfoCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newInfoCommand(m *Main) *InfoCommand { return &InfoCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newInfoCommand", "(", "m", "*", "Main", ")", "*", "InfoCommand", "{", "return", "&", "InfoCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}" ]
// NewInfoCommand returns a InfoCommand.
[ "NewInfoCommand", "returns", "a", "InfoCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L238-L244
162,305
boltdb/bolt
cmd/bolt/main.go
newDumpCommand
func newDumpCommand(m *Main) *DumpCommand { return &DumpCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newDumpCommand(m *Main) *DumpCommand { return &DumpCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newDumpCommand", "(", "m", "*", "Main", ")", "*", "DumpCommand", "{", "return", "&", "DumpCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}" ]
// newDumpCommand returns a DumpCommand.
[ "newDumpCommand", "returns", "a", "DumpCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L297-L303
162,306
boltdb/bolt
cmd/bolt/main.go
PrintPage
func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { const bytesPerLineN = 16 // Read page into buffer. buf := make([]byte, pageSize) addr := pageID * pageSize if n, err := r.ReadAt(buf, int64(addr)); err != nil { return err } else if n != pageSize { return io.ErrUnexpectedEOF } // Write out to writer in 16-byte lines. var prev []byte var skipped bool for offset := 0; offset < pageSize; offset += bytesPerLineN { // Retrieve current 16-byte line. line := buf[offset : offset+bytesPerLineN] isLastLine := (offset == (pageSize - bytesPerLineN)) // If it's the same as the previous line then print a skip. if bytes.Equal(line, prev) && !isLastLine { if !skipped { fmt.Fprintf(w, "%07x *\n", addr+offset) skipped = true } } else { // Print line as hexadecimal in 2-byte groups. fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, line[0:2], line[2:4], line[4:6], line[6:8], line[8:10], line[10:12], line[12:14], line[14:16], ) skipped = false } // Save the previous line. prev = line } fmt.Fprint(w, "\n") return nil }
go
func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { const bytesPerLineN = 16 // Read page into buffer. buf := make([]byte, pageSize) addr := pageID * pageSize if n, err := r.ReadAt(buf, int64(addr)); err != nil { return err } else if n != pageSize { return io.ErrUnexpectedEOF } // Write out to writer in 16-byte lines. var prev []byte var skipped bool for offset := 0; offset < pageSize; offset += bytesPerLineN { // Retrieve current 16-byte line. line := buf[offset : offset+bytesPerLineN] isLastLine := (offset == (pageSize - bytesPerLineN)) // If it's the same as the previous line then print a skip. if bytes.Equal(line, prev) && !isLastLine { if !skipped { fmt.Fprintf(w, "%07x *\n", addr+offset) skipped = true } } else { // Print line as hexadecimal in 2-byte groups. fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, line[0:2], line[2:4], line[4:6], line[6:8], line[8:10], line[10:12], line[12:14], line[14:16], ) skipped = false } // Save the previous line. prev = line } fmt.Fprint(w, "\n") return nil }
[ "func", "(", "cmd", "*", "DumpCommand", ")", "PrintPage", "(", "w", "io", ".", "Writer", ",", "r", "io", ".", "ReaderAt", ",", "pageID", "int", ",", "pageSize", "int", ")", "error", "{", "const", "bytesPerLineN", "=", "16", "\n\n", "// Read page into buf...
// PrintPage prints a given page as hexadecimal.
[ "PrintPage", "prints", "a", "given", "page", "as", "hexadecimal", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L363-L405
162,307
boltdb/bolt
cmd/bolt/main.go
newPageCommand
func newPageCommand(m *Main) *PageCommand { return &PageCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newPageCommand(m *Main) *PageCommand { return &PageCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newPageCommand", "(", "m", "*", "Main", ")", "*", "PageCommand", "{", "return", "&", "PageCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}" ]
// newPageCommand returns a PageCommand.
[ "newPageCommand", "returns", "a", "PageCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L424-L430
162,308
boltdb/bolt
cmd/bolt/main.go
PrintMeta
func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error { m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) fmt.Fprintf(w, "Version: %d\n", m.version) fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize) fmt.Fprintf(w, "Flags: %08x\n", m.flags) fmt.Fprintf(w, "Root: <pgid=%d>\n", m.root.root) fmt.Fprintf(w, "Freelist: <pgid=%d>\n", m.freelist) fmt.Fprintf(w, "HWM: <pgid=%d>\n", m.pgid) fmt.Fprintf(w, "Txn ID: %d\n", m.txid) fmt.Fprintf(w, "Checksum: %016x\n", m.checksum) fmt.Fprintf(w, "\n") return nil }
go
func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error { m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) fmt.Fprintf(w, "Version: %d\n", m.version) fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize) fmt.Fprintf(w, "Flags: %08x\n", m.flags) fmt.Fprintf(w, "Root: <pgid=%d>\n", m.root.root) fmt.Fprintf(w, "Freelist: <pgid=%d>\n", m.freelist) fmt.Fprintf(w, "HWM: <pgid=%d>\n", m.pgid) fmt.Fprintf(w, "Txn ID: %d\n", m.txid) fmt.Fprintf(w, "Checksum: %016x\n", m.checksum) fmt.Fprintf(w, "\n") return nil }
[ "func", "(", "cmd", "*", "PageCommand", ")", "PrintMeta", "(", "w", "io", ".", "Writer", ",", "buf", "[", "]", "byte", ")", "error", "{", "m", ":=", "(", "*", "meta", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "PageHeaderSize", "]"...
// PrintMeta prints the data from the meta page.
[ "PrintMeta", "prints", "the", "data", "from", "the", "meta", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L505-L517
162,309
boltdb/bolt
cmd/bolt/main.go
PrintLeaf
func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each key/value. for i := uint16(0); i < p.count; i++ { e := p.leafPageElement(i) // Format key as string. var k string if isPrintable(string(e.key())) { k = fmt.Sprintf("%q", string(e.key())) } else { k = fmt.Sprintf("%x", string(e.key())) } // Format value as string. var v string if (e.flags & uint32(bucketLeafFlag)) != 0 { b := (*bucket)(unsafe.Pointer(&e.value()[0])) v = fmt.Sprintf("<pgid=%d,seq=%d>", b.root, b.sequence) } else if isPrintable(string(e.value())) { v = fmt.Sprintf("%q", string(e.value())) } else { v = fmt.Sprintf("%x", string(e.value())) } fmt.Fprintf(w, "%s: %s\n", k, v) } fmt.Fprintf(w, "\n") return nil }
go
func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each key/value. for i := uint16(0); i < p.count; i++ { e := p.leafPageElement(i) // Format key as string. var k string if isPrintable(string(e.key())) { k = fmt.Sprintf("%q", string(e.key())) } else { k = fmt.Sprintf("%x", string(e.key())) } // Format value as string. var v string if (e.flags & uint32(bucketLeafFlag)) != 0 { b := (*bucket)(unsafe.Pointer(&e.value()[0])) v = fmt.Sprintf("<pgid=%d,seq=%d>", b.root, b.sequence) } else if isPrintable(string(e.value())) { v = fmt.Sprintf("%q", string(e.value())) } else { v = fmt.Sprintf("%x", string(e.value())) } fmt.Fprintf(w, "%s: %s\n", k, v) } fmt.Fprintf(w, "\n") return nil }
[ "func", "(", "cmd", "*", "PageCommand", ")", "PrintLeaf", "(", "w", "io", ".", "Writer", ",", "buf", "[", "]", "byte", ")", "error", "{", "p", ":=", "(", "*", "page", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "0", "]", ")", ")...
// PrintLeaf prints the data for a leaf page.
[ "PrintLeaf", "prints", "the", "data", "for", "a", "leaf", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L520-L554
162,310
boltdb/bolt
cmd/bolt/main.go
PrintBranch
func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each key/value. for i := uint16(0); i < p.count; i++ { e := p.branchPageElement(i) // Format key as string. var k string if isPrintable(string(e.key())) { k = fmt.Sprintf("%q", string(e.key())) } else { k = fmt.Sprintf("%x", string(e.key())) } fmt.Fprintf(w, "%s: <pgid=%d>\n", k, e.pgid) } fmt.Fprintf(w, "\n") return nil }
go
func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each key/value. for i := uint16(0); i < p.count; i++ { e := p.branchPageElement(i) // Format key as string. var k string if isPrintable(string(e.key())) { k = fmt.Sprintf("%q", string(e.key())) } else { k = fmt.Sprintf("%x", string(e.key())) } fmt.Fprintf(w, "%s: <pgid=%d>\n", k, e.pgid) } fmt.Fprintf(w, "\n") return nil }
[ "func", "(", "cmd", "*", "PageCommand", ")", "PrintBranch", "(", "w", "io", ".", "Writer", ",", "buf", "[", "]", "byte", ")", "error", "{", "p", ":=", "(", "*", "page", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "0", "]", ")", ...
// PrintBranch prints the data for a leaf page.
[ "PrintBranch", "prints", "the", "data", "for", "a", "leaf", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L557-L580
162,311
boltdb/bolt
cmd/bolt/main.go
PrintFreelist
func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each page in the freelist. ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)) for i := uint16(0); i < p.count; i++ { fmt.Fprintf(w, "%d\n", ids[i]) } fmt.Fprintf(w, "\n") return nil }
go
func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error { p := (*page)(unsafe.Pointer(&buf[0])) // Print number of items. fmt.Fprintf(w, "Item Count: %d\n", p.count) fmt.Fprintf(w, "\n") // Print each page in the freelist. ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)) for i := uint16(0); i < p.count; i++ { fmt.Fprintf(w, "%d\n", ids[i]) } fmt.Fprintf(w, "\n") return nil }
[ "func", "(", "cmd", "*", "PageCommand", ")", "PrintFreelist", "(", "w", "io", ".", "Writer", ",", "buf", "[", "]", "byte", ")", "error", "{", "p", ":=", "(", "*", "page", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "0", "]", ")", ...
// PrintFreelist prints the data for a freelist page.
[ "PrintFreelist", "prints", "the", "data", "for", "a", "freelist", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L583-L597
162,312
boltdb/bolt
cmd/bolt/main.go
newPagesCommand
func newPagesCommand(m *Main) *PagesCommand { return &PagesCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newPagesCommand(m *Main) *PagesCommand { return &PagesCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newPagesCommand", "(", "m", "*", "Main", ")", "*", "PagesCommand", "{", "return", "&", "PagesCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}...
// NewPagesCommand returns a PagesCommand.
[ "NewPagesCommand", "returns", "a", "PagesCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L661-L667
162,313
boltdb/bolt
cmd/bolt/main.go
newStatsCommand
func newStatsCommand(m *Main) *StatsCommand { return &StatsCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newStatsCommand(m *Main) *StatsCommand { return &StatsCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newStatsCommand", "(", "m", "*", "Main", ")", "*", "StatsCommand", "{", "return", "&", "StatsCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}...
// NewStatsCommand returns a StatsCommand.
[ "NewStatsCommand", "returns", "a", "StatsCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L755-L761
162,314
boltdb/bolt
cmd/bolt/main.go
newBenchCommand
func newBenchCommand(m *Main) *BenchCommand { return &BenchCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newBenchCommand(m *Main) *BenchCommand { return &BenchCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newBenchCommand", "(", "m", "*", "Main", ")", "*", "BenchCommand", "{", "return", "&", "BenchCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n", "}...
// NewBenchCommand returns a BenchCommand using the
[ "NewBenchCommand", "returns", "a", "BenchCommand", "using", "the" ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L892-L898
162,315
boltdb/bolt
cmd/bolt/main.go
Run
func (cmd *BenchCommand) Run(args ...string) error { // Parse CLI arguments. options, err := cmd.ParseFlags(args) if err != nil { return err } // Remove path if "-work" is not set. Otherwise keep path. if options.Work { fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path) } else { defer os.Remove(options.Path) } // Create database. db, err := bolt.Open(options.Path, 0666, nil) if err != nil { return err } db.NoSync = options.NoSync defer db.Close() // Write to the database. var results BenchResults if err := cmd.runWrites(db, options, &results); err != nil { return fmt.Errorf("write: %v", err) } // Read from the database. if err := cmd.runReads(db, options, &results); err != nil { return fmt.Errorf("bench: read: %s", err) } // Print results. fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond()) fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond()) fmt.Fprintln(os.Stderr, "") return nil }
go
func (cmd *BenchCommand) Run(args ...string) error { // Parse CLI arguments. options, err := cmd.ParseFlags(args) if err != nil { return err } // Remove path if "-work" is not set. Otherwise keep path. if options.Work { fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path) } else { defer os.Remove(options.Path) } // Create database. db, err := bolt.Open(options.Path, 0666, nil) if err != nil { return err } db.NoSync = options.NoSync defer db.Close() // Write to the database. var results BenchResults if err := cmd.runWrites(db, options, &results); err != nil { return fmt.Errorf("write: %v", err) } // Read from the database. if err := cmd.runReads(db, options, &results); err != nil { return fmt.Errorf("bench: read: %s", err) } // Print results. fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond()) fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond()) fmt.Fprintln(os.Stderr, "") return nil }
[ "func", "(", "cmd", "*", "BenchCommand", ")", "Run", "(", "args", "...", "string", ")", "error", "{", "// Parse CLI arguments.", "options", ",", "err", ":=", "cmd", ".", "ParseFlags", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "er...
// Run executes the "bench" command.
[ "Run", "executes", "the", "bench", "command", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L901-L939
162,316
boltdb/bolt
cmd/bolt/main.go
runWrites
func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error { // Start profiling for writes. if options.ProfileMode == "rw" || options.ProfileMode == "w" { cmd.startProfiling(options) } t := time.Now() var err error switch options.WriteMode { case "seq": err = cmd.runWritesSequential(db, options, results) case "rnd": err = cmd.runWritesRandom(db, options, results) case "seq-nest": err = cmd.runWritesSequentialNested(db, options, results) case "rnd-nest": err = cmd.runWritesRandomNested(db, options, results) default: return fmt.Errorf("invalid write mode: %s", options.WriteMode) } // Save time to write. results.WriteDuration = time.Since(t) // Stop profiling for writes only. if options.ProfileMode == "w" { cmd.stopProfiling() } return err }
go
func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error { // Start profiling for writes. if options.ProfileMode == "rw" || options.ProfileMode == "w" { cmd.startProfiling(options) } t := time.Now() var err error switch options.WriteMode { case "seq": err = cmd.runWritesSequential(db, options, results) case "rnd": err = cmd.runWritesRandom(db, options, results) case "seq-nest": err = cmd.runWritesSequentialNested(db, options, results) case "rnd-nest": err = cmd.runWritesRandomNested(db, options, results) default: return fmt.Errorf("invalid write mode: %s", options.WriteMode) } // Save time to write. results.WriteDuration = time.Since(t) // Stop profiling for writes only. if options.ProfileMode == "w" { cmd.stopProfiling() } return err }
[ "func", "(", "cmd", "*", "BenchCommand", ")", "runWrites", "(", "db", "*", "bolt", ".", "DB", ",", "options", "*", "BenchOptions", ",", "results", "*", "BenchResults", ")", "error", "{", "// Start profiling for writes.", "if", "options", ".", "ProfileMode", ...
// Writes to the database.
[ "Writes", "to", "the", "database", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L989-L1020
162,317
boltdb/bolt
cmd/bolt/main.go
runReads
func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error { // Start profiling for reads. if options.ProfileMode == "r" { cmd.startProfiling(options) } t := time.Now() var err error switch options.ReadMode { case "seq": switch options.WriteMode { case "seq-nest", "rnd-nest": err = cmd.runReadsSequentialNested(db, options, results) default: err = cmd.runReadsSequential(db, options, results) } default: return fmt.Errorf("invalid read mode: %s", options.ReadMode) } // Save read time. results.ReadDuration = time.Since(t) // Stop profiling for reads. if options.ProfileMode == "rw" || options.ProfileMode == "r" { cmd.stopProfiling() } return err }
go
func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error { // Start profiling for reads. if options.ProfileMode == "r" { cmd.startProfiling(options) } t := time.Now() var err error switch options.ReadMode { case "seq": switch options.WriteMode { case "seq-nest", "rnd-nest": err = cmd.runReadsSequentialNested(db, options, results) default: err = cmd.runReadsSequential(db, options, results) } default: return fmt.Errorf("invalid read mode: %s", options.ReadMode) } // Save read time. results.ReadDuration = time.Since(t) // Stop profiling for reads. if options.ProfileMode == "rw" || options.ProfileMode == "r" { cmd.stopProfiling() } return err }
[ "func", "(", "cmd", "*", "BenchCommand", ")", "runReads", "(", "db", "*", "bolt", ".", "DB", ",", "options", "*", "BenchOptions", ",", "results", "*", "BenchResults", ")", "error", "{", "// Start profiling for reads.", "if", "options", ".", "ProfileMode", "=...
// Reads from the database.
[ "Reads", "from", "the", "database", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1115-L1145
162,318
boltdb/bolt
cmd/bolt/main.go
startProfiling
func (cmd *BenchCommand) startProfiling(options *BenchOptions) { var err error // Start CPU profiling. if options.CPUProfile != "" { cpuprofile, err = os.Create(options.CPUProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err) os.Exit(1) } pprof.StartCPUProfile(cpuprofile) } // Start memory profiling. if options.MemProfile != "" { memprofile, err = os.Create(options.MemProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err) os.Exit(1) } runtime.MemProfileRate = 4096 } // Start fatal profiling. if options.BlockProfile != "" { blockprofile, err = os.Create(options.BlockProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err) os.Exit(1) } runtime.SetBlockProfileRate(1) } }
go
func (cmd *BenchCommand) startProfiling(options *BenchOptions) { var err error // Start CPU profiling. if options.CPUProfile != "" { cpuprofile, err = os.Create(options.CPUProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err) os.Exit(1) } pprof.StartCPUProfile(cpuprofile) } // Start memory profiling. if options.MemProfile != "" { memprofile, err = os.Create(options.MemProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err) os.Exit(1) } runtime.MemProfileRate = 4096 } // Start fatal profiling. if options.BlockProfile != "" { blockprofile, err = os.Create(options.BlockProfile) if err != nil { fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err) os.Exit(1) } runtime.SetBlockProfileRate(1) } }
[ "func", "(", "cmd", "*", "BenchCommand", ")", "startProfiling", "(", "options", "*", "BenchOptions", ")", "{", "var", "err", "error", "\n\n", "// Start CPU profiling.", "if", "options", ".", "CPUProfile", "!=", "\"", "\"", "{", "cpuprofile", ",", "err", "=",...
// Starts all profiles set on the options.
[ "Starts", "all", "profiles", "set", "on", "the", "options", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1218-L1250
162,319
boltdb/bolt
cmd/bolt/main.go
stopProfiling
func (cmd *BenchCommand) stopProfiling() { if cpuprofile != nil { pprof.StopCPUProfile() cpuprofile.Close() cpuprofile = nil } if memprofile != nil { pprof.Lookup("heap").WriteTo(memprofile, 0) memprofile.Close() memprofile = nil } if blockprofile != nil { pprof.Lookup("block").WriteTo(blockprofile, 0) blockprofile.Close() blockprofile = nil runtime.SetBlockProfileRate(0) } }
go
func (cmd *BenchCommand) stopProfiling() { if cpuprofile != nil { pprof.StopCPUProfile() cpuprofile.Close() cpuprofile = nil } if memprofile != nil { pprof.Lookup("heap").WriteTo(memprofile, 0) memprofile.Close() memprofile = nil } if blockprofile != nil { pprof.Lookup("block").WriteTo(blockprofile, 0) blockprofile.Close() blockprofile = nil runtime.SetBlockProfileRate(0) } }
[ "func", "(", "cmd", "*", "BenchCommand", ")", "stopProfiling", "(", ")", "{", "if", "cpuprofile", "!=", "nil", "{", "pprof", ".", "StopCPUProfile", "(", ")", "\n", "cpuprofile", ".", "Close", "(", ")", "\n", "cpuprofile", "=", "nil", "\n", "}", "\n\n",...
// Stops all profiles.
[ "Stops", "all", "profiles", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1253-L1272
162,320
boltdb/bolt
cmd/bolt/main.go
WriteOpDuration
func (r *BenchResults) WriteOpDuration() time.Duration { if r.WriteOps == 0 { return 0 } return r.WriteDuration / time.Duration(r.WriteOps) }
go
func (r *BenchResults) WriteOpDuration() time.Duration { if r.WriteOps == 0 { return 0 } return r.WriteDuration / time.Duration(r.WriteOps) }
[ "func", "(", "r", "*", "BenchResults", ")", "WriteOpDuration", "(", ")", "time", ".", "Duration", "{", "if", "r", ".", "WriteOps", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "r", ".", "WriteDuration", "/", "time", ".", "Duration", "(",...
// Returns the duration for a single write operation.
[ "Returns", "the", "duration", "for", "a", "single", "write", "operation", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1302-L1307
162,321
boltdb/bolt
cmd/bolt/main.go
WriteOpsPerSecond
func (r *BenchResults) WriteOpsPerSecond() int { var op = r.WriteOpDuration() if op == 0 { return 0 } return int(time.Second) / int(op) }
go
func (r *BenchResults) WriteOpsPerSecond() int { var op = r.WriteOpDuration() if op == 0 { return 0 } return int(time.Second) / int(op) }
[ "func", "(", "r", "*", "BenchResults", ")", "WriteOpsPerSecond", "(", ")", "int", "{", "var", "op", "=", "r", ".", "WriteOpDuration", "(", ")", "\n", "if", "op", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "int", "(", "time", ".", "...
// Returns average number of write operations that can be performed per second.
[ "Returns", "average", "number", "of", "write", "operations", "that", "can", "be", "performed", "per", "second", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1310-L1316
162,322
boltdb/bolt
cmd/bolt/main.go
ReadOpDuration
func (r *BenchResults) ReadOpDuration() time.Duration { if r.ReadOps == 0 { return 0 } return r.ReadDuration / time.Duration(r.ReadOps) }
go
func (r *BenchResults) ReadOpDuration() time.Duration { if r.ReadOps == 0 { return 0 } return r.ReadDuration / time.Duration(r.ReadOps) }
[ "func", "(", "r", "*", "BenchResults", ")", "ReadOpDuration", "(", ")", "time", ".", "Duration", "{", "if", "r", ".", "ReadOps", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "r", ".", "ReadDuration", "/", "time", ".", "Duration", "(", ...
// Returns the duration for a single read operation.
[ "Returns", "the", "duration", "for", "a", "single", "read", "operation", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1319-L1324
162,323
boltdb/bolt
cmd/bolt/main.go
ReadOpsPerSecond
func (r *BenchResults) ReadOpsPerSecond() int { var op = r.ReadOpDuration() if op == 0 { return 0 } return int(time.Second) / int(op) }
go
func (r *BenchResults) ReadOpsPerSecond() int { var op = r.ReadOpDuration() if op == 0 { return 0 } return int(time.Second) / int(op) }
[ "func", "(", "r", "*", "BenchResults", ")", "ReadOpsPerSecond", "(", ")", "int", "{", "var", "op", "=", "r", ".", "ReadOpDuration", "(", ")", "\n", "if", "op", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "int", "(", "time", ".", "Se...
// Returns average number of read operations that can be performed per second.
[ "Returns", "average", "number", "of", "read", "operations", "that", "can", "be", "performed", "per", "second", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1327-L1333
162,324
boltdb/bolt
cmd/bolt/main.go
isPrintable
func isPrintable(s string) bool { if !utf8.ValidString(s) { return false } for _, ch := range s { if !unicode.IsPrint(ch) { return false } } return true }
go
func isPrintable(s string) bool { if !utf8.ValidString(s) { return false } for _, ch := range s { if !unicode.IsPrint(ch) { return false } } return true }
[ "func", "isPrintable", "(", "s", "string", ")", "bool", "{", "if", "!", "utf8", ".", "ValidString", "(", "s", ")", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "ch", ":=", "range", "s", "{", "if", "!", "unicode", ".", "IsPrint", "(",...
// isPrintable returns true if the string is valid unicode and contains only printable runes.
[ "isPrintable", "returns", "true", "if", "the", "string", "is", "valid", "unicode", "and", "contains", "only", "printable", "runes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1345-L1355
162,325
boltdb/bolt
cmd/bolt/main.go
ReadPage
func ReadPage(path string, pageID int) (*page, []byte, error) { // Find page size. pageSize, err := ReadPageSize(path) if err != nil { return nil, nil, fmt.Errorf("read page size: %s", err) } // Open database file. f, err := os.Open(path) if err != nil { return nil, nil, err } defer f.Close() // Read one block into buffer. buf := make([]byte, pageSize) if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { return nil, nil, err } else if n != len(buf) { return nil, nil, io.ErrUnexpectedEOF } // Determine total number of blocks. p := (*page)(unsafe.Pointer(&buf[0])) overflowN := p.overflow // Re-read entire page (with overflow) into buffer. buf = make([]byte, (int(overflowN)+1)*pageSize) if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { return nil, nil, err } else if n != len(buf) { return nil, nil, io.ErrUnexpectedEOF } p = (*page)(unsafe.Pointer(&buf[0])) return p, buf, nil }
go
func ReadPage(path string, pageID int) (*page, []byte, error) { // Find page size. pageSize, err := ReadPageSize(path) if err != nil { return nil, nil, fmt.Errorf("read page size: %s", err) } // Open database file. f, err := os.Open(path) if err != nil { return nil, nil, err } defer f.Close() // Read one block into buffer. buf := make([]byte, pageSize) if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { return nil, nil, err } else if n != len(buf) { return nil, nil, io.ErrUnexpectedEOF } // Determine total number of blocks. p := (*page)(unsafe.Pointer(&buf[0])) overflowN := p.overflow // Re-read entire page (with overflow) into buffer. buf = make([]byte, (int(overflowN)+1)*pageSize) if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { return nil, nil, err } else if n != len(buf) { return nil, nil, io.ErrUnexpectedEOF } p = (*page)(unsafe.Pointer(&buf[0])) return p, buf, nil }
[ "func", "ReadPage", "(", "path", "string", ",", "pageID", "int", ")", "(", "*", "page", ",", "[", "]", "byte", ",", "error", ")", "{", "// Find page size.", "pageSize", ",", "err", ":=", "ReadPageSize", "(", "path", ")", "\n", "if", "err", "!=", "nil...
// ReadPage reads page info & full page data from a path. // This is not transactionally safe.
[ "ReadPage", "reads", "page", "info", "&", "full", "page", "data", "from", "a", "path", ".", "This", "is", "not", "transactionally", "safe", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1359-L1395
162,326
boltdb/bolt
cmd/bolt/main.go
ReadPageSize
func ReadPageSize(path string) (int, error) { // Open database file. f, err := os.Open(path) if err != nil { return 0, err } defer f.Close() // Read 4KB chunk. buf := make([]byte, 4096) if _, err := io.ReadFull(f, buf); err != nil { return 0, err } // Read page size from metadata. m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) return int(m.pageSize), nil }
go
func ReadPageSize(path string) (int, error) { // Open database file. f, err := os.Open(path) if err != nil { return 0, err } defer f.Close() // Read 4KB chunk. buf := make([]byte, 4096) if _, err := io.ReadFull(f, buf); err != nil { return 0, err } // Read page size from metadata. m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) return int(m.pageSize), nil }
[ "func", "ReadPageSize", "(", "path", "string", ")", "(", "int", ",", "error", ")", "{", "// Open database file.", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}",...
// ReadPageSize reads page size a path. // This is not transactionally safe.
[ "ReadPageSize", "reads", "page", "size", "a", "path", ".", "This", "is", "not", "transactionally", "safe", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1399-L1416
162,327
boltdb/bolt
cmd/bolt/main.go
atois
func atois(strs []string) ([]int, error) { var a []int for _, str := range strs { i, err := strconv.Atoi(str) if err != nil { return nil, err } a = append(a, i) } return a, nil }
go
func atois(strs []string) ([]int, error) { var a []int for _, str := range strs { i, err := strconv.Atoi(str) if err != nil { return nil, err } a = append(a, i) } return a, nil }
[ "func", "atois", "(", "strs", "[", "]", "string", ")", "(", "[", "]", "int", ",", "error", ")", "{", "var", "a", "[", "]", "int", "\n", "for", "_", ",", "str", ":=", "range", "strs", "{", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", ...
// atois parses a slice of strings into integers.
[ "atois", "parses", "a", "slice", "of", "strings", "into", "integers", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1419-L1429
162,328
boltdb/bolt
cmd/bolt/main.go
newCompactCommand
func newCompactCommand(m *Main) *CompactCommand { return &CompactCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
go
func newCompactCommand(m *Main) *CompactCommand { return &CompactCommand{ Stdin: m.Stdin, Stdout: m.Stdout, Stderr: m.Stderr, } }
[ "func", "newCompactCommand", "(", "m", "*", "Main", ")", "*", "CompactCommand", "{", "return", "&", "CompactCommand", "{", "Stdin", ":", "m", ".", "Stdin", ",", "Stdout", ":", "m", ".", "Stdout", ",", "Stderr", ":", "m", ".", "Stderr", ",", "}", "\n"...
// newCompactCommand returns a CompactCommand.
[ "newCompactCommand", "returns", "a", "CompactCommand", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1549-L1555
162,329
boltdb/bolt
cmd/bolt/main.go
walk
func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error { return db.View(func(tx *bolt.Tx) error { return tx.ForEach(func(name []byte, b *bolt.Bucket) error { return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn) }) }) }
go
func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error { return db.View(func(tx *bolt.Tx) error { return tx.ForEach(func(name []byte, b *bolt.Bucket) error { return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn) }) }) }
[ "func", "(", "cmd", "*", "CompactCommand", ")", "walk", "(", "db", "*", "bolt", ".", "DB", ",", "walkFn", "walkFunc", ")", "error", "{", "return", "db", ".", "View", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "tx...
// walk walks recursively the bolt database db, calling walkFn for each key it finds.
[ "walk", "walks", "recursively", "the", "bolt", "database", "db", "calling", "walkFn", "for", "each", "key", "it", "finds", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cmd/bolt/main.go#L1694-L1700
162,330
boltdb/bolt
node.go
size
func (n *node) size() int { sz, elsz := pageHeaderSize, n.pageElementSize() for i := 0; i < len(n.inodes); i++ { item := &n.inodes[i] sz += elsz + len(item.key) + len(item.value) } return sz }
go
func (n *node) size() int { sz, elsz := pageHeaderSize, n.pageElementSize() for i := 0; i < len(n.inodes); i++ { item := &n.inodes[i] sz += elsz + len(item.key) + len(item.value) } return sz }
[ "func", "(", "n", "*", "node", ")", "size", "(", ")", "int", "{", "sz", ",", "elsz", ":=", "pageHeaderSize", ",", "n", ".", "pageElementSize", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "n", ".", "inodes", ")", ";", "i"...
// size returns the size of the node after serialization.
[ "size", "returns", "the", "size", "of", "the", "node", "after", "serialization", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L40-L47
162,331
boltdb/bolt
node.go
sizeLessThan
func (n *node) sizeLessThan(v int) bool { sz, elsz := pageHeaderSize, n.pageElementSize() for i := 0; i < len(n.inodes); i++ { item := &n.inodes[i] sz += elsz + len(item.key) + len(item.value) if sz >= v { return false } } return true }
go
func (n *node) sizeLessThan(v int) bool { sz, elsz := pageHeaderSize, n.pageElementSize() for i := 0; i < len(n.inodes); i++ { item := &n.inodes[i] sz += elsz + len(item.key) + len(item.value) if sz >= v { return false } } return true }
[ "func", "(", "n", "*", "node", ")", "sizeLessThan", "(", "v", "int", ")", "bool", "{", "sz", ",", "elsz", ":=", "pageHeaderSize", ",", "n", ".", "pageElementSize", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "n", ".", "ino...
// sizeLessThan returns true if the node is less than a given size. // This is an optimization to avoid calculating a large node when we only need // to know if it fits inside a certain page size.
[ "sizeLessThan", "returns", "true", "if", "the", "node", "is", "less", "than", "a", "given", "size", ".", "This", "is", "an", "optimization", "to", "avoid", "calculating", "a", "large", "node", "when", "we", "only", "need", "to", "know", "if", "it", "fits...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L52-L62
162,332
boltdb/bolt
node.go
childAt
func (n *node) childAt(index int) *node { if n.isLeaf { panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) } return n.bucket.node(n.inodes[index].pgid, n) }
go
func (n *node) childAt(index int) *node { if n.isLeaf { panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) } return n.bucket.node(n.inodes[index].pgid, n) }
[ "func", "(", "n", "*", "node", ")", "childAt", "(", "index", "int", ")", "*", "node", "{", "if", "n", ".", "isLeaf", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", ")", ")", "\n", "}", "\n", "return", "n", ".", "buck...
// childAt returns the child node at a given index.
[ "childAt", "returns", "the", "child", "node", "at", "a", "given", "index", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L73-L78
162,333
boltdb/bolt
node.go
childIndex
func (n *node) childIndex(child *node) int { index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) return index }
go
func (n *node) childIndex(child *node) int { index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) return index }
[ "func", "(", "n", "*", "node", ")", "childIndex", "(", "child", "*", "node", ")", "int", "{", "index", ":=", "sort", ".", "Search", "(", "len", "(", "n", ".", "inodes", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", "bytes", "."...
// childIndex returns the index of a given child node.
[ "childIndex", "returns", "the", "index", "of", "a", "given", "child", "node", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L81-L84
162,334
boltdb/bolt
node.go
nextSibling
func (n *node) nextSibling() *node { if n.parent == nil { return nil } index := n.parent.childIndex(n) if index >= n.parent.numChildren()-1 { return nil } return n.parent.childAt(index + 1) }
go
func (n *node) nextSibling() *node { if n.parent == nil { return nil } index := n.parent.childIndex(n) if index >= n.parent.numChildren()-1 { return nil } return n.parent.childAt(index + 1) }
[ "func", "(", "n", "*", "node", ")", "nextSibling", "(", ")", "*", "node", "{", "if", "n", ".", "parent", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "index", ":=", "n", ".", "parent", ".", "childIndex", "(", "n", ")", "\n", "if", "index...
// nextSibling returns the next node with the same parent.
[ "nextSibling", "returns", "the", "next", "node", "with", "the", "same", "parent", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L92-L101
162,335
boltdb/bolt
node.go
prevSibling
func (n *node) prevSibling() *node { if n.parent == nil { return nil } index := n.parent.childIndex(n) if index == 0 { return nil } return n.parent.childAt(index - 1) }
go
func (n *node) prevSibling() *node { if n.parent == nil { return nil } index := n.parent.childIndex(n) if index == 0 { return nil } return n.parent.childAt(index - 1) }
[ "func", "(", "n", "*", "node", ")", "prevSibling", "(", ")", "*", "node", "{", "if", "n", ".", "parent", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "index", ":=", "n", ".", "parent", ".", "childIndex", "(", "n", ")", "\n", "if", "index...
// prevSibling returns the previous node with the same parent.
[ "prevSibling", "returns", "the", "previous", "node", "with", "the", "same", "parent", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L104-L113
162,336
boltdb/bolt
node.go
del
func (n *node) del(key []byte) { // Find index of key. index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) // Exit if the key isn't found. if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { return } // Delete inode from the node. n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) // Mark the node as needing rebalancing. n.unbalanced = true }
go
func (n *node) del(key []byte) { // Find index of key. index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) // Exit if the key isn't found. if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { return } // Delete inode from the node. n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) // Mark the node as needing rebalancing. n.unbalanced = true }
[ "func", "(", "n", "*", "node", ")", "del", "(", "key", "[", "]", "byte", ")", "{", "// Find index of key.", "index", ":=", "sort", ".", "Search", "(", "len", "(", "n", ".", "inodes", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", ...
// del removes a key from the node.
[ "del", "removes", "a", "key", "from", "the", "node", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L144-L158
162,337
boltdb/bolt
node.go
read
func (n *node) read(p *page) { n.pgid = p.id n.isLeaf = ((p.flags & leafPageFlag) != 0) n.inodes = make(inodes, int(p.count)) for i := 0; i < int(p.count); i++ { inode := &n.inodes[i] if n.isLeaf { elem := p.leafPageElement(uint16(i)) inode.flags = elem.flags inode.key = elem.key() inode.value = elem.value() } else { elem := p.branchPageElement(uint16(i)) inode.pgid = elem.pgid inode.key = elem.key() } _assert(len(inode.key) > 0, "read: zero-length inode key") } // Save first key so we can find the node in the parent when we spill. if len(n.inodes) > 0 { n.key = n.inodes[0].key _assert(len(n.key) > 0, "read: zero-length node key") } else { n.key = nil } }
go
func (n *node) read(p *page) { n.pgid = p.id n.isLeaf = ((p.flags & leafPageFlag) != 0) n.inodes = make(inodes, int(p.count)) for i := 0; i < int(p.count); i++ { inode := &n.inodes[i] if n.isLeaf { elem := p.leafPageElement(uint16(i)) inode.flags = elem.flags inode.key = elem.key() inode.value = elem.value() } else { elem := p.branchPageElement(uint16(i)) inode.pgid = elem.pgid inode.key = elem.key() } _assert(len(inode.key) > 0, "read: zero-length inode key") } // Save first key so we can find the node in the parent when we spill. if len(n.inodes) > 0 { n.key = n.inodes[0].key _assert(len(n.key) > 0, "read: zero-length node key") } else { n.key = nil } }
[ "func", "(", "n", "*", "node", ")", "read", "(", "p", "*", "page", ")", "{", "n", ".", "pgid", "=", "p", ".", "id", "\n", "n", ".", "isLeaf", "=", "(", "(", "p", ".", "flags", "&", "leafPageFlag", ")", "!=", "0", ")", "\n", "n", ".", "ino...
// read initializes the node from a page.
[ "read", "initializes", "the", "node", "from", "a", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L161-L188
162,338
boltdb/bolt
node.go
write
func (n *node) write(p *page) { // Initialize page. if n.isLeaf { p.flags |= leafPageFlag } else { p.flags |= branchPageFlag } if len(n.inodes) >= 0xFFFF { panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) } p.count = uint16(len(n.inodes)) // Stop here if there are no items to write. if p.count == 0 { return } // Loop over each item and write it to the page. b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] for i, item := range n.inodes { _assert(len(item.key) > 0, "write: zero-length inode key") // Write the page element. if n.isLeaf { elem := p.leafPageElement(uint16(i)) elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) elem.flags = item.flags elem.ksize = uint32(len(item.key)) elem.vsize = uint32(len(item.value)) } else { elem := p.branchPageElement(uint16(i)) elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) elem.ksize = uint32(len(item.key)) elem.pgid = item.pgid _assert(elem.pgid != p.id, "write: circular dependency occurred") } // If the length of key+value is larger than the max allocation size // then we need to reallocate the byte array pointer. // // See: https://github.com/boltdb/bolt/pull/335 klen, vlen := len(item.key), len(item.value) if len(b) < klen+vlen { b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] } // Write data for the element to the end of the page. copy(b[0:], item.key) b = b[klen:] copy(b[0:], item.value) b = b[vlen:] } // DEBUG ONLY: n.dump() }
go
func (n *node) write(p *page) { // Initialize page. if n.isLeaf { p.flags |= leafPageFlag } else { p.flags |= branchPageFlag } if len(n.inodes) >= 0xFFFF { panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) } p.count = uint16(len(n.inodes)) // Stop here if there are no items to write. if p.count == 0 { return } // Loop over each item and write it to the page. b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] for i, item := range n.inodes { _assert(len(item.key) > 0, "write: zero-length inode key") // Write the page element. if n.isLeaf { elem := p.leafPageElement(uint16(i)) elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) elem.flags = item.flags elem.ksize = uint32(len(item.key)) elem.vsize = uint32(len(item.value)) } else { elem := p.branchPageElement(uint16(i)) elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) elem.ksize = uint32(len(item.key)) elem.pgid = item.pgid _assert(elem.pgid != p.id, "write: circular dependency occurred") } // If the length of key+value is larger than the max allocation size // then we need to reallocate the byte array pointer. // // See: https://github.com/boltdb/bolt/pull/335 klen, vlen := len(item.key), len(item.value) if len(b) < klen+vlen { b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] } // Write data for the element to the end of the page. copy(b[0:], item.key) b = b[klen:] copy(b[0:], item.value) b = b[vlen:] } // DEBUG ONLY: n.dump() }
[ "func", "(", "n", "*", "node", ")", "write", "(", "p", "*", "page", ")", "{", "// Initialize page.", "if", "n", ".", "isLeaf", "{", "p", ".", "flags", "|=", "leafPageFlag", "\n", "}", "else", "{", "p", ".", "flags", "|=", "branchPageFlag", "\n", "}...
// write writes the items onto one or more pages.
[ "write", "writes", "the", "items", "onto", "one", "or", "more", "pages", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L191-L246
162,339
boltdb/bolt
node.go
spill
func (n *node) spill() error { var tx = n.bucket.tx if n.spilled { return nil } // Spill child nodes first. Child nodes can materialize sibling nodes in // the case of split-merge so we cannot use a range loop. We have to check // the children size on every loop iteration. sort.Sort(n.children) for i := 0; i < len(n.children); i++ { if err := n.children[i].spill(); err != nil { return err } } // We no longer need the child list because it's only used for spill tracking. n.children = nil // Split nodes into appropriate sizes. The first node will always be n. var nodes = n.split(tx.db.pageSize) for _, node := range nodes { // Add node's page to the freelist if it's not new. if node.pgid > 0 { tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) node.pgid = 0 } // Allocate contiguous space for the node. p, err := tx.allocate((node.size() / tx.db.pageSize) + 1) if err != nil { return err } // Write the node. if p.id >= tx.meta.pgid { panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) } node.pgid = p.id node.write(p) node.spilled = true // Insert into parent inodes. if node.parent != nil { var key = node.key if key == nil { key = node.inodes[0].key } node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) node.key = node.inodes[0].key _assert(len(node.key) > 0, "spill: zero-length node key") } // Update the statistics. tx.stats.Spill++ } // If the root node split and created a new root then we need to spill that // as well. We'll clear out the children to make sure it doesn't try to respill. if n.parent != nil && n.parent.pgid == 0 { n.children = nil return n.parent.spill() } return nil }
go
func (n *node) spill() error { var tx = n.bucket.tx if n.spilled { return nil } // Spill child nodes first. Child nodes can materialize sibling nodes in // the case of split-merge so we cannot use a range loop. We have to check // the children size on every loop iteration. sort.Sort(n.children) for i := 0; i < len(n.children); i++ { if err := n.children[i].spill(); err != nil { return err } } // We no longer need the child list because it's only used for spill tracking. n.children = nil // Split nodes into appropriate sizes. The first node will always be n. var nodes = n.split(tx.db.pageSize) for _, node := range nodes { // Add node's page to the freelist if it's not new. if node.pgid > 0 { tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) node.pgid = 0 } // Allocate contiguous space for the node. p, err := tx.allocate((node.size() / tx.db.pageSize) + 1) if err != nil { return err } // Write the node. if p.id >= tx.meta.pgid { panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) } node.pgid = p.id node.write(p) node.spilled = true // Insert into parent inodes. if node.parent != nil { var key = node.key if key == nil { key = node.inodes[0].key } node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) node.key = node.inodes[0].key _assert(len(node.key) > 0, "spill: zero-length node key") } // Update the statistics. tx.stats.Spill++ } // If the root node split and created a new root then we need to spill that // as well. We'll clear out the children to make sure it doesn't try to respill. if n.parent != nil && n.parent.pgid == 0 { n.children = nil return n.parent.spill() } return nil }
[ "func", "(", "n", "*", "node", ")", "spill", "(", ")", "error", "{", "var", "tx", "=", "n", ".", "bucket", ".", "tx", "\n", "if", "n", ".", "spilled", "{", "return", "nil", "\n", "}", "\n\n", "// Spill child nodes first. Child nodes can materialize sibling...
// spill writes the nodes to dirty pages and splits nodes as it goes. // Returns an error if dirty pages cannot be allocated.
[ "spill", "writes", "the", "nodes", "to", "dirty", "pages", "and", "splits", "nodes", "as", "it", "goes", ".", "Returns", "an", "error", "if", "dirty", "pages", "cannot", "be", "allocated", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L339-L405
162,340
boltdb/bolt
node.go
removeChild
func (n *node) removeChild(target *node) { for i, child := range n.children { if child == target { n.children = append(n.children[:i], n.children[i+1:]...) return } } }
go
func (n *node) removeChild(target *node) { for i, child := range n.children { if child == target { n.children = append(n.children[:i], n.children[i+1:]...) return } } }
[ "func", "(", "n", "*", "node", ")", "removeChild", "(", "target", "*", "node", ")", "{", "for", "i", ",", "child", ":=", "range", "n", ".", "children", "{", "if", "child", "==", "target", "{", "n", ".", "children", "=", "append", "(", "n", ".", ...
// removes a node from the list of in-memory children. // This does not affect the inodes.
[ "removes", "a", "node", "from", "the", "list", "of", "in", "-", "memory", "children", ".", "This", "does", "not", "affect", "the", "inodes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L512-L519
162,341
boltdb/bolt
node.go
free
func (n *node) free() { if n.pgid != 0 { n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) n.pgid = 0 } }
go
func (n *node) free() { if n.pgid != 0 { n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) n.pgid = 0 } }
[ "func", "(", "n", "*", "node", ")", "free", "(", ")", "{", "if", "n", ".", "pgid", "!=", "0", "{", "n", ".", "bucket", ".", "tx", ".", "db", ".", "freelist", ".", "free", "(", "n", ".", "bucket", ".", "tx", ".", "meta", ".", "txid", ",", ...
// free adds the node's underlying page to the freelist.
[ "free", "adds", "the", "node", "s", "underlying", "page", "to", "the", "freelist", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/node.go#L554-L559
162,342
boltdb/bolt
bucket.go
newBucket
func newBucket(tx *Tx) Bucket { var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} if tx.writable { b.buckets = make(map[string]*Bucket) b.nodes = make(map[pgid]*node) } return b }
go
func newBucket(tx *Tx) Bucket { var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} if tx.writable { b.buckets = make(map[string]*Bucket) b.nodes = make(map[pgid]*node) } return b }
[ "func", "newBucket", "(", "tx", "*", "Tx", ")", "Bucket", "{", "var", "b", "=", "Bucket", "{", "tx", ":", "tx", ",", "FillPercent", ":", "DefaultFillPercent", "}", "\n", "if", "tx", ".", "writable", "{", "b", ".", "buckets", "=", "make", "(", "map"...
// newBucket returns a new bucket associated with a transaction.
[ "newBucket", "returns", "a", "new", "bucket", "associated", "with", "a", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L62-L69
162,343
boltdb/bolt
bucket.go
Cursor
func (b *Bucket) Cursor() *Cursor { // Update transaction statistics. b.tx.stats.CursorCount++ // Allocate and return a cursor. return &Cursor{ bucket: b, stack: make([]elemRef, 0), } }
go
func (b *Bucket) Cursor() *Cursor { // Update transaction statistics. b.tx.stats.CursorCount++ // Allocate and return a cursor. return &Cursor{ bucket: b, stack: make([]elemRef, 0), } }
[ "func", "(", "b", "*", "Bucket", ")", "Cursor", "(", ")", "*", "Cursor", "{", "// Update transaction statistics.", "b", ".", "tx", ".", "stats", ".", "CursorCount", "++", "\n\n", "// Allocate and return a cursor.", "return", "&", "Cursor", "{", "bucket", ":", ...
// Cursor creates a cursor associated with the bucket. // The cursor is only valid as long as the transaction is open. // Do not use a cursor after the transaction is closed.
[ "Cursor", "creates", "a", "cursor", "associated", "with", "the", "bucket", ".", "The", "cursor", "is", "only", "valid", "as", "long", "as", "the", "transaction", "is", "open", ".", "Do", "not", "use", "a", "cursor", "after", "the", "transaction", "is", "...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L89-L98
162,344
boltdb/bolt
bucket.go
Bucket
func (b *Bucket) Bucket(name []byte) *Bucket { if b.buckets != nil { if child := b.buckets[string(name)]; child != nil { return child } } // Move cursor to key. c := b.Cursor() k, v, flags := c.seek(name) // Return nil if the key doesn't exist or it is not a bucket. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { return nil } // Otherwise create a bucket and cache it. var child = b.openBucket(v) if b.buckets != nil { b.buckets[string(name)] = child } return child }
go
func (b *Bucket) Bucket(name []byte) *Bucket { if b.buckets != nil { if child := b.buckets[string(name)]; child != nil { return child } } // Move cursor to key. c := b.Cursor() k, v, flags := c.seek(name) // Return nil if the key doesn't exist or it is not a bucket. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { return nil } // Otherwise create a bucket and cache it. var child = b.openBucket(v) if b.buckets != nil { b.buckets[string(name)] = child } return child }
[ "func", "(", "b", "*", "Bucket", ")", "Bucket", "(", "name", "[", "]", "byte", ")", "*", "Bucket", "{", "if", "b", ".", "buckets", "!=", "nil", "{", "if", "child", ":=", "b", ".", "buckets", "[", "string", "(", "name", ")", "]", ";", "child", ...
// Bucket retrieves a nested bucket by name. // Returns nil if the bucket does not exist. // The bucket instance is only valid for the lifetime of the transaction.
[ "Bucket", "retrieves", "a", "nested", "bucket", "by", "name", ".", "Returns", "nil", "if", "the", "bucket", "does", "not", "exist", ".", "The", "bucket", "instance", "is", "only", "valid", "for", "the", "lifetime", "of", "the", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L103-L126
162,345
boltdb/bolt
bucket.go
openBucket
func (b *Bucket) openBucket(value []byte) *Bucket { var child = newBucket(b.tx) // If unaligned load/stores are broken on this arch and value is // unaligned simply clone to an aligned byte array. unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 if unaligned { value = cloneBytes(value) } // If this is a writable transaction then we need to copy the bucket entry. // Read-only transactions can point directly at the mmap entry. if b.tx.writable && !unaligned { child.bucket = &bucket{} *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) } else { child.bucket = (*bucket)(unsafe.Pointer(&value[0])) } // Save a reference to the inline page if the bucket is inline. if child.root == 0 { child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) } return &child }
go
func (b *Bucket) openBucket(value []byte) *Bucket { var child = newBucket(b.tx) // If unaligned load/stores are broken on this arch and value is // unaligned simply clone to an aligned byte array. unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 if unaligned { value = cloneBytes(value) } // If this is a writable transaction then we need to copy the bucket entry. // Read-only transactions can point directly at the mmap entry. if b.tx.writable && !unaligned { child.bucket = &bucket{} *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) } else { child.bucket = (*bucket)(unsafe.Pointer(&value[0])) } // Save a reference to the inline page if the bucket is inline. if child.root == 0 { child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) } return &child }
[ "func", "(", "b", "*", "Bucket", ")", "openBucket", "(", "value", "[", "]", "byte", ")", "*", "Bucket", "{", "var", "child", "=", "newBucket", "(", "b", ".", "tx", ")", "\n\n", "// If unaligned load/stores are broken on this arch and value is", "// unaligned sim...
// Helper method that re-interprets a sub-bucket value // from a parent into a Bucket
[ "Helper", "method", "that", "re", "-", "interprets", "a", "sub", "-", "bucket", "value", "from", "a", "parent", "into", "a", "Bucket" ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L130-L156
162,346
boltdb/bolt
bucket.go
CreateBucketIfNotExists
func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { child, err := b.CreateBucket(key) if err == ErrBucketExists { return b.Bucket(key), nil } else if err != nil { return nil, err } return child, nil }
go
func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { child, err := b.CreateBucket(key) if err == ErrBucketExists { return b.Bucket(key), nil } else if err != nil { return nil, err } return child, nil }
[ "func", "(", "b", "*", "Bucket", ")", "CreateBucketIfNotExists", "(", "key", "[", "]", "byte", ")", "(", "*", "Bucket", ",", "error", ")", "{", "child", ",", "err", ":=", "b", ".", "CreateBucket", "(", "key", ")", "\n", "if", "err", "==", "ErrBucke...
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. // Returns an error if the bucket name is blank, or if the bucket name is too long. // The bucket instance is only valid for the lifetime of the transaction.
[ "CreateBucketIfNotExists", "creates", "a", "new", "bucket", "if", "it", "doesn", "t", "already", "exist", "and", "returns", "a", "reference", "to", "it", ".", "Returns", "an", "error", "if", "the", "bucket", "name", "is", "blank", "or", "if", "the", "bucke...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L205-L213
162,347
boltdb/bolt
bucket.go
DeleteBucket
func (b *Bucket) DeleteBucket(key []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if bucket doesn't exist or is not a bucket. if !bytes.Equal(key, k) { return ErrBucketNotFound } else if (flags & bucketLeafFlag) == 0 { return ErrIncompatibleValue } // Recursively delete all child buckets. child := b.Bucket(key) err := child.ForEach(func(k, v []byte) error { if v == nil { if err := child.DeleteBucket(k); err != nil { return fmt.Errorf("delete bucket: %s", err) } } return nil }) if err != nil { return err } // Remove cached copy. delete(b.buckets, string(key)) // Release all bucket pages to freelist. child.nodes = nil child.rootNode = nil child.free() // Delete the node if we have a matching key. c.node().del(key) return nil }
go
func (b *Bucket) DeleteBucket(key []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if bucket doesn't exist or is not a bucket. if !bytes.Equal(key, k) { return ErrBucketNotFound } else if (flags & bucketLeafFlag) == 0 { return ErrIncompatibleValue } // Recursively delete all child buckets. child := b.Bucket(key) err := child.ForEach(func(k, v []byte) error { if v == nil { if err := child.DeleteBucket(k); err != nil { return fmt.Errorf("delete bucket: %s", err) } } return nil }) if err != nil { return err } // Remove cached copy. delete(b.buckets, string(key)) // Release all bucket pages to freelist. child.nodes = nil child.rootNode = nil child.free() // Delete the node if we have a matching key. c.node().del(key) return nil }
[ "func", "(", "b", "*", "Bucket", ")", "DeleteBucket", "(", "key", "[", "]", "byte", ")", "error", "{", "if", "b", ".", "tx", ".", "db", "==", "nil", "{", "return", "ErrTxClosed", "\n", "}", "else", "if", "!", "b", ".", "Writable", "(", ")", "{"...
// DeleteBucket deletes a bucket at the given key. // Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
[ "DeleteBucket", "deletes", "a", "bucket", "at", "the", "given", "key", ".", "Returns", "an", "error", "if", "the", "bucket", "does", "not", "exists", "or", "if", "the", "key", "represents", "a", "non", "-", "bucket", "value", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L217-L261
162,348
boltdb/bolt
bucket.go
Get
func (b *Bucket) Get(key []byte) []byte { k, v, flags := b.Cursor().seek(key) // Return nil if this is a bucket. if (flags & bucketLeafFlag) != 0 { return nil } // If our target node isn't the same key as what's passed in then return nil. if !bytes.Equal(key, k) { return nil } return v }
go
func (b *Bucket) Get(key []byte) []byte { k, v, flags := b.Cursor().seek(key) // Return nil if this is a bucket. if (flags & bucketLeafFlag) != 0 { return nil } // If our target node isn't the same key as what's passed in then return nil. if !bytes.Equal(key, k) { return nil } return v }
[ "func", "(", "b", "*", "Bucket", ")", "Get", "(", "key", "[", "]", "byte", ")", "[", "]", "byte", "{", "k", ",", "v", ",", "flags", ":=", "b", ".", "Cursor", "(", ")", ".", "seek", "(", "key", ")", "\n\n", "// Return nil if this is a bucket.", "i...
// Get retrieves the value for a key in the bucket. // Returns a nil value if the key does not exist or if the key is a nested bucket. // The returned value is only valid for the life of the transaction.
[ "Get", "retrieves", "the", "value", "for", "a", "key", "in", "the", "bucket", ".", "Returns", "a", "nil", "value", "if", "the", "key", "does", "not", "exist", "or", "if", "the", "key", "is", "a", "nested", "bucket", ".", "The", "returned", "value", "...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L266-L279
162,349
boltdb/bolt
bucket.go
Put
func (b *Bucket) Put(key []byte, value []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } else if len(key) == 0 { return ErrKeyRequired } else if len(key) > MaxKeySize { return ErrKeyTooLarge } else if int64(len(value)) > MaxValueSize { return ErrValueTooLarge } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if there is an existing key with a bucket value. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { return ErrIncompatibleValue } // Insert into node. key = cloneBytes(key) c.node().put(key, key, value, 0, 0) return nil }
go
func (b *Bucket) Put(key []byte, value []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } else if len(key) == 0 { return ErrKeyRequired } else if len(key) > MaxKeySize { return ErrKeyTooLarge } else if int64(len(value)) > MaxValueSize { return ErrValueTooLarge } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if there is an existing key with a bucket value. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { return ErrIncompatibleValue } // Insert into node. key = cloneBytes(key) c.node().put(key, key, value, 0, 0) return nil }
[ "func", "(", "b", "*", "Bucket", ")", "Put", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "error", "{", "if", "b", ".", "tx", ".", "db", "==", "nil", "{", "return", "ErrTxClosed", "\n", "}", "else", "if", "!", "b", ".", ...
// Put sets the value for a key in the bucket. // If the key exist then its previous value will be overwritten. // Supplied value must remain valid for the life of the transaction. // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
[ "Put", "sets", "the", "value", "for", "a", "key", "in", "the", "bucket", ".", "If", "the", "key", "exist", "then", "its", "previous", "value", "will", "be", "overwritten", ".", "Supplied", "value", "must", "remain", "valid", "for", "the", "life", "of", ...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L285-L312
162,350
boltdb/bolt
bucket.go
SetSequence
func (b *Bucket) SetSequence(v uint64) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Materialize the root node if it hasn't been already so that the // bucket will be saved during commit. if b.rootNode == nil { _ = b.node(b.root, nil) } // Increment and return the sequence. b.bucket.sequence = v return nil }
go
func (b *Bucket) SetSequence(v uint64) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Materialize the root node if it hasn't been already so that the // bucket will be saved during commit. if b.rootNode == nil { _ = b.node(b.root, nil) } // Increment and return the sequence. b.bucket.sequence = v return nil }
[ "func", "(", "b", "*", "Bucket", ")", "SetSequence", "(", "v", "uint64", ")", "error", "{", "if", "b", ".", "tx", ".", "db", "==", "nil", "{", "return", "ErrTxClosed", "\n", "}", "else", "if", "!", "b", ".", "Writable", "(", ")", "{", "return", ...
// SetSequence updates the sequence number for the bucket.
[ "SetSequence", "updates", "the", "sequence", "number", "for", "the", "bucket", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L343-L359
162,351
boltdb/bolt
bucket.go
Stats
func (b *Bucket) Stats() BucketStats { var s, subStats BucketStats pageSize := b.tx.db.pageSize s.BucketN += 1 if b.root == 0 { s.InlineBucketN += 1 } b.forEachPage(func(p *page, depth int) { if (p.flags & leafPageFlag) != 0 { s.KeyN += int(p.count) // used totals the used bytes for the page used := pageHeaderSize if p.count != 0 { // If page has any elements, add all element headers. used += leafPageElementSize * int(p.count-1) // Add all element key, value sizes. // The computation takes advantage of the fact that the position // of the last element's key/value equals to the total of the sizes // of all previous elements' keys and values. // It also includes the last element's header. lastElement := p.leafPageElement(p.count - 1) used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) } if b.root == 0 { // For inlined bucket just update the inline stats s.InlineBucketInuse += used } else { // For non-inlined bucket update all the leaf stats s.LeafPageN++ s.LeafInuse += used s.LeafOverflowN += int(p.overflow) // Collect stats from sub-buckets. // Do that by iterating over all element headers // looking for the ones with the bucketLeafFlag. for i := uint16(0); i < p.count; i++ { e := p.leafPageElement(i) if (e.flags & bucketLeafFlag) != 0 { // For any bucket element, open the element value // and recursively call Stats on the contained bucket. subStats.Add(b.openBucket(e.value()).Stats()) } } } } else if (p.flags & branchPageFlag) != 0 { s.BranchPageN++ lastElement := p.branchPageElement(p.count - 1) // used totals the used bytes for the page // Add header and all element headers. used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) // Add size of all keys and values. // Again, use the fact that last element's position equals to // the total of key, value sizes of all previous elements. used += int(lastElement.pos + lastElement.ksize) s.BranchInuse += used s.BranchOverflowN += int(p.overflow) } // Keep track of maximum page depth. if depth+1 > s.Depth { s.Depth = (depth + 1) } }) // Alloc stats can be computed from page counts and pageSize. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize // Add the max depth of sub-buckets to get total nested depth. s.Depth += subStats.Depth // Add the stats for all sub-buckets s.Add(subStats) return s }
go
func (b *Bucket) Stats() BucketStats { var s, subStats BucketStats pageSize := b.tx.db.pageSize s.BucketN += 1 if b.root == 0 { s.InlineBucketN += 1 } b.forEachPage(func(p *page, depth int) { if (p.flags & leafPageFlag) != 0 { s.KeyN += int(p.count) // used totals the used bytes for the page used := pageHeaderSize if p.count != 0 { // If page has any elements, add all element headers. used += leafPageElementSize * int(p.count-1) // Add all element key, value sizes. // The computation takes advantage of the fact that the position // of the last element's key/value equals to the total of the sizes // of all previous elements' keys and values. // It also includes the last element's header. lastElement := p.leafPageElement(p.count - 1) used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) } if b.root == 0 { // For inlined bucket just update the inline stats s.InlineBucketInuse += used } else { // For non-inlined bucket update all the leaf stats s.LeafPageN++ s.LeafInuse += used s.LeafOverflowN += int(p.overflow) // Collect stats from sub-buckets. // Do that by iterating over all element headers // looking for the ones with the bucketLeafFlag. for i := uint16(0); i < p.count; i++ { e := p.leafPageElement(i) if (e.flags & bucketLeafFlag) != 0 { // For any bucket element, open the element value // and recursively call Stats on the contained bucket. subStats.Add(b.openBucket(e.value()).Stats()) } } } } else if (p.flags & branchPageFlag) != 0 { s.BranchPageN++ lastElement := p.branchPageElement(p.count - 1) // used totals the used bytes for the page // Add header and all element headers. used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) // Add size of all keys and values. // Again, use the fact that last element's position equals to // the total of key, value sizes of all previous elements. used += int(lastElement.pos + lastElement.ksize) s.BranchInuse += used s.BranchOverflowN += int(p.overflow) } // Keep track of maximum page depth. if depth+1 > s.Depth { s.Depth = (depth + 1) } }) // Alloc stats can be computed from page counts and pageSize. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize // Add the max depth of sub-buckets to get total nested depth. s.Depth += subStats.Depth // Add the stats for all sub-buckets s.Add(subStats) return s }
[ "func", "(", "b", "*", "Bucket", ")", "Stats", "(", ")", "BucketStats", "{", "var", "s", ",", "subStats", "BucketStats", "\n", "pageSize", ":=", "b", ".", "tx", ".", "db", ".", "pageSize", "\n", "s", ".", "BucketN", "+=", "1", "\n", "if", "b", "....
// Stat returns stats on a bucket.
[ "Stat", "returns", "stats", "on", "a", "bucket", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L398-L477
162,352
boltdb/bolt
bucket.go
forEachPage
func (b *Bucket) forEachPage(fn func(*page, int)) { // If we have an inline page then just use that. if b.page != nil { fn(b.page, 0) return } // Otherwise traverse the page hierarchy. b.tx.forEachPage(b.root, 0, fn) }
go
func (b *Bucket) forEachPage(fn func(*page, int)) { // If we have an inline page then just use that. if b.page != nil { fn(b.page, 0) return } // Otherwise traverse the page hierarchy. b.tx.forEachPage(b.root, 0, fn) }
[ "func", "(", "b", "*", "Bucket", ")", "forEachPage", "(", "fn", "func", "(", "*", "page", ",", "int", ")", ")", "{", "// If we have an inline page then just use that.", "if", "b", ".", "page", "!=", "nil", "{", "fn", "(", "b", ".", "page", ",", "0", ...
// forEachPage iterates over every page in a bucket, including inline pages.
[ "forEachPage", "iterates", "over", "every", "page", "in", "a", "bucket", "including", "inline", "pages", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L480-L489
162,353
boltdb/bolt
bucket.go
spill
func (b *Bucket) spill() error { // Spill all child buckets first. for name, child := range b.buckets { // If the child bucket is small enough and it has no child buckets then // write it inline into the parent bucket's page. Otherwise spill it // like a normal bucket and make the parent value a pointer to the page. var value []byte if child.inlineable() { child.free() value = child.write() } else { if err := child.spill(); err != nil { return err } // Update the child bucket header in this bucket. value = make([]byte, unsafe.Sizeof(bucket{})) var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *child.bucket } // Skip writing the bucket if there are no materialized nodes. if child.rootNode == nil { continue } // Update parent node. var c = b.Cursor() k, _, flags := c.seek([]byte(name)) if !bytes.Equal([]byte(name), k) { panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) } if flags&bucketLeafFlag == 0 { panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) } c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) } // Ignore if there's not a materialized root node. if b.rootNode == nil { return nil } // Spill nodes. if err := b.rootNode.spill(); err != nil { return err } b.rootNode = b.rootNode.root() // Update the root node for this bucket. if b.rootNode.pgid >= b.tx.meta.pgid { panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) } b.root = b.rootNode.pgid return nil }
go
func (b *Bucket) spill() error { // Spill all child buckets first. for name, child := range b.buckets { // If the child bucket is small enough and it has no child buckets then // write it inline into the parent bucket's page. Otherwise spill it // like a normal bucket and make the parent value a pointer to the page. var value []byte if child.inlineable() { child.free() value = child.write() } else { if err := child.spill(); err != nil { return err } // Update the child bucket header in this bucket. value = make([]byte, unsafe.Sizeof(bucket{})) var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *child.bucket } // Skip writing the bucket if there are no materialized nodes. if child.rootNode == nil { continue } // Update parent node. var c = b.Cursor() k, _, flags := c.seek([]byte(name)) if !bytes.Equal([]byte(name), k) { panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) } if flags&bucketLeafFlag == 0 { panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) } c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) } // Ignore if there's not a materialized root node. if b.rootNode == nil { return nil } // Spill nodes. if err := b.rootNode.spill(); err != nil { return err } b.rootNode = b.rootNode.root() // Update the root node for this bucket. if b.rootNode.pgid >= b.tx.meta.pgid { panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) } b.root = b.rootNode.pgid return nil }
[ "func", "(", "b", "*", "Bucket", ")", "spill", "(", ")", "error", "{", "// Spill all child buckets first.", "for", "name", ",", "child", ":=", "range", "b", ".", "buckets", "{", "// If the child bucket is small enough and it has no child buckets then", "// write it inli...
// spill writes all the nodes for this bucket to dirty pages.
[ "spill", "writes", "all", "the", "nodes", "for", "this", "bucket", "to", "dirty", "pages", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L526-L582
162,354
boltdb/bolt
bucket.go
inlineable
func (b *Bucket) inlineable() bool { var n = b.rootNode // Bucket must only contain a single leaf node. if n == nil || !n.isLeaf { return false } // Bucket is not inlineable if it contains subbuckets or if it goes beyond // our threshold for inline bucket size. var size = pageHeaderSize for _, inode := range n.inodes { size += leafPageElementSize + len(inode.key) + len(inode.value) if inode.flags&bucketLeafFlag != 0 { return false } else if size > b.maxInlineBucketSize() { return false } } return true }
go
func (b *Bucket) inlineable() bool { var n = b.rootNode // Bucket must only contain a single leaf node. if n == nil || !n.isLeaf { return false } // Bucket is not inlineable if it contains subbuckets or if it goes beyond // our threshold for inline bucket size. var size = pageHeaderSize for _, inode := range n.inodes { size += leafPageElementSize + len(inode.key) + len(inode.value) if inode.flags&bucketLeafFlag != 0 { return false } else if size > b.maxInlineBucketSize() { return false } } return true }
[ "func", "(", "b", "*", "Bucket", ")", "inlineable", "(", ")", "bool", "{", "var", "n", "=", "b", ".", "rootNode", "\n\n", "// Bucket must only contain a single leaf node.", "if", "n", "==", "nil", "||", "!", "n", ".", "isLeaf", "{", "return", "false", "\...
// inlineable returns true if a bucket is small enough to be written inline // and if it contains no subbuckets. Otherwise returns false.
[ "inlineable", "returns", "true", "if", "a", "bucket", "is", "small", "enough", "to", "be", "written", "inline", "and", "if", "it", "contains", "no", "subbuckets", ".", "Otherwise", "returns", "false", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L586-L608
162,355
boltdb/bolt
bucket.go
write
func (b *Bucket) write() []byte { // Allocate the appropriate size. var n = b.rootNode var value = make([]byte, bucketHeaderSize+n.size()) // Write a bucket header. var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *b.bucket // Convert byte slice to a fake page and write the root node. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) n.write(p) return value }
go
func (b *Bucket) write() []byte { // Allocate the appropriate size. var n = b.rootNode var value = make([]byte, bucketHeaderSize+n.size()) // Write a bucket header. var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *b.bucket // Convert byte slice to a fake page and write the root node. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) n.write(p) return value }
[ "func", "(", "b", "*", "Bucket", ")", "write", "(", ")", "[", "]", "byte", "{", "// Allocate the appropriate size.", "var", "n", "=", "b", ".", "rootNode", "\n", "var", "value", "=", "make", "(", "[", "]", "byte", ",", "bucketHeaderSize", "+", "n", "...
// write allocates and writes a bucket to a byte slice.
[ "write", "allocates", "and", "writes", "a", "bucket", "to", "a", "byte", "slice", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L616-L630
162,356
boltdb/bolt
bucket.go
rebalance
func (b *Bucket) rebalance() { for _, n := range b.nodes { n.rebalance() } for _, child := range b.buckets { child.rebalance() } }
go
func (b *Bucket) rebalance() { for _, n := range b.nodes { n.rebalance() } for _, child := range b.buckets { child.rebalance() } }
[ "func", "(", "b", "*", "Bucket", ")", "rebalance", "(", ")", "{", "for", "_", ",", "n", ":=", "range", "b", ".", "nodes", "{", "n", ".", "rebalance", "(", ")", "\n", "}", "\n", "for", "_", ",", "child", ":=", "range", "b", ".", "buckets", "{"...
// rebalance attempts to balance all nodes.
[ "rebalance", "attempts", "to", "balance", "all", "nodes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L633-L640
162,357
boltdb/bolt
bucket.go
node
func (b *Bucket) node(pgid pgid, parent *node) *node { _assert(b.nodes != nil, "nodes map expected") // Retrieve node if it's already been created. if n := b.nodes[pgid]; n != nil { return n } // Otherwise create a node and cache it. n := &node{bucket: b, parent: parent} if parent == nil { b.rootNode = n } else { parent.children = append(parent.children, n) } // Use the inline page if this is an inline bucket. var p = b.page if p == nil { p = b.tx.page(pgid) } // Read the page into the node and cache it. n.read(p) b.nodes[pgid] = n // Update statistics. b.tx.stats.NodeCount++ return n }
go
func (b *Bucket) node(pgid pgid, parent *node) *node { _assert(b.nodes != nil, "nodes map expected") // Retrieve node if it's already been created. if n := b.nodes[pgid]; n != nil { return n } // Otherwise create a node and cache it. n := &node{bucket: b, parent: parent} if parent == nil { b.rootNode = n } else { parent.children = append(parent.children, n) } // Use the inline page if this is an inline bucket. var p = b.page if p == nil { p = b.tx.page(pgid) } // Read the page into the node and cache it. n.read(p) b.nodes[pgid] = n // Update statistics. b.tx.stats.NodeCount++ return n }
[ "func", "(", "b", "*", "Bucket", ")", "node", "(", "pgid", "pgid", ",", "parent", "*", "node", ")", "*", "node", "{", "_assert", "(", "b", ".", "nodes", "!=", "nil", ",", "\"", "\"", ")", "\n\n", "// Retrieve node if it's already been created.", "if", ...
// node creates a node from a page and associates it with a given parent.
[ "node", "creates", "a", "node", "from", "a", "page", "and", "associates", "it", "with", "a", "given", "parent", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L643-L673
162,358
boltdb/bolt
bucket.go
free
func (b *Bucket) free() { if b.root == 0 { return } var tx = b.tx b.forEachPageNode(func(p *page, n *node, _ int) { if p != nil { tx.db.freelist.free(tx.meta.txid, p) } else { n.free() } }) b.root = 0 }
go
func (b *Bucket) free() { if b.root == 0 { return } var tx = b.tx b.forEachPageNode(func(p *page, n *node, _ int) { if p != nil { tx.db.freelist.free(tx.meta.txid, p) } else { n.free() } }) b.root = 0 }
[ "func", "(", "b", "*", "Bucket", ")", "free", "(", ")", "{", "if", "b", ".", "root", "==", "0", "{", "return", "\n", "}", "\n\n", "var", "tx", "=", "b", ".", "tx", "\n", "b", ".", "forEachPageNode", "(", "func", "(", "p", "*", "page", ",", ...
// free recursively frees all pages in the bucket.
[ "free", "recursively", "frees", "all", "pages", "in", "the", "bucket", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L676-L690
162,359
boltdb/bolt
bucket.go
dereference
func (b *Bucket) dereference() { if b.rootNode != nil { b.rootNode.root().dereference() } for _, child := range b.buckets { child.dereference() } }
go
func (b *Bucket) dereference() { if b.rootNode != nil { b.rootNode.root().dereference() } for _, child := range b.buckets { child.dereference() } }
[ "func", "(", "b", "*", "Bucket", ")", "dereference", "(", ")", "{", "if", "b", ".", "rootNode", "!=", "nil", "{", "b", ".", "rootNode", ".", "root", "(", ")", ".", "dereference", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "child", ":=", "ran...
// dereference removes all references to the old mmap.
[ "dereference", "removes", "all", "references", "to", "the", "old", "mmap", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L693-L701
162,360
boltdb/bolt
bucket.go
pageNode
func (b *Bucket) pageNode(id pgid) (*page, *node) { // Inline buckets have a fake page embedded in their value so treat them // differently. We'll return the rootNode (if available) or the fake page. if b.root == 0 { if id != 0 { panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) } if b.rootNode != nil { return nil, b.rootNode } return b.page, nil } // Check the node cache for non-inline buckets. if b.nodes != nil { if n := b.nodes[id]; n != nil { return nil, n } } // Finally lookup the page from the transaction if no node is materialized. return b.tx.page(id), nil }
go
func (b *Bucket) pageNode(id pgid) (*page, *node) { // Inline buckets have a fake page embedded in their value so treat them // differently. We'll return the rootNode (if available) or the fake page. if b.root == 0 { if id != 0 { panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) } if b.rootNode != nil { return nil, b.rootNode } return b.page, nil } // Check the node cache for non-inline buckets. if b.nodes != nil { if n := b.nodes[id]; n != nil { return nil, n } } // Finally lookup the page from the transaction if no node is materialized. return b.tx.page(id), nil }
[ "func", "(", "b", "*", "Bucket", ")", "pageNode", "(", "id", "pgid", ")", "(", "*", "page", ",", "*", "node", ")", "{", "// Inline buckets have a fake page embedded in their value so treat them", "// differently. We'll return the rootNode (if available) or the fake page.", ...
// pageNode returns the in-memory node, if it exists. // Otherwise returns the underlying page.
[ "pageNode", "returns", "the", "in", "-", "memory", "node", "if", "it", "exists", ".", "Otherwise", "returns", "the", "underlying", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L705-L727
162,361
boltdb/bolt
bucket.go
cloneBytes
func cloneBytes(v []byte) []byte { var clone = make([]byte, len(v)) copy(clone, v) return clone }
go
func cloneBytes(v []byte) []byte { var clone = make([]byte, len(v)) copy(clone, v) return clone }
[ "func", "cloneBytes", "(", "v", "[", "]", "byte", ")", "[", "]", "byte", "{", "var", "clone", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "v", ")", ")", "\n", "copy", "(", "clone", ",", "v", ")", "\n", "return", "clone", "\n", "}" ]
// cloneBytes returns a copy of a given slice.
[ "cloneBytes", "returns", "a", "copy", "of", "a", "given", "slice", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bucket.go#L773-L777
162,362
boltdb/bolt
bolt_unix_solaris.go
mmap
func mmap(db *DB, sz int) error { // Map the data file to memory. b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) if err != nil { return err } // Advise the kernel that the mmap is accessed randomly. if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { return fmt.Errorf("madvise: %s", err) } // Save the original byte slice and convert to a byte array pointer. db.dataref = b db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) db.datasz = sz return nil }
go
func mmap(db *DB, sz int) error { // Map the data file to memory. b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) if err != nil { return err } // Advise the kernel that the mmap is accessed randomly. if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { return fmt.Errorf("madvise: %s", err) } // Save the original byte slice and convert to a byte array pointer. db.dataref = b db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) db.datasz = sz return nil }
[ "func", "mmap", "(", "db", "*", "DB", ",", "sz", "int", ")", "error", "{", "// Map the data file to memory.", "b", ",", "err", ":=", "unix", ".", "Mmap", "(", "int", "(", "db", ".", "file", ".", "Fd", "(", ")", ")", ",", "0", ",", "sz", ",", "s...
// mmap memory maps a DB's data file.
[ "mmap", "memory", "maps", "a", "DB", "s", "data", "file", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bolt_unix_solaris.go#L58-L75
162,363
boltdb/bolt
bolt_unix_solaris.go
munmap
func munmap(db *DB) error { // Ignore the unmap if we have no mapped data. if db.dataref == nil { return nil } // Unmap using the original byte slice. err := unix.Munmap(db.dataref) db.dataref = nil db.data = nil db.datasz = 0 return err }
go
func munmap(db *DB) error { // Ignore the unmap if we have no mapped data. if db.dataref == nil { return nil } // Unmap using the original byte slice. err := unix.Munmap(db.dataref) db.dataref = nil db.data = nil db.datasz = 0 return err }
[ "func", "munmap", "(", "db", "*", "DB", ")", "error", "{", "// Ignore the unmap if we have no mapped data.", "if", "db", ".", "dataref", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Unmap using the original byte slice.", "err", ":=", "unix", ".", "M...
// munmap unmaps a DB's data file from memory.
[ "munmap", "unmaps", "a", "DB", "s", "data", "file", "from", "memory", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bolt_unix_solaris.go#L78-L90
162,364
boltdb/bolt
cursor.go
First
func (c *Cursor) First() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) c.first() // If we land on an empty page then move to the next value. // https://github.com/boltdb/bolt/issues/450 if c.stack[len(c.stack)-1].count() == 0 { c.next() } k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
go
func (c *Cursor) First() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) c.first() // If we land on an empty page then move to the next value. // https://github.com/boltdb/bolt/issues/450 if c.stack[len(c.stack)-1].count() == 0 { c.next() } k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
[ "func", "(", "c", "*", "Cursor", ")", "First", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "_assert", "(", "c", ".", "bucket", ".", "tx", ".", "db", "!=", "nil", ",", "\"", "\"", ")", "\n", "c", ".", ...
// First moves the cursor to the first item in the bucket and returns its key and value. // If the bucket is empty then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction.
[ "First", "moves", "the", "cursor", "to", "the", "first", "item", "in", "the", "bucket", "and", "returns", "its", "key", "and", "value", ".", "If", "the", "bucket", "is", "empty", "then", "a", "nil", "key", "and", "value", "are", "returned", ".", "The",...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L31-L50
162,365
boltdb/bolt
cursor.go
Last
func (c *Cursor) Last() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) ref := elemRef{page: p, node: n} ref.index = ref.count() - 1 c.stack = append(c.stack, ref) c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
go
func (c *Cursor) Last() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) ref := elemRef{page: p, node: n} ref.index = ref.count() - 1 c.stack = append(c.stack, ref) c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
[ "func", "(", "c", "*", "Cursor", ")", "Last", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "_assert", "(", "c", ".", "bucket", ".", "tx", ".", "db", "!=", "nil", ",", "\"", "\"", ")", "\n", "c", ".", "...
// Last moves the cursor to the last item in the bucket and returns its key and value. // If the bucket is empty then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction.
[ "Last", "moves", "the", "cursor", "to", "the", "last", "item", "in", "the", "bucket", "and", "returns", "its", "key", "and", "value", ".", "If", "the", "bucket", "is", "empty", "then", "a", "nil", "key", "and", "value", "are", "returned", ".", "The", ...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L55-L68
162,366
boltdb/bolt
cursor.go
Next
func (c *Cursor) Next() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") k, v, flags := c.next() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
go
func (c *Cursor) Next() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") k, v, flags := c.next() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
[ "func", "(", "c", "*", "Cursor", ")", "Next", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "_assert", "(", "c", ".", "bucket", ".", "tx", ".", "db", "!=", "nil", ",", "\"", "\"", ")", "\n", "k", ",", "...
// Next moves the cursor to the next item in the bucket and returns its key and value. // If the cursor is at the end of the bucket then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction.
[ "Next", "moves", "the", "cursor", "to", "the", "next", "item", "in", "the", "bucket", "and", "returns", "its", "key", "and", "value", ".", "If", "the", "cursor", "is", "at", "the", "end", "of", "the", "bucket", "then", "a", "nil", "key", "and", "valu...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L73-L80
162,367
boltdb/bolt
cursor.go
Prev
func (c *Cursor) Prev() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") // Attempt to move back one element until we're successful. // Move up the stack as we hit the beginning of each page in our stack. for i := len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index > 0 { elem.index-- break } c.stack = c.stack[:i] } // If we've hit the end then return nil. if len(c.stack) == 0 { return nil, nil } // Move down the stack to find the last element of the last leaf under this branch. c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
go
func (c *Cursor) Prev() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") // Attempt to move back one element until we're successful. // Move up the stack as we hit the beginning of each page in our stack. for i := len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index > 0 { elem.index-- break } c.stack = c.stack[:i] } // If we've hit the end then return nil. if len(c.stack) == 0 { return nil, nil } // Move down the stack to find the last element of the last leaf under this branch. c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
[ "func", "(", "c", "*", "Cursor", ")", "Prev", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "_assert", "(", "c", ".", "bucket", ".", "tx", ".", "db", "!=", "nil", ",", "\"", "\"", ")", "\n\n", "// Attempt t...
// Prev moves the cursor to the previous item in the bucket and returns its key and value. // If the cursor is at the beginning of the bucket then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction.
[ "Prev", "moves", "the", "cursor", "to", "the", "previous", "item", "in", "the", "bucket", "and", "returns", "its", "key", "and", "value", ".", "If", "the", "cursor", "is", "at", "the", "beginning", "of", "the", "bucket", "then", "a", "nil", "key", "and...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L85-L111
162,368
boltdb/bolt
cursor.go
Seek
func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { k, v, flags := c.seek(seek) // If we ended up after the last element of a page then move to the next one. if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { k, v, flags = c.next() } if k == nil { return nil, nil } else if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
go
func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { k, v, flags := c.seek(seek) // If we ended up after the last element of a page then move to the next one. if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { k, v, flags = c.next() } if k == nil { return nil, nil } else if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v }
[ "func", "(", "c", "*", "Cursor", ")", "Seek", "(", "seek", "[", "]", "byte", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "k", ",", "v", ",", "flags", ":=", "c", ".", "seek", "(", "seek", ")", "\n\n", "// If ...
// Seek moves the cursor to a given key and returns it. // If the key does not exist then the next key is used. If no keys // follow, a nil key is returned. // The returned key and value are only valid for the life of the transaction.
[ "Seek", "moves", "the", "cursor", "to", "a", "given", "key", "and", "returns", "it", ".", "If", "the", "key", "does", "not", "exist", "then", "the", "next", "key", "is", "used", ".", "If", "no", "keys", "follow", "a", "nil", "key", "is", "returned", ...
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L117-L131
162,369
boltdb/bolt
cursor.go
seek
func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { _assert(c.bucket.tx.db != nil, "tx closed") // Start from root page/node and traverse to correct page. c.stack = c.stack[:0] c.search(seek, c.bucket.root) ref := &c.stack[len(c.stack)-1] // If the cursor is pointing to the end of page/node then return nil. if ref.index >= ref.count() { return nil, nil, 0 } // If this is a bucket then return a nil value. return c.keyValue() }
go
func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { _assert(c.bucket.tx.db != nil, "tx closed") // Start from root page/node and traverse to correct page. c.stack = c.stack[:0] c.search(seek, c.bucket.root) ref := &c.stack[len(c.stack)-1] // If the cursor is pointing to the end of page/node then return nil. if ref.index >= ref.count() { return nil, nil, 0 } // If this is a bucket then return a nil value. return c.keyValue() }
[ "func", "(", "c", "*", "Cursor", ")", "seek", "(", "seek", "[", "]", "byte", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ",", "flags", "uint32", ")", "{", "_assert", "(", "c", ".", "bucket", ".", "tx", ".", "db", "!=", ...
// seek moves the cursor to a given key and returns it. // If the key does not exist then the next key is used.
[ "seek", "moves", "the", "cursor", "to", "a", "given", "key", "and", "returns", "it", ".", "If", "the", "key", "does", "not", "exist", "then", "the", "next", "key", "is", "used", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L154-L169
162,370
boltdb/bolt
cursor.go
first
func (c *Cursor) first() { for { // Exit when we hit a leaf page. var ref = &c.stack[len(c.stack)-1] if ref.isLeaf() { break } // Keep adding pages pointing to the first element to the stack. var pgid pgid if ref.node != nil { pgid = ref.node.inodes[ref.index].pgid } else { pgid = ref.page.branchPageElement(uint16(ref.index)).pgid } p, n := c.bucket.pageNode(pgid) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) } }
go
func (c *Cursor) first() { for { // Exit when we hit a leaf page. var ref = &c.stack[len(c.stack)-1] if ref.isLeaf() { break } // Keep adding pages pointing to the first element to the stack. var pgid pgid if ref.node != nil { pgid = ref.node.inodes[ref.index].pgid } else { pgid = ref.page.branchPageElement(uint16(ref.index)).pgid } p, n := c.bucket.pageNode(pgid) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) } }
[ "func", "(", "c", "*", "Cursor", ")", "first", "(", ")", "{", "for", "{", "// Exit when we hit a leaf page.", "var", "ref", "=", "&", "c", ".", "stack", "[", "len", "(", "c", ".", "stack", ")", "-", "1", "]", "\n", "if", "ref", ".", "isLeaf", "("...
// first moves the cursor to the first leaf element under the last page in the stack.
[ "first", "moves", "the", "cursor", "to", "the", "first", "leaf", "element", "under", "the", "last", "page", "in", "the", "stack", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L172-L190
162,371
boltdb/bolt
cursor.go
next
func (c *Cursor) next() (key []byte, value []byte, flags uint32) { for { // Attempt to move over one element until we're successful. // Move up the stack as we hit the end of each page in our stack. var i int for i = len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index < elem.count()-1 { elem.index++ break } } // If we've hit the root page then stop and return. This will leave the // cursor on the last element of the last page. if i == -1 { return nil, nil, 0 } // Otherwise start from where we left off in the stack and find the // first element of the first leaf page. c.stack = c.stack[:i+1] c.first() // If this is an empty page then restart and move back up the stack. // https://github.com/boltdb/bolt/issues/450 if c.stack[len(c.stack)-1].count() == 0 { continue } return c.keyValue() } }
go
func (c *Cursor) next() (key []byte, value []byte, flags uint32) { for { // Attempt to move over one element until we're successful. // Move up the stack as we hit the end of each page in our stack. var i int for i = len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index < elem.count()-1 { elem.index++ break } } // If we've hit the root page then stop and return. This will leave the // cursor on the last element of the last page. if i == -1 { return nil, nil, 0 } // Otherwise start from where we left off in the stack and find the // first element of the first leaf page. c.stack = c.stack[:i+1] c.first() // If this is an empty page then restart and move back up the stack. // https://github.com/boltdb/bolt/issues/450 if c.stack[len(c.stack)-1].count() == 0 { continue } return c.keyValue() } }
[ "func", "(", "c", "*", "Cursor", ")", "next", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ",", "flags", "uint32", ")", "{", "for", "{", "// Attempt to move over one element until we're successful.", "// Move up the stack as we hit the...
// next moves to the next leaf element and returns the key and value. // If the cursor is at the last leaf element then it stays there and returns nil.
[ "next", "moves", "to", "the", "next", "leaf", "element", "and", "returns", "the", "key", "and", "value", ".", "If", "the", "cursor", "is", "at", "the", "last", "leaf", "element", "then", "it", "stays", "there", "and", "returns", "nil", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L218-L250
162,372
boltdb/bolt
cursor.go
nsearch
func (c *Cursor) nsearch(key []byte) { e := &c.stack[len(c.stack)-1] p, n := e.page, e.node // If we have a node then search its inodes. if n != nil { index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) e.index = index return } // If we have a page then search its leaf elements. inodes := p.leafPageElements() index := sort.Search(int(p.count), func(i int) bool { return bytes.Compare(inodes[i].key(), key) != -1 }) e.index = index }
go
func (c *Cursor) nsearch(key []byte) { e := &c.stack[len(c.stack)-1] p, n := e.page, e.node // If we have a node then search its inodes. if n != nil { index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) e.index = index return } // If we have a page then search its leaf elements. inodes := p.leafPageElements() index := sort.Search(int(p.count), func(i int) bool { return bytes.Compare(inodes[i].key(), key) != -1 }) e.index = index }
[ "func", "(", "c", "*", "Cursor", ")", "nsearch", "(", "key", "[", "]", "byte", ")", "{", "e", ":=", "&", "c", ".", "stack", "[", "len", "(", "c", ".", "stack", ")", "-", "1", "]", "\n", "p", ",", "n", ":=", "e", ".", "page", ",", "e", "...
// nsearch searches the leaf node on the top of the stack for a key.
[ "nsearch", "searches", "the", "leaf", "node", "on", "the", "top", "of", "the", "stack", "for", "a", "key", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L318-L337
162,373
boltdb/bolt
cursor.go
keyValue
func (c *Cursor) keyValue() ([]byte, []byte, uint32) { ref := &c.stack[len(c.stack)-1] if ref.count() == 0 || ref.index >= ref.count() { return nil, nil, 0 } // Retrieve value from node. if ref.node != nil { inode := &ref.node.inodes[ref.index] return inode.key, inode.value, inode.flags } // Or retrieve value from page. elem := ref.page.leafPageElement(uint16(ref.index)) return elem.key(), elem.value(), elem.flags }
go
func (c *Cursor) keyValue() ([]byte, []byte, uint32) { ref := &c.stack[len(c.stack)-1] if ref.count() == 0 || ref.index >= ref.count() { return nil, nil, 0 } // Retrieve value from node. if ref.node != nil { inode := &ref.node.inodes[ref.index] return inode.key, inode.value, inode.flags } // Or retrieve value from page. elem := ref.page.leafPageElement(uint16(ref.index)) return elem.key(), elem.value(), elem.flags }
[ "func", "(", "c", "*", "Cursor", ")", "keyValue", "(", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "uint32", ")", "{", "ref", ":=", "&", "c", ".", "stack", "[", "len", "(", "c", ".", "stack", ")", "-", "1", "]", "\n", "if", "r...
// keyValue returns the key and value of the current leaf element.
[ "keyValue", "returns", "the", "key", "and", "value", "of", "the", "current", "leaf", "element", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L340-L355
162,374
boltdb/bolt
cursor.go
node
func (c *Cursor) node() *node { _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") // If the top of the stack is a leaf node then just return it. if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { return ref.node } // Start from root and traverse down the hierarchy. var n = c.stack[0].node if n == nil { n = c.bucket.node(c.stack[0].page.id, nil) } for _, ref := range c.stack[:len(c.stack)-1] { _assert(!n.isLeaf, "expected branch node") n = n.childAt(int(ref.index)) } _assert(n.isLeaf, "expected leaf node") return n }
go
func (c *Cursor) node() *node { _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") // If the top of the stack is a leaf node then just return it. if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { return ref.node } // Start from root and traverse down the hierarchy. var n = c.stack[0].node if n == nil { n = c.bucket.node(c.stack[0].page.id, nil) } for _, ref := range c.stack[:len(c.stack)-1] { _assert(!n.isLeaf, "expected branch node") n = n.childAt(int(ref.index)) } _assert(n.isLeaf, "expected leaf node") return n }
[ "func", "(", "c", "*", "Cursor", ")", "node", "(", ")", "*", "node", "{", "_assert", "(", "len", "(", "c", ".", "stack", ")", ">", "0", ",", "\"", "\"", ")", "\n\n", "// If the top of the stack is a leaf node then just return it.", "if", "ref", ":=", "&"...
// node returns the node that the cursor is currently positioned on.
[ "node", "returns", "the", "node", "that", "the", "cursor", "is", "currently", "positioned", "on", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L358-L377
162,375
boltdb/bolt
cursor.go
count
func (r *elemRef) count() int { if r.node != nil { return len(r.node.inodes) } return int(r.page.count) }
go
func (r *elemRef) count() int { if r.node != nil { return len(r.node.inodes) } return int(r.page.count) }
[ "func", "(", "r", "*", "elemRef", ")", "count", "(", ")", "int", "{", "if", "r", ".", "node", "!=", "nil", "{", "return", "len", "(", "r", ".", "node", ".", "inodes", ")", "\n", "}", "\n", "return", "int", "(", "r", ".", "page", ".", "count",...
// count returns the number of inodes or page elements.
[ "count", "returns", "the", "number", "of", "inodes", "or", "page", "elements", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/cursor.go#L395-L400
162,376
boltdb/bolt
page.go
leafPageElements
func (p *page) leafPageElements() []leafPageElement { if p.count == 0 { return nil } return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] }
go
func (p *page) leafPageElements() []leafPageElement { if p.count == 0 { return nil } return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] }
[ "func", "(", "p", "*", "page", ")", "leafPageElements", "(", ")", "[", "]", "leafPageElement", "{", "if", "p", ".", "count", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "(", "(", "*", "[", "0x7FFFFFF", "]", "leafPageElement", ")", "...
// leafPageElements retrieves a list of leaf nodes.
[ "leafPageElements", "retrieves", "a", "list", "of", "leaf", "nodes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L64-L69
162,377
boltdb/bolt
page.go
branchPageElements
func (p *page) branchPageElements() []branchPageElement { if p.count == 0 { return nil } return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] }
go
func (p *page) branchPageElements() []branchPageElement { if p.count == 0 { return nil } return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] }
[ "func", "(", "p", "*", "page", ")", "branchPageElements", "(", ")", "[", "]", "branchPageElement", "{", "if", "p", ".", "count", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "(", "(", "*", "[", "0x7FFFFFF", "]", "branchPageElement", ")...
// branchPageElements retrieves a list of branch nodes.
[ "branchPageElements", "retrieves", "a", "list", "of", "branch", "nodes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L77-L82
162,378
boltdb/bolt
page.go
hexdump
func (p *page) hexdump(n int) { buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] fmt.Fprintf(os.Stderr, "%x\n", buf) }
go
func (p *page) hexdump(n int) { buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] fmt.Fprintf(os.Stderr, "%x\n", buf) }
[ "func", "(", "p", "*", "page", ")", "hexdump", "(", "n", "int", ")", "{", "buf", ":=", "(", "*", "[", "maxAllocSize", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "p", ")", ")", "[", ":", "n", "]", "\n", "fmt", ".", "Fprintf", "(", ...
// dump writes n bytes of the page to STDERR as hex output.
[ "dump", "writes", "n", "bytes", "of", "the", "page", "to", "STDERR", "as", "hex", "output", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L85-L88
162,379
boltdb/bolt
page.go
value
func (n *leafPageElement) value() []byte { buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] }
go
func (n *leafPageElement) value() []byte { buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] }
[ "func", "(", "n", "*", "leafPageElement", ")", "value", "(", ")", "[", "]", "byte", "{", "buf", ":=", "(", "*", "[", "maxAllocSize", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "n", ")", ")", "\n", "return", "(", "*", "[", "maxAllocSize...
// value returns a byte slice of the node value.
[ "value", "returns", "a", "byte", "slice", "of", "the", "node", "value", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L124-L127
162,380
boltdb/bolt
page.go
merge
func (a pgids) merge(b pgids) pgids { // Return the opposite slice if one is nil. if len(a) == 0 { return b } if len(b) == 0 { return a } merged := make(pgids, len(a)+len(b)) mergepgids(merged, a, b) return merged }
go
func (a pgids) merge(b pgids) pgids { // Return the opposite slice if one is nil. if len(a) == 0 { return b } if len(b) == 0 { return a } merged := make(pgids, len(a)+len(b)) mergepgids(merged, a, b) return merged }
[ "func", "(", "a", "pgids", ")", "merge", "(", "b", "pgids", ")", "pgids", "{", "// Return the opposite slice if one is nil.", "if", "len", "(", "a", ")", "==", "0", "{", "return", "b", "\n", "}", "\n", "if", "len", "(", "b", ")", "==", "0", "{", "r...
// merge returns the sorted union of a and b.
[ "merge", "returns", "the", "sorted", "union", "of", "a", "and", "b", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L144-L155
162,381
boltdb/bolt
page.go
mergepgids
func mergepgids(dst, a, b pgids) { if len(dst) < len(a)+len(b) { panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b))) } // Copy in the opposite slice if one is nil. if len(a) == 0 { copy(dst, b) return } if len(b) == 0 { copy(dst, a) return } // Merged will hold all elements from both lists. merged := dst[:0] // Assign lead to the slice with a lower starting value, follow to the higher value. lead, follow := a, b if b[0] < a[0] { lead, follow = b, a } // Continue while there are elements in the lead. for len(lead) > 0 { // Merge largest prefix of lead that is ahead of follow[0]. n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) merged = append(merged, lead[:n]...) if n >= len(lead) { break } // Swap lead and follow. lead, follow = follow, lead[n:] } // Append what's left in follow. _ = append(merged, follow...) }
go
func mergepgids(dst, a, b pgids) { if len(dst) < len(a)+len(b) { panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b))) } // Copy in the opposite slice if one is nil. if len(a) == 0 { copy(dst, b) return } if len(b) == 0 { copy(dst, a) return } // Merged will hold all elements from both lists. merged := dst[:0] // Assign lead to the slice with a lower starting value, follow to the higher value. lead, follow := a, b if b[0] < a[0] { lead, follow = b, a } // Continue while there are elements in the lead. for len(lead) > 0 { // Merge largest prefix of lead that is ahead of follow[0]. n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) merged = append(merged, lead[:n]...) if n >= len(lead) { break } // Swap lead and follow. lead, follow = follow, lead[n:] } // Append what's left in follow. _ = append(merged, follow...) }
[ "func", "mergepgids", "(", "dst", ",", "a", ",", "b", "pgids", ")", "{", "if", "len", "(", "dst", ")", "<", "len", "(", "a", ")", "+", "len", "(", "b", ")", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "dst", ...
// mergepgids copies the sorted union of a and b into dst. // If dst is too small, it panics.
[ "mergepgids", "copies", "the", "sorted", "union", "of", "a", "and", "b", "into", "dst", ".", "If", "dst", "is", "too", "small", "it", "panics", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/page.go#L159-L197
162,382
appleboy/gorush
gorush/version.go
PrintGoRushVersion
func PrintGoRushVersion() { fmt.Printf(`GoRush %s, Compiler: %s %s, Copyright (C) 2019 Bo-Yi Wu, Inc.`, version, runtime.Compiler, runtime.Version()) fmt.Println() }
go
func PrintGoRushVersion() { fmt.Printf(`GoRush %s, Compiler: %s %s, Copyright (C) 2019 Bo-Yi Wu, Inc.`, version, runtime.Compiler, runtime.Version()) fmt.Println() }
[ "func", "PrintGoRushVersion", "(", ")", "{", "fmt", ".", "Printf", "(", "`GoRush %s, Compiler: %s %s, Copyright (C) 2019 Bo-Yi Wu, Inc.`", ",", "version", ",", "runtime", ".", "Compiler", ",", "runtime", ".", "Version", "(", ")", ")", "\n", "fmt", ".", "Println", ...
// PrintGoRushVersion provide print server engine
[ "PrintGoRushVersion", "provide", "print", "server", "engine" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/version.go#L23-L29
162,383
appleboy/gorush
gorush/notification_fcm.go
InitFCMClient
func InitFCMClient(key string) (*fcm.Client, error) { var err error if key == "" { return nil, errors.New("Missing Android API Key") } if key != PushConf.Android.APIKey { return fcm.NewClient(key) } if FCMClient == nil { FCMClient, err = fcm.NewClient(key) return FCMClient, err } return FCMClient, nil }
go
func InitFCMClient(key string) (*fcm.Client, error) { var err error if key == "" { return nil, errors.New("Missing Android API Key") } if key != PushConf.Android.APIKey { return fcm.NewClient(key) } if FCMClient == nil { FCMClient, err = fcm.NewClient(key) return FCMClient, err } return FCMClient, nil }
[ "func", "InitFCMClient", "(", "key", "string", ")", "(", "*", "fcm", ".", "Client", ",", "error", ")", "{", "var", "err", "error", "\n\n", "if", "key", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n",...
// InitFCMClient use for initialize FCM Client.
[ "InitFCMClient", "use", "for", "initialize", "FCM", "Client", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification_fcm.go#L11-L28
162,384
appleboy/gorush
main.go
pinger
func pinger() error { resp, err := http.Get("http://localhost:" + gorush.PushConf.Core.Port + gorush.PushConf.API.HealthURI) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("server returned non-200 status code") } return nil }
go
func pinger() error { resp, err := http.Get("http://localhost:" + gorush.PushConf.Core.Port + gorush.PushConf.API.HealthURI) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("server returned non-200 status code") } return nil }
[ "func", "pinger", "(", ")", "error", "{", "resp", ",", "err", ":=", "http", ".", "Get", "(", "\"", "\"", "+", "gorush", ".", "PushConf", ".", "Core", ".", "Port", "+", "gorush", ".", "PushConf", ".", "API", ".", "HealthURI", ")", "\n", "if", "err...
// handles pinging the endpoint and returns an error if the // agent is in an unhealthy state.
[ "handles", "pinging", "the", "endpoint", "and", "returns", "an", "error", "if", "the", "agent", "is", "in", "an", "unhealthy", "state", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/main.go#L297-L307
162,385
appleboy/gorush
rpc/server.go
Send
func (s *Server) Send(ctx context.Context, in *proto.NotificationRequest) (*proto.NotificationReply, error) { var badge = int(in.Badge) notification := gorush.PushNotification{ Platform: int(in.Platform), Tokens: in.Tokens, Message: in.Message, Title: in.Title, Topic: in.Topic, APIKey: in.Key, Category: in.Category, Sound: in.Sound, ContentAvailable: in.ContentAvailable, ThreadID: in.ThreadID, MutableContent: in.MutableContent, } if badge > 0 { notification.Badge = &badge } if in.Alert != nil { notification.Alert = gorush.Alert{ Title: in.Alert.Title, Body: in.Alert.Body, Subtitle: in.Alert.Subtitle, Action: in.Alert.Action, ActionLocKey: in.Alert.Action, LaunchImage: in.Alert.LaunchImage, LocArgs: in.Alert.LocArgs, LocKey: in.Alert.LocKey, TitleLocArgs: in.Alert.TitleLocArgs, TitleLocKey: in.Alert.TitleLocKey, } } go gorush.SendNotification(notification) return &proto.NotificationReply{ Success: true, Counts: int32(len(notification.Tokens)), }, nil }
go
func (s *Server) Send(ctx context.Context, in *proto.NotificationRequest) (*proto.NotificationReply, error) { var badge = int(in.Badge) notification := gorush.PushNotification{ Platform: int(in.Platform), Tokens: in.Tokens, Message: in.Message, Title: in.Title, Topic: in.Topic, APIKey: in.Key, Category: in.Category, Sound: in.Sound, ContentAvailable: in.ContentAvailable, ThreadID: in.ThreadID, MutableContent: in.MutableContent, } if badge > 0 { notification.Badge = &badge } if in.Alert != nil { notification.Alert = gorush.Alert{ Title: in.Alert.Title, Body: in.Alert.Body, Subtitle: in.Alert.Subtitle, Action: in.Alert.Action, ActionLocKey: in.Alert.Action, LaunchImage: in.Alert.LaunchImage, LocArgs: in.Alert.LocArgs, LocKey: in.Alert.LocKey, TitleLocArgs: in.Alert.TitleLocArgs, TitleLocKey: in.Alert.TitleLocKey, } } go gorush.SendNotification(notification) return &proto.NotificationReply{ Success: true, Counts: int32(len(notification.Tokens)), }, nil }
[ "func", "(", "s", "*", "Server", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "in", "*", "proto", ".", "NotificationRequest", ")", "(", "*", "proto", ".", "NotificationReply", ",", "error", ")", "{", "var", "badge", "=", "int", "(", "in",...
// Send implements helloworld.GreeterServer
[ "Send", "implements", "helloworld", ".", "GreeterServer" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/rpc/server.go#L50-L91
162,386
appleboy/gorush
rpc/server.go
RunGRPCServer
func RunGRPCServer() error { if !gorush.PushConf.GRPC.Enabled { gorush.LogAccess.Debug("gRPC server is disabled.") return nil } lis, err := net.Listen("tcp", ":"+gorush.PushConf.GRPC.Port) if err != nil { gorush.LogError.Errorf("failed to listen: %v", err) return err } s := grpc.NewServer() srv := NewServer() proto.RegisterGorushServer(s, srv) proto.RegisterHealthServer(s, srv) // Register reflection service on gRPC server. reflection.Register(s) gorush.LogAccess.Debug("gRPC server is running on " + gorush.PushConf.GRPC.Port + " port.") if err := s.Serve(lis); err != nil { gorush.LogError.Errorf("failed to serve: %v", err) return err } return nil }
go
func RunGRPCServer() error { if !gorush.PushConf.GRPC.Enabled { gorush.LogAccess.Debug("gRPC server is disabled.") return nil } lis, err := net.Listen("tcp", ":"+gorush.PushConf.GRPC.Port) if err != nil { gorush.LogError.Errorf("failed to listen: %v", err) return err } s := grpc.NewServer() srv := NewServer() proto.RegisterGorushServer(s, srv) proto.RegisterHealthServer(s, srv) // Register reflection service on gRPC server. reflection.Register(s) gorush.LogAccess.Debug("gRPC server is running on " + gorush.PushConf.GRPC.Port + " port.") if err := s.Serve(lis); err != nil { gorush.LogError.Errorf("failed to serve: %v", err) return err } return nil }
[ "func", "RunGRPCServer", "(", ")", "error", "{", "if", "!", "gorush", ".", "PushConf", ".", "GRPC", ".", "Enabled", "{", "gorush", ".", "LogAccess", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "lis", ",", "err", ":...
// RunGRPCServer run gorush grpc server
[ "RunGRPCServer", "run", "gorush", "grpc", "server" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/rpc/server.go#L94-L118
162,387
appleboy/gorush
gorush/notification_apns.go
InitAPNSClient
func InitAPNSClient() error { if PushConf.Ios.Enabled { var err error var authKey *ecdsa.PrivateKey var certificateKey tls.Certificate var ext string if PushConf.Ios.KeyPath != "" { ext = filepath.Ext(PushConf.Ios.KeyPath) switch ext { case ".p12": certificateKey, err = certificate.FromP12File(PushConf.Ios.KeyPath, PushConf.Ios.Password) case ".pem": certificateKey, err = certificate.FromPemFile(PushConf.Ios.KeyPath, PushConf.Ios.Password) case ".p8": authKey, err = token.AuthKeyFromFile(PushConf.Ios.KeyPath) default: err = errors.New("wrong certificate key extension") } if err != nil { LogError.Error("Cert Error:", err.Error()) return err } } else if PushConf.Ios.KeyBase64 != "" { ext = "." + PushConf.Ios.KeyType key, err := base64.StdEncoding.DecodeString(PushConf.Ios.KeyBase64) if err != nil { LogError.Error("base64 decode error:", err.Error()) return err } switch ext { case ".p12": certificateKey, err = certificate.FromP12Bytes(key, PushConf.Ios.Password) case ".pem": certificateKey, err = certificate.FromPemBytes(key, PushConf.Ios.Password) case ".p8": authKey, err = token.AuthKeyFromBytes(key) default: err = errors.New("wrong certificate key type") } if err != nil { LogError.Error("Cert Error:", err.Error()) return err } } if ext == ".p8" && PushConf.Ios.KeyID != "" && PushConf.Ios.TeamID != "" { token := &token.Token{ AuthKey: authKey, // KeyID from developer account (Certificates, Identifiers & Profiles -> Keys) KeyID: PushConf.Ios.KeyID, // TeamID from developer account (View Account -> Membership) TeamID: PushConf.Ios.TeamID, } if PushConf.Ios.Production { ApnsClient = apns2.NewTokenClient(token).Production() } else { ApnsClient = apns2.NewTokenClient(token).Development() } } else { if PushConf.Ios.Production { ApnsClient = apns2.NewClient(certificateKey).Production() } else { ApnsClient = apns2.NewClient(certificateKey).Development() } } } return nil }
go
func InitAPNSClient() error { if PushConf.Ios.Enabled { var err error var authKey *ecdsa.PrivateKey var certificateKey tls.Certificate var ext string if PushConf.Ios.KeyPath != "" { ext = filepath.Ext(PushConf.Ios.KeyPath) switch ext { case ".p12": certificateKey, err = certificate.FromP12File(PushConf.Ios.KeyPath, PushConf.Ios.Password) case ".pem": certificateKey, err = certificate.FromPemFile(PushConf.Ios.KeyPath, PushConf.Ios.Password) case ".p8": authKey, err = token.AuthKeyFromFile(PushConf.Ios.KeyPath) default: err = errors.New("wrong certificate key extension") } if err != nil { LogError.Error("Cert Error:", err.Error()) return err } } else if PushConf.Ios.KeyBase64 != "" { ext = "." + PushConf.Ios.KeyType key, err := base64.StdEncoding.DecodeString(PushConf.Ios.KeyBase64) if err != nil { LogError.Error("base64 decode error:", err.Error()) return err } switch ext { case ".p12": certificateKey, err = certificate.FromP12Bytes(key, PushConf.Ios.Password) case ".pem": certificateKey, err = certificate.FromPemBytes(key, PushConf.Ios.Password) case ".p8": authKey, err = token.AuthKeyFromBytes(key) default: err = errors.New("wrong certificate key type") } if err != nil { LogError.Error("Cert Error:", err.Error()) return err } } if ext == ".p8" && PushConf.Ios.KeyID != "" && PushConf.Ios.TeamID != "" { token := &token.Token{ AuthKey: authKey, // KeyID from developer account (Certificates, Identifiers & Profiles -> Keys) KeyID: PushConf.Ios.KeyID, // TeamID from developer account (View Account -> Membership) TeamID: PushConf.Ios.TeamID, } if PushConf.Ios.Production { ApnsClient = apns2.NewTokenClient(token).Production() } else { ApnsClient = apns2.NewTokenClient(token).Development() } } else { if PushConf.Ios.Production { ApnsClient = apns2.NewClient(certificateKey).Production() } else { ApnsClient = apns2.NewClient(certificateKey).Development() } } } return nil }
[ "func", "InitAPNSClient", "(", ")", "error", "{", "if", "PushConf", ".", "Ios", ".", "Enabled", "{", "var", "err", "error", "\n", "var", "authKey", "*", "ecdsa", ".", "PrivateKey", "\n", "var", "certificateKey", "tls", ".", "Certificate", "\n", "var", "e...
// InitAPNSClient use for initialize APNs Client.
[ "InitAPNSClient", "use", "for", "initialize", "APNs", "Client", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification_apns.go#L26-L101
162,388
appleboy/gorush
gorush/notification_apns.go
PushToIOS
func PushToIOS(req PushNotification) bool { LogAccess.Debug("Start push notification for iOS") if PushConf.Core.Sync { defer req.WaitDone() } var ( retryCount = 0 maxRetry = PushConf.Ios.MaxRetry ) if req.Retry > 0 && req.Retry < maxRetry { maxRetry = req.Retry } Retry: var ( isError = false newTokens []string ) notification := GetIOSNotification(req) client := getApnsClient(req) for _, token := range req.Tokens { notification.DeviceToken = token // send ios notification res, err := client.Push(notification) if err != nil { // apns server error LogPush(FailedPush, token, req, err) if PushConf.Core.Sync { req.AddLog(getLogPushEntry(FailedPush, token, req, err)) } StatStorage.AddIosError(1) newTokens = append(newTokens, token) isError = true continue } if res.StatusCode != 200 { // error message: // ref: https://github.com/sideshow/apns2/blob/master/response.go#L14-L65 LogPush(FailedPush, token, req, errors.New(res.Reason)) if PushConf.Core.Sync { req.AddLog(getLogPushEntry(FailedPush, token, req, errors.New(res.Reason))) } StatStorage.AddIosError(1) newTokens = append(newTokens, token) isError = true continue } if res.Sent() { LogPush(SucceededPush, token, req, nil) StatStorage.AddIosSuccess(1) } } if isError && retryCount < maxRetry { retryCount++ // resend fail token req.Tokens = newTokens goto Retry } return isError }
go
func PushToIOS(req PushNotification) bool { LogAccess.Debug("Start push notification for iOS") if PushConf.Core.Sync { defer req.WaitDone() } var ( retryCount = 0 maxRetry = PushConf.Ios.MaxRetry ) if req.Retry > 0 && req.Retry < maxRetry { maxRetry = req.Retry } Retry: var ( isError = false newTokens []string ) notification := GetIOSNotification(req) client := getApnsClient(req) for _, token := range req.Tokens { notification.DeviceToken = token // send ios notification res, err := client.Push(notification) if err != nil { // apns server error LogPush(FailedPush, token, req, err) if PushConf.Core.Sync { req.AddLog(getLogPushEntry(FailedPush, token, req, err)) } StatStorage.AddIosError(1) newTokens = append(newTokens, token) isError = true continue } if res.StatusCode != 200 { // error message: // ref: https://github.com/sideshow/apns2/blob/master/response.go#L14-L65 LogPush(FailedPush, token, req, errors.New(res.Reason)) if PushConf.Core.Sync { req.AddLog(getLogPushEntry(FailedPush, token, req, errors.New(res.Reason))) } StatStorage.AddIosError(1) newTokens = append(newTokens, token) isError = true continue } if res.Sent() { LogPush(SucceededPush, token, req, nil) StatStorage.AddIosSuccess(1) } } if isError && retryCount < maxRetry { retryCount++ // resend fail token req.Tokens = newTokens goto Retry } return isError }
[ "func", "PushToIOS", "(", "req", "PushNotification", ")", "bool", "{", "LogAccess", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "PushConf", ".", "Core", ".", "Sync", "{", "defer", "req", ".", "WaitDone", "(", ")", "\n", "}", "\n\n", "var", "(", ...
// PushToIOS provide send notification to APNs server.
[ "PushToIOS", "provide", "send", "notification", "to", "APNs", "server", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification_apns.go#L261-L331
162,389
appleboy/gorush
gorush/status.go
InitAppStatus
func InitAppStatus() error { LogAccess.Debug("Init App Status Engine as ", PushConf.Stat.Engine) switch PushConf.Stat.Engine { case "memory": StatStorage = memory.New() case "redis": StatStorage = redis.New(PushConf) case "boltdb": StatStorage = boltdb.New(PushConf) case "buntdb": StatStorage = buntdb.New(PushConf) case "leveldb": StatStorage = leveldb.New(PushConf) case "badger": StatStorage = badger.New(PushConf) default: LogError.Error("storage error: can't find storage driver") return errors.New("can't find storage driver") } if err := StatStorage.Init(); err != nil { LogError.Error("storage error: " + err.Error()) return err } return nil }
go
func InitAppStatus() error { LogAccess.Debug("Init App Status Engine as ", PushConf.Stat.Engine) switch PushConf.Stat.Engine { case "memory": StatStorage = memory.New() case "redis": StatStorage = redis.New(PushConf) case "boltdb": StatStorage = boltdb.New(PushConf) case "buntdb": StatStorage = buntdb.New(PushConf) case "leveldb": StatStorage = leveldb.New(PushConf) case "badger": StatStorage = badger.New(PushConf) default: LogError.Error("storage error: can't find storage driver") return errors.New("can't find storage driver") } if err := StatStorage.Init(); err != nil { LogError.Error("storage error: " + err.Error()) return err } return nil }
[ "func", "InitAppStatus", "(", ")", "error", "{", "LogAccess", ".", "Debug", "(", "\"", "\"", ",", "PushConf", ".", "Stat", ".", "Engine", ")", "\n", "switch", "PushConf", ".", "Stat", ".", "Engine", "{", "case", "\"", "\"", ":", "StatStorage", "=", "...
// InitAppStatus for initialize app status
[ "InitAppStatus", "for", "initialize", "app", "status" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/status.go#L43-L70
162,390
appleboy/gorush
gorush/status.go
StatMiddleware
func StatMiddleware() gin.HandlerFunc { return func(c *gin.Context) { beginning, recorder := Stats.Begin(c.Writer) c.Next() Stats.End(beginning, stats.WithRecorder(recorder)) } }
go
func StatMiddleware() gin.HandlerFunc { return func(c *gin.Context) { beginning, recorder := Stats.Begin(c.Writer) c.Next() Stats.End(beginning, stats.WithRecorder(recorder)) } }
[ "func", "StatMiddleware", "(", ")", "gin", ".", "HandlerFunc", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "beginning", ",", "recorder", ":=", "Stats", ".", "Begin", "(", "c", ".", "Writer", ")", "\n", "c", ".", "Next", "...
// StatMiddleware response time, status code count, etc.
[ "StatMiddleware", "response", "time", "status", "code", "count", "etc", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/status.go#L92-L98
162,391
appleboy/gorush
rpc/client_grpc_health.go
NewGrpcHealthClient
func NewGrpcHealthClient(conn *grpc.ClientConn) Health { client := new(healthClient) client.client = proto.NewHealthClient(conn) client.conn = conn return client }
go
func NewGrpcHealthClient(conn *grpc.ClientConn) Health { client := new(healthClient) client.client = proto.NewHealthClient(conn) client.conn = conn return client }
[ "func", "NewGrpcHealthClient", "(", "conn", "*", "grpc", ".", "ClientConn", ")", "Health", "{", "client", ":=", "new", "(", "healthClient", ")", "\n", "client", ".", "client", "=", "proto", ".", "NewHealthClient", "(", "conn", ")", "\n", "client", ".", "...
// NewGrpcHealthClient returns a new grpc Client.
[ "NewGrpcHealthClient", "returns", "a", "new", "grpc", "Client", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/rpc/client_grpc_health.go#L21-L26
162,392
appleboy/gorush
gorush/notification.go
AddLog
func (p *PushNotification) AddLog(log LogPushEntry) { if p.log != nil { *p.log = append(*p.log, log) } }
go
func (p *PushNotification) AddLog(log LogPushEntry) { if p.log != nil { *p.log = append(*p.log, log) } }
[ "func", "(", "p", "*", "PushNotification", ")", "AddLog", "(", "log", "LogPushEntry", ")", "{", "if", "p", ".", "log", "!=", "nil", "{", "*", "p", ".", "log", "=", "append", "(", "*", "p", ".", "log", ",", "log", ")", "\n", "}", "\n", "}" ]
// AddLog record fail log of notification
[ "AddLog", "record", "fail", "log", "of", "notification" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification.go#L110-L114
162,393
appleboy/gorush
gorush/notification.go
CheckMessage
func CheckMessage(req PushNotification) error { var msg string // ignore send topic mesaage from FCM if !req.IsTopic() && len(req.Tokens) == 0 && len(req.To) == 0 { msg = "the message must specify at least one registration ID" LogAccess.Debug(msg) return errors.New(msg) } if len(req.Tokens) == PlatFormIos && len(req.Tokens[0]) == 0 { msg = "the token must not be empty" LogAccess.Debug(msg) return errors.New(msg) } if req.Platform == PlatFormAndroid && len(req.Tokens) > 1000 { msg = "the message may specify at most 1000 registration IDs" LogAccess.Debug(msg) return errors.New(msg) } // ref: https://firebase.google.com/docs/cloud-messaging/http-server-ref if req.Platform == PlatFormAndroid && req.TimeToLive != nil && (*req.TimeToLive < uint(0) || uint(2419200) < *req.TimeToLive) { msg = "the message's TimeToLive field must be an integer " + "between 0 and 2419200 (4 weeks)" LogAccess.Debug(msg) return errors.New(msg) } return nil }
go
func CheckMessage(req PushNotification) error { var msg string // ignore send topic mesaage from FCM if !req.IsTopic() && len(req.Tokens) == 0 && len(req.To) == 0 { msg = "the message must specify at least one registration ID" LogAccess.Debug(msg) return errors.New(msg) } if len(req.Tokens) == PlatFormIos && len(req.Tokens[0]) == 0 { msg = "the token must not be empty" LogAccess.Debug(msg) return errors.New(msg) } if req.Platform == PlatFormAndroid && len(req.Tokens) > 1000 { msg = "the message may specify at most 1000 registration IDs" LogAccess.Debug(msg) return errors.New(msg) } // ref: https://firebase.google.com/docs/cloud-messaging/http-server-ref if req.Platform == PlatFormAndroid && req.TimeToLive != nil && (*req.TimeToLive < uint(0) || uint(2419200) < *req.TimeToLive) { msg = "the message's TimeToLive field must be an integer " + "between 0 and 2419200 (4 weeks)" LogAccess.Debug(msg) return errors.New(msg) } return nil }
[ "func", "CheckMessage", "(", "req", "PushNotification", ")", "error", "{", "var", "msg", "string", "\n\n", "// ignore send topic mesaage from FCM", "if", "!", "req", ".", "IsTopic", "(", ")", "&&", "len", "(", "req", ".", "Tokens", ")", "==", "0", "&&", "l...
// CheckMessage for check request message
[ "CheckMessage", "for", "check", "request", "message" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification.go#L124-L155
162,394
appleboy/gorush
gorush/notification.go
SetProxy
func SetProxy(proxy string) error { proxyURL, err := url.ParseRequestURI(proxy) if err != nil { return err } http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyURL)} LogAccess.Debug("Set http proxy as " + proxy) return nil }
go
func SetProxy(proxy string) error { proxyURL, err := url.ParseRequestURI(proxy) if err != nil { return err } http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyURL)} LogAccess.Debug("Set http proxy as " + proxy) return nil }
[ "func", "SetProxy", "(", "proxy", "string", ")", "error", "{", "proxyURL", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "proxy", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "http", ".", "DefaultTransport", "...
// SetProxy only working for FCM server.
[ "SetProxy", "only", "working", "for", "FCM", "server", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification.go#L158-L170
162,395
appleboy/gorush
gorush/notification.go
CheckPushConf
func CheckPushConf() error { if !PushConf.Ios.Enabled && !PushConf.Android.Enabled { return errors.New("Please enable iOS or Android config in yml config") } if PushConf.Ios.Enabled { if PushConf.Ios.KeyPath == "" && PushConf.Ios.KeyBase64 == "" { return errors.New("Missing iOS certificate key") } // check certificate file exist if PushConf.Ios.KeyPath != "" { if _, err := os.Stat(PushConf.Ios.KeyPath); os.IsNotExist(err) { return errors.New("certificate file does not exist") } } } if PushConf.Android.Enabled { if PushConf.Android.APIKey == "" { return errors.New("Missing Android API Key") } } return nil }
go
func CheckPushConf() error { if !PushConf.Ios.Enabled && !PushConf.Android.Enabled { return errors.New("Please enable iOS or Android config in yml config") } if PushConf.Ios.Enabled { if PushConf.Ios.KeyPath == "" && PushConf.Ios.KeyBase64 == "" { return errors.New("Missing iOS certificate key") } // check certificate file exist if PushConf.Ios.KeyPath != "" { if _, err := os.Stat(PushConf.Ios.KeyPath); os.IsNotExist(err) { return errors.New("certificate file does not exist") } } } if PushConf.Android.Enabled { if PushConf.Android.APIKey == "" { return errors.New("Missing Android API Key") } } return nil }
[ "func", "CheckPushConf", "(", ")", "error", "{", "if", "!", "PushConf", ".", "Ios", ".", "Enabled", "&&", "!", "PushConf", ".", "Android", ".", "Enabled", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "PushConf",...
// CheckPushConf provide check your yml config.
[ "CheckPushConf", "provide", "check", "your", "yml", "config", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/notification.go#L173-L198
162,396
appleboy/gorush
gorush/metrics.go
NewMetrics
func NewMetrics() Metrics { return Metrics{ TotalPushCount: prometheus.NewDesc( namespace+"total_push_count", "Number of push count", nil, nil, ), IosSuccess: prometheus.NewDesc( namespace+"ios_success", "Number of iOS success count", nil, nil, ), IosError: prometheus.NewDesc( namespace+"ios_error", "Number of iOS fail count", nil, nil, ), AndroidSuccess: prometheus.NewDesc( namespace+"android_success", "Number of android success count", nil, nil, ), AndroidError: prometheus.NewDesc( namespace+"android_fail", "Number of android fail count", nil, nil, ), QueueUsage: prometheus.NewDesc( namespace+"queue_usage", "Length of internal queue", nil, nil, ), } }
go
func NewMetrics() Metrics { return Metrics{ TotalPushCount: prometheus.NewDesc( namespace+"total_push_count", "Number of push count", nil, nil, ), IosSuccess: prometheus.NewDesc( namespace+"ios_success", "Number of iOS success count", nil, nil, ), IosError: prometheus.NewDesc( namespace+"ios_error", "Number of iOS fail count", nil, nil, ), AndroidSuccess: prometheus.NewDesc( namespace+"android_success", "Number of android success count", nil, nil, ), AndroidError: prometheus.NewDesc( namespace+"android_fail", "Number of android fail count", nil, nil, ), QueueUsage: prometheus.NewDesc( namespace+"queue_usage", "Length of internal queue", nil, nil, ), } }
[ "func", "NewMetrics", "(", ")", "Metrics", "{", "return", "Metrics", "{", "TotalPushCount", ":", "prometheus", ".", "NewDesc", "(", "namespace", "+", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "nil", ",", ")", ",", "IosSuccess", ":", "prometheus", "...
// NewMetrics returns a new Metrics with all prometheus.Desc initialized
[ "NewMetrics", "returns", "a", "new", "Metrics", "with", "all", "prometheus", ".", "Desc", "initialized" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/metrics.go#L21-L55
162,397
appleboy/gorush
gorush/metrics.go
Describe
func (c Metrics) Describe(ch chan<- *prometheus.Desc) { ch <- c.TotalPushCount ch <- c.IosSuccess ch <- c.IosError ch <- c.AndroidSuccess ch <- c.AndroidError ch <- c.QueueUsage }
go
func (c Metrics) Describe(ch chan<- *prometheus.Desc) { ch <- c.TotalPushCount ch <- c.IosSuccess ch <- c.IosError ch <- c.AndroidSuccess ch <- c.AndroidError ch <- c.QueueUsage }
[ "func", "(", "c", "Metrics", ")", "Describe", "(", "ch", "chan", "<-", "*", "prometheus", ".", "Desc", ")", "{", "ch", "<-", "c", ".", "TotalPushCount", "\n", "ch", "<-", "c", ".", "IosSuccess", "\n", "ch", "<-", "c", ".", "IosError", "\n", "ch", ...
// Describe returns all possible prometheus.Desc
[ "Describe", "returns", "all", "possible", "prometheus", ".", "Desc" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/metrics.go#L58-L65
162,398
appleboy/gorush
gorush/metrics.go
Collect
func (c Metrics) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric( c.TotalPushCount, prometheus.GaugeValue, float64(StatStorage.GetTotalCount()), ) ch <- prometheus.MustNewConstMetric( c.IosSuccess, prometheus.GaugeValue, float64(StatStorage.GetIosSuccess()), ) ch <- prometheus.MustNewConstMetric( c.IosError, prometheus.GaugeValue, float64(StatStorage.GetIosError()), ) ch <- prometheus.MustNewConstMetric( c.AndroidSuccess, prometheus.GaugeValue, float64(StatStorage.GetAndroidSuccess()), ) ch <- prometheus.MustNewConstMetric( c.AndroidError, prometheus.GaugeValue, float64(StatStorage.GetAndroidError()), ) ch <- prometheus.MustNewConstMetric( c.QueueUsage, prometheus.GaugeValue, float64(len(QueueNotification)), ) }
go
func (c Metrics) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric( c.TotalPushCount, prometheus.GaugeValue, float64(StatStorage.GetTotalCount()), ) ch <- prometheus.MustNewConstMetric( c.IosSuccess, prometheus.GaugeValue, float64(StatStorage.GetIosSuccess()), ) ch <- prometheus.MustNewConstMetric( c.IosError, prometheus.GaugeValue, float64(StatStorage.GetIosError()), ) ch <- prometheus.MustNewConstMetric( c.AndroidSuccess, prometheus.GaugeValue, float64(StatStorage.GetAndroidSuccess()), ) ch <- prometheus.MustNewConstMetric( c.AndroidError, prometheus.GaugeValue, float64(StatStorage.GetAndroidError()), ) ch <- prometheus.MustNewConstMetric( c.QueueUsage, prometheus.GaugeValue, float64(len(QueueNotification)), ) }
[ "func", "(", "c", "Metrics", ")", "Collect", "(", "ch", "chan", "<-", "prometheus", ".", "Metric", ")", "{", "ch", "<-", "prometheus", ".", "MustNewConstMetric", "(", "c", ".", "TotalPushCount", ",", "prometheus", ".", "GaugeValue", ",", "float64", "(", ...
// Collect returns the metrics with values
[ "Collect", "returns", "the", "metrics", "with", "values" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/metrics.go#L68-L99
162,399
appleboy/gorush
gorush/log.go
InitLog
func InitLog() error { var err error // init logger LogAccess = logrus.New() LogError = logrus.New() LogAccess.Formatter = &logrus.TextFormatter{ TimestampFormat: "2006/01/02 - 15:04:05", FullTimestamp: true, } LogError.Formatter = &logrus.TextFormatter{ TimestampFormat: "2006/01/02 - 15:04:05", FullTimestamp: true, } // set logger if err = SetLogLevel(LogAccess, PushConf.Log.AccessLevel); err != nil { return errors.New("Set access log level error: " + err.Error()) } if err = SetLogLevel(LogError, PushConf.Log.ErrorLevel); err != nil { return errors.New("Set error log level error: " + err.Error()) } if err = SetLogOut(LogAccess, PushConf.Log.AccessLog); err != nil { return errors.New("Set access log path error: " + err.Error()) } if err = SetLogOut(LogError, PushConf.Log.ErrorLog); err != nil { return errors.New("Set error log path error: " + err.Error()) } return nil }
go
func InitLog() error { var err error // init logger LogAccess = logrus.New() LogError = logrus.New() LogAccess.Formatter = &logrus.TextFormatter{ TimestampFormat: "2006/01/02 - 15:04:05", FullTimestamp: true, } LogError.Formatter = &logrus.TextFormatter{ TimestampFormat: "2006/01/02 - 15:04:05", FullTimestamp: true, } // set logger if err = SetLogLevel(LogAccess, PushConf.Log.AccessLevel); err != nil { return errors.New("Set access log level error: " + err.Error()) } if err = SetLogLevel(LogError, PushConf.Log.ErrorLevel); err != nil { return errors.New("Set error log level error: " + err.Error()) } if err = SetLogOut(LogAccess, PushConf.Log.AccessLog); err != nil { return errors.New("Set access log path error: " + err.Error()) } if err = SetLogOut(LogError, PushConf.Log.ErrorLog); err != nil { return errors.New("Set error log path error: " + err.Error()) } return nil }
[ "func", "InitLog", "(", ")", "error", "{", "var", "err", "error", "\n\n", "// init logger", "LogAccess", "=", "logrus", ".", "New", "(", ")", "\n", "LogError", "=", "logrus", ".", "New", "(", ")", "\n\n", "LogAccess", ".", "Formatter", "=", "&", "logru...
// InitLog use for initial log module
[ "InitLog", "use", "for", "initial", "log", "module" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/log.go#L51-L87