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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
17,100 |
mailgun/holster
|
secret/secret.go
|
Open
|
func (s *Service) Open(e SealedData) (byt []byte, err error) {
// once function is complete, check if we are returning err or not.
// if we are, return emit a failure metric, if not a success metric.
defer func() {
if err == nil {
s.metricsClient.Inc("success", 1, 1)
} else {
s.metricsClient.Inc("failure", 1, 1)
}
}()
// convert nonce to an array
nonce, err := nonceSliceToArray(e.NonceBytes())
if err != nil {
return nil, err
}
// decrypt
var decrypted []byte
decrypted, ok := secretbox.Open(decrypted, e.CiphertextBytes(), nonce, s.secretKey)
if !ok {
return nil, fmt.Errorf("unable to decrypt message")
}
return decrypted, nil
}
|
go
|
func (s *Service) Open(e SealedData) (byt []byte, err error) {
// once function is complete, check if we are returning err or not.
// if we are, return emit a failure metric, if not a success metric.
defer func() {
if err == nil {
s.metricsClient.Inc("success", 1, 1)
} else {
s.metricsClient.Inc("failure", 1, 1)
}
}()
// convert nonce to an array
nonce, err := nonceSliceToArray(e.NonceBytes())
if err != nil {
return nil, err
}
// decrypt
var decrypted []byte
decrypted, ok := secretbox.Open(decrypted, e.CiphertextBytes(), nonce, s.secretKey)
if !ok {
return nil, fmt.Errorf("unable to decrypt message")
}
return decrypted, nil
}
|
[
"func",
"(",
"s",
"*",
"Service",
")",
"Open",
"(",
"e",
"SealedData",
")",
"(",
"byt",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"// once function is complete, check if we are returning err or not.",
"// if we are, return emit a failure metric, if not a success metric.",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"s",
".",
"metricsClient",
".",
"Inc",
"(",
"\"",
"\"",
",",
"1",
",",
"1",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"metricsClient",
".",
"Inc",
"(",
"\"",
"\"",
",",
"1",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// convert nonce to an array",
"nonce",
",",
"err",
":=",
"nonceSliceToArray",
"(",
"e",
".",
"NonceBytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// decrypt",
"var",
"decrypted",
"[",
"]",
"byte",
"\n",
"decrypted",
",",
"ok",
":=",
"secretbox",
".",
"Open",
"(",
"decrypted",
",",
"e",
".",
"CiphertextBytes",
"(",
")",
",",
"nonce",
",",
"s",
".",
"secretKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"decrypted",
",",
"nil",
"\n",
"}"
] |
// Open authenticates the ciphertext and if valid, decrypts and returns plaintext.
|
[
"Open",
"authenticates",
"the",
"ciphertext",
"and",
"if",
"valid",
"decrypts",
"and",
"returns",
"plaintext",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/secret/secret.go#L194-L219
|
17,101 |
mailgun/holster
|
election/election.go
|
Watch
|
func (s *EtcdElection) Watch(ctx context.Context, startIndex uint64) chan bool {
results := make(chan bool)
var cancel atomic.Value
var stop int32
go func() {
select {
case <-ctx.Done():
cancel.Load().(context.CancelFunc)()
return
}
}()
// Create our initial watcher
watcher := s.api.Watcher(s.conf.Election, nil)
s.wg.Loop(func() bool {
// this ensures we exit properly if the watcher isn't connected to etcd
if atomic.LoadInt32(&stop) == 1 {
return false
}
ctx, c := context.WithTimeout(context.Background(), time.Second*10)
cancel.Store(c)
resp, err := watcher.Next(ctx)
if err != nil {
if err == context.Canceled {
close(results)
return false
}
if cErr, ok := err.(etcd.Error); ok {
if cErr.Code == etcd.ErrorCodeEventIndexCleared {
logrus.WithField("category", "election").
Infof("EtcdElection %s - new index is %d",
err, cErr.Index+1)
// Re-create the watcher with a newer index until we catch up
watcher = s.api.Watcher(s.conf.Election, nil)
return true
}
}
if err != context.DeadlineExceeded {
logrus.WithField("category", "election").
Errorf("EtcdElection etcd error: %s", err)
time.Sleep(time.Second * 10)
}
} else {
logrus.WithField("category", "election").
Debugf("EtcdElection etcd event: %+v\n", resp)
results <- true
}
return true
})
return results
}
|
go
|
func (s *EtcdElection) Watch(ctx context.Context, startIndex uint64) chan bool {
results := make(chan bool)
var cancel atomic.Value
var stop int32
go func() {
select {
case <-ctx.Done():
cancel.Load().(context.CancelFunc)()
return
}
}()
// Create our initial watcher
watcher := s.api.Watcher(s.conf.Election, nil)
s.wg.Loop(func() bool {
// this ensures we exit properly if the watcher isn't connected to etcd
if atomic.LoadInt32(&stop) == 1 {
return false
}
ctx, c := context.WithTimeout(context.Background(), time.Second*10)
cancel.Store(c)
resp, err := watcher.Next(ctx)
if err != nil {
if err == context.Canceled {
close(results)
return false
}
if cErr, ok := err.(etcd.Error); ok {
if cErr.Code == etcd.ErrorCodeEventIndexCleared {
logrus.WithField("category", "election").
Infof("EtcdElection %s - new index is %d",
err, cErr.Index+1)
// Re-create the watcher with a newer index until we catch up
watcher = s.api.Watcher(s.conf.Election, nil)
return true
}
}
if err != context.DeadlineExceeded {
logrus.WithField("category", "election").
Errorf("EtcdElection etcd error: %s", err)
time.Sleep(time.Second * 10)
}
} else {
logrus.WithField("category", "election").
Debugf("EtcdElection etcd event: %+v\n", resp)
results <- true
}
return true
})
return results
}
|
[
"func",
"(",
"s",
"*",
"EtcdElection",
")",
"Watch",
"(",
"ctx",
"context",
".",
"Context",
",",
"startIndex",
"uint64",
")",
"chan",
"bool",
"{",
"results",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"var",
"cancel",
"atomic",
".",
"Value",
"\n",
"var",
"stop",
"int32",
"\n\n",
"go",
"func",
"(",
")",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"cancel",
".",
"Load",
"(",
")",
".",
"(",
"context",
".",
"CancelFunc",
")",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Create our initial watcher",
"watcher",
":=",
"s",
".",
"api",
".",
"Watcher",
"(",
"s",
".",
"conf",
".",
"Election",
",",
"nil",
")",
"\n\n",
"s",
".",
"wg",
".",
"Loop",
"(",
"func",
"(",
")",
"bool",
"{",
"// this ensures we exit properly if the watcher isn't connected to etcd",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"stop",
")",
"==",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"ctx",
",",
"c",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"time",
".",
"Second",
"*",
"10",
")",
"\n",
"cancel",
".",
"Store",
"(",
"c",
")",
"\n",
"resp",
",",
"err",
":=",
"watcher",
".",
"Next",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"context",
".",
"Canceled",
"{",
"close",
"(",
"results",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"cErr",
",",
"ok",
":=",
"err",
".",
"(",
"etcd",
".",
"Error",
")",
";",
"ok",
"{",
"if",
"cErr",
".",
"Code",
"==",
"etcd",
".",
"ErrorCodeEventIndexCleared",
"{",
"logrus",
".",
"WithField",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
",",
"cErr",
".",
"Index",
"+",
"1",
")",
"\n\n",
"// Re-create the watcher with a newer index until we catch up",
"watcher",
"=",
"s",
".",
"api",
".",
"Watcher",
"(",
"s",
".",
"conf",
".",
"Election",
",",
"nil",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"context",
".",
"DeadlineExceeded",
"{",
"logrus",
".",
"WithField",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
"*",
"10",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"logrus",
".",
"WithField",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"resp",
")",
"\n",
"results",
"<-",
"true",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"return",
"results",
"\n",
"}"
] |
// Watch the prefix for any events and send a 'true' if we should attempt grab leader
|
[
"Watch",
"the",
"prefix",
"for",
"any",
"events",
"and",
"send",
"a",
"true",
"if",
"we",
"should",
"attempt",
"grab",
"leader"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/election/election.go#L105-L160
|
17,102 |
mailgun/holster
|
secret/key.go
|
EncodedStringToKey
|
func EncodedStringToKey(encodedKey string) (*[SecretKeyLength]byte, error) {
// decode base64-encoded key
keySlice, err := base64.StdEncoding.DecodeString(encodedKey)
if err != nil {
return nil, err
}
// convert to array and return
return KeySliceToArray(keySlice)
}
|
go
|
func EncodedStringToKey(encodedKey string) (*[SecretKeyLength]byte, error) {
// decode base64-encoded key
keySlice, err := base64.StdEncoding.DecodeString(encodedKey)
if err != nil {
return nil, err
}
// convert to array and return
return KeySliceToArray(keySlice)
}
|
[
"func",
"EncodedStringToKey",
"(",
"encodedKey",
"string",
")",
"(",
"*",
"[",
"SecretKeyLength",
"]",
"byte",
",",
"error",
")",
"{",
"// decode base64-encoded key",
"keySlice",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"encodedKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// convert to array and return",
"return",
"KeySliceToArray",
"(",
"keySlice",
")",
"\n",
"}"
] |
// EncodedStringToKey converts a base64-encoded string into key bytes.
|
[
"EncodedStringToKey",
"converts",
"a",
"base64",
"-",
"encoded",
"string",
"into",
"key",
"bytes",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/secret/key.go#L36-L45
|
17,103 |
mailgun/holster
|
secret/key.go
|
SealedDataToString
|
func SealedDataToString(sealedData SealedData) (string, error) {
b, err := json.Marshal(sealedData)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
|
go
|
func SealedDataToString(sealedData SealedData) (string, error) {
b, err := json.Marshal(sealedData)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
|
[
"func",
"SealedDataToString",
"(",
"sealedData",
"SealedData",
")",
"(",
"string",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"sealedData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"b",
")",
",",
"nil",
"\n",
"}"
] |
// Given SealedData returns equivalent URL safe base64 encoded string.
|
[
"Given",
"SealedData",
"returns",
"equivalent",
"URL",
"safe",
"base64",
"encoded",
"string",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/secret/key.go#L53-L60
|
17,104 |
mailgun/holster
|
secret/key.go
|
StringToSealedData
|
func StringToSealedData(encodedBytes string) (SealedData, error) {
bytes, err := base64.URLEncoding.DecodeString(encodedBytes)
if err != nil {
return nil, err
}
var sb SealedBytes
err = json.Unmarshal(bytes, &sb)
if err != nil {
return nil, err
}
return &sb, nil
}
|
go
|
func StringToSealedData(encodedBytes string) (SealedData, error) {
bytes, err := base64.URLEncoding.DecodeString(encodedBytes)
if err != nil {
return nil, err
}
var sb SealedBytes
err = json.Unmarshal(bytes, &sb)
if err != nil {
return nil, err
}
return &sb, nil
}
|
[
"func",
"StringToSealedData",
"(",
"encodedBytes",
"string",
")",
"(",
"SealedData",
",",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"encodedBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"sb",
"SealedBytes",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"bytes",
",",
"&",
"sb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"sb",
",",
"nil",
"\n",
"}"
] |
// Given a URL safe base64 encoded string, returns SealedData.
|
[
"Given",
"a",
"URL",
"safe",
"base64",
"encoded",
"string",
"returns",
"SealedData",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/secret/key.go#L63-L76
|
17,105 |
mailgun/holster
|
broadcast.go
|
Broadcast
|
func (b *broadcast) Broadcast() {
b.mutex.Lock()
for _, channel := range b.clients {
channel <- struct{}{}
}
b.mutex.Unlock()
}
|
go
|
func (b *broadcast) Broadcast() {
b.mutex.Lock()
for _, channel := range b.clients {
channel <- struct{}{}
}
b.mutex.Unlock()
}
|
[
"func",
"(",
"b",
"*",
"broadcast",
")",
"Broadcast",
"(",
")",
"{",
"b",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"channel",
":=",
"range",
"b",
".",
"clients",
"{",
"channel",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"b",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// Notify all Waiting goroutines
|
[
"Notify",
"all",
"Waiting",
"goroutines"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/broadcast.go#L31-L37
|
17,106 |
mailgun/holster
|
broadcast.go
|
Wait
|
func (b *broadcast) Wait(name string) {
b.mutex.Lock()
channel, ok := b.clients[name]
if !ok {
b.clients[name] = make(chan struct{}, 10000)
channel = b.clients[name]
}
b.mutex.Unlock()
// Wait for a new event or done is closed
select {
case <-channel:
return
case <-b.done:
return
}
}
|
go
|
func (b *broadcast) Wait(name string) {
b.mutex.Lock()
channel, ok := b.clients[name]
if !ok {
b.clients[name] = make(chan struct{}, 10000)
channel = b.clients[name]
}
b.mutex.Unlock()
// Wait for a new event or done is closed
select {
case <-channel:
return
case <-b.done:
return
}
}
|
[
"func",
"(",
"b",
"*",
"broadcast",
")",
"Wait",
"(",
"name",
"string",
")",
"{",
"b",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"channel",
",",
"ok",
":=",
"b",
".",
"clients",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"b",
".",
"clients",
"[",
"name",
"]",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"10000",
")",
"\n",
"channel",
"=",
"b",
".",
"clients",
"[",
"name",
"]",
"\n",
"}",
"\n",
"b",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"// Wait for a new event or done is closed",
"select",
"{",
"case",
"<-",
"channel",
":",
"return",
"\n",
"case",
"<-",
"b",
".",
"done",
":",
"return",
"\n",
"}",
"\n",
"}"
] |
// Blocks until a broadcast is received
|
[
"Blocks",
"until",
"a",
"broadcast",
"is",
"received"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/broadcast.go#L45-L61
|
17,107 |
mailgun/holster
|
broadcast.go
|
WaitChan
|
func (b *broadcast) WaitChan(name string) chan struct{} {
b.mutex.Lock()
channel, ok := b.clients[name]
if !ok {
b.clients[name] = make(chan struct{}, 10000)
channel = b.clients[name]
}
b.mutex.Unlock()
return channel
}
|
go
|
func (b *broadcast) WaitChan(name string) chan struct{} {
b.mutex.Lock()
channel, ok := b.clients[name]
if !ok {
b.clients[name] = make(chan struct{}, 10000)
channel = b.clients[name]
}
b.mutex.Unlock()
return channel
}
|
[
"func",
"(",
"b",
"*",
"broadcast",
")",
"WaitChan",
"(",
"name",
"string",
")",
"chan",
"struct",
"{",
"}",
"{",
"b",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"channel",
",",
"ok",
":=",
"b",
".",
"clients",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"b",
".",
"clients",
"[",
"name",
"]",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"10000",
")",
"\n",
"channel",
"=",
"b",
".",
"clients",
"[",
"name",
"]",
"\n",
"}",
"\n",
"b",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"channel",
"\n",
"}"
] |
// Returns a channel the caller can use to wait for a broadcast
|
[
"Returns",
"a",
"channel",
"the",
"caller",
"can",
"use",
"to",
"wait",
"for",
"a",
"broadcast"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/broadcast.go#L64-L73
|
17,108 |
mailgun/holster
|
httpsign/nonce.go
|
NewNonceCache
|
func NewNonceCache(capacity int, cacheTTL int, clock holster.Clock) *NonceCache {
return &NonceCache{
cache: holster.NewTTLMapWithClock(capacity, clock),
cacheTTL: cacheTTL,
clock: clock,
}
}
|
go
|
func NewNonceCache(capacity int, cacheTTL int, clock holster.Clock) *NonceCache {
return &NonceCache{
cache: holster.NewTTLMapWithClock(capacity, clock),
cacheTTL: cacheTTL,
clock: clock,
}
}
|
[
"func",
"NewNonceCache",
"(",
"capacity",
"int",
",",
"cacheTTL",
"int",
",",
"clock",
"holster",
".",
"Clock",
")",
"*",
"NonceCache",
"{",
"return",
"&",
"NonceCache",
"{",
"cache",
":",
"holster",
".",
"NewTTLMapWithClock",
"(",
"capacity",
",",
"clock",
")",
",",
"cacheTTL",
":",
"cacheTTL",
",",
"clock",
":",
"clock",
",",
"}",
"\n",
"}"
] |
// Return a new NonceCache. Allows you to control cache capacity and ttl
|
[
"Return",
"a",
"new",
"NonceCache",
".",
"Allows",
"you",
"to",
"control",
"cache",
"capacity",
"and",
"ttl"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/httpsign/nonce.go#L17-L23
|
17,109 |
mailgun/holster
|
httpsign/nonce.go
|
InCache
|
func (n *NonceCache) InCache(nonce string) bool {
n.Lock()
defer n.Unlock()
// check if the nonce is already in the cache
_, exists := n.cache.Get(nonce)
if exists {
return true
}
// it's not, so let's put it in the cache
n.cache.Set(nonce, "", n.cacheTTL)
return false
}
|
go
|
func (n *NonceCache) InCache(nonce string) bool {
n.Lock()
defer n.Unlock()
// check if the nonce is already in the cache
_, exists := n.cache.Get(nonce)
if exists {
return true
}
// it's not, so let's put it in the cache
n.cache.Set(nonce, "", n.cacheTTL)
return false
}
|
[
"func",
"(",
"n",
"*",
"NonceCache",
")",
"InCache",
"(",
"nonce",
"string",
")",
"bool",
"{",
"n",
".",
"Lock",
"(",
")",
"\n",
"defer",
"n",
".",
"Unlock",
"(",
")",
"\n\n",
"// check if the nonce is already in the cache",
"_",
",",
"exists",
":=",
"n",
".",
"cache",
".",
"Get",
"(",
"nonce",
")",
"\n",
"if",
"exists",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// it's not, so let's put it in the cache",
"n",
".",
"cache",
".",
"Set",
"(",
"nonce",
",",
"\"",
"\"",
",",
"n",
".",
"cacheTTL",
")",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// InCache checks if a nonce is in the cache. If not, it adds it to the
// cache and returns false. Otherwise it returns true.
|
[
"InCache",
"checks",
"if",
"a",
"nonce",
"is",
"in",
"the",
"cache",
".",
"If",
"not",
"it",
"adds",
"it",
"to",
"the",
"cache",
"and",
"returns",
"false",
".",
"Otherwise",
"it",
"returns",
"true",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/httpsign/nonce.go#L27-L41
|
17,110 |
mailgun/holster
|
lru_cache.go
|
NewLRUCache
|
func NewLRUCache(maxEntries int) *LRUCache {
return &LRUCache{
MaxEntries: maxEntries,
ll: list.New(),
cache: make(map[interface{}]*list.Element),
}
}
|
go
|
func NewLRUCache(maxEntries int) *LRUCache {
return &LRUCache{
MaxEntries: maxEntries,
ll: list.New(),
cache: make(map[interface{}]*list.Element),
}
}
|
[
"func",
"NewLRUCache",
"(",
"maxEntries",
"int",
")",
"*",
"LRUCache",
"{",
"return",
"&",
"LRUCache",
"{",
"MaxEntries",
":",
"maxEntries",
",",
"ll",
":",
"list",
".",
"New",
"(",
")",
",",
"cache",
":",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"*",
"list",
".",
"Element",
")",
",",
"}",
"\n",
"}"
] |
// New creates a new Cache.
// If maxEntries is zero, the cache has no limit and it's assumed
// that eviction is done by the caller.
|
[
"New",
"creates",
"a",
"new",
"Cache",
".",
"If",
"maxEntries",
"is",
"zero",
"the",
"cache",
"has",
"no",
"limit",
"and",
"it",
"s",
"assumed",
"that",
"eviction",
"is",
"done",
"by",
"the",
"caller",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L62-L68
|
17,111 |
mailgun/holster
|
lru_cache.go
|
Add
|
func (c *LRUCache) Add(key Key, value interface{}) bool {
return c.addRecord(&cacheRecord{key: key, value: value})
}
|
go
|
func (c *LRUCache) Add(key Key, value interface{}) bool {
return c.addRecord(&cacheRecord{key: key, value: value})
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"Add",
"(",
"key",
"Key",
",",
"value",
"interface",
"{",
"}",
")",
"bool",
"{",
"return",
"c",
".",
"addRecord",
"(",
"&",
"cacheRecord",
"{",
"key",
":",
"key",
",",
"value",
":",
"value",
"}",
")",
"\n",
"}"
] |
// Add or Update a value in the cache, return true if the key already existed
|
[
"Add",
"or",
"Update",
"a",
"value",
"in",
"the",
"cache",
"return",
"true",
"if",
"the",
"key",
"already",
"existed"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L71-L73
|
17,112 |
mailgun/holster
|
lru_cache.go
|
AddWithTTL
|
func (c *LRUCache) AddWithTTL(key Key, value interface{}, TTL time.Duration) bool {
expireAt := time.Now().UTC().Add(TTL)
return c.addRecord(&cacheRecord{
key: key,
value: value,
expireAt: &expireAt,
})
}
|
go
|
func (c *LRUCache) AddWithTTL(key Key, value interface{}, TTL time.Duration) bool {
expireAt := time.Now().UTC().Add(TTL)
return c.addRecord(&cacheRecord{
key: key,
value: value,
expireAt: &expireAt,
})
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"AddWithTTL",
"(",
"key",
"Key",
",",
"value",
"interface",
"{",
"}",
",",
"TTL",
"time",
".",
"Duration",
")",
"bool",
"{",
"expireAt",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Add",
"(",
"TTL",
")",
"\n",
"return",
"c",
".",
"addRecord",
"(",
"&",
"cacheRecord",
"{",
"key",
":",
"key",
",",
"value",
":",
"value",
",",
"expireAt",
":",
"&",
"expireAt",
",",
"}",
")",
"\n",
"}"
] |
// Adds a value to the cache with a TTL
|
[
"Adds",
"a",
"value",
"to",
"the",
"cache",
"with",
"a",
"TTL"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L76-L83
|
17,113 |
mailgun/holster
|
lru_cache.go
|
addRecord
|
func (c *LRUCache) addRecord(record *cacheRecord) bool {
defer c.mutex.Unlock()
c.mutex.Lock()
// If the key already exist, set the new value
if ee, ok := c.cache[record.key]; ok {
c.ll.MoveToFront(ee)
temp := ee.Value.(*cacheRecord)
*temp = *record
return true
}
ele := c.ll.PushFront(record)
c.cache[record.key] = ele
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries {
c.removeOldest()
}
return false
}
|
go
|
func (c *LRUCache) addRecord(record *cacheRecord) bool {
defer c.mutex.Unlock()
c.mutex.Lock()
// If the key already exist, set the new value
if ee, ok := c.cache[record.key]; ok {
c.ll.MoveToFront(ee)
temp := ee.Value.(*cacheRecord)
*temp = *record
return true
}
ele := c.ll.PushFront(record)
c.cache[record.key] = ele
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries {
c.removeOldest()
}
return false
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"addRecord",
"(",
"record",
"*",
"cacheRecord",
")",
"bool",
"{",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"// If the key already exist, set the new value",
"if",
"ee",
",",
"ok",
":=",
"c",
".",
"cache",
"[",
"record",
".",
"key",
"]",
";",
"ok",
"{",
"c",
".",
"ll",
".",
"MoveToFront",
"(",
"ee",
")",
"\n",
"temp",
":=",
"ee",
".",
"Value",
".",
"(",
"*",
"cacheRecord",
")",
"\n",
"*",
"temp",
"=",
"*",
"record",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"ele",
":=",
"c",
".",
"ll",
".",
"PushFront",
"(",
"record",
")",
"\n",
"c",
".",
"cache",
"[",
"record",
".",
"key",
"]",
"=",
"ele",
"\n",
"if",
"c",
".",
"MaxEntries",
"!=",
"0",
"&&",
"c",
".",
"ll",
".",
"Len",
"(",
")",
">",
"c",
".",
"MaxEntries",
"{",
"c",
".",
"removeOldest",
"(",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Adds a value to the cache.
|
[
"Adds",
"a",
"value",
"to",
"the",
"cache",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L86-L104
|
17,114 |
mailgun/holster
|
lru_cache.go
|
Stats
|
func (c *LRUCache) Stats() LRUCacheStats {
defer func() {
c.stats = LRUCacheStats{}
c.mutex.Unlock()
}()
c.mutex.Lock()
c.stats.Size = int64(len(c.cache))
return c.stats
}
|
go
|
func (c *LRUCache) Stats() LRUCacheStats {
defer func() {
c.stats = LRUCacheStats{}
c.mutex.Unlock()
}()
c.mutex.Lock()
c.stats.Size = int64(len(c.cache))
return c.stats
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"Stats",
"(",
")",
"LRUCacheStats",
"{",
"defer",
"func",
"(",
")",
"{",
"c",
".",
"stats",
"=",
"LRUCacheStats",
"{",
"}",
"\n",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"stats",
".",
"Size",
"=",
"int64",
"(",
"len",
"(",
"c",
".",
"cache",
")",
")",
"\n",
"return",
"c",
".",
"stats",
"\n",
"}"
] |
// Returns stats about the current state of the cache
|
[
"Returns",
"stats",
"about",
"the",
"current",
"state",
"of",
"the",
"cache"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L163-L171
|
17,115 |
mailgun/holster
|
lru_cache.go
|
Keys
|
func (c *LRUCache) Keys() (keys []interface{}) {
defer c.mutex.Unlock()
c.mutex.Lock()
for key := range c.cache {
keys = append(keys, key)
}
return
}
|
go
|
func (c *LRUCache) Keys() (keys []interface{}) {
defer c.mutex.Unlock()
c.mutex.Lock()
for key := range c.cache {
keys = append(keys, key)
}
return
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"Keys",
"(",
")",
"(",
"keys",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"for",
"key",
":=",
"range",
"c",
".",
"cache",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Get a list of keys at this point in time
|
[
"Get",
"a",
"list",
"of",
"keys",
"at",
"this",
"point",
"in",
"time"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L174-L182
|
17,116 |
mailgun/holster
|
lru_cache.go
|
Peek
|
func (c *LRUCache) Peek(key interface{}) (value interface{}, ok bool) {
defer c.mutex.Unlock()
c.mutex.Lock()
if ele, hit := c.cache[key]; hit {
entry := ele.Value.(*cacheRecord)
return entry.value, true
}
return nil, false
}
|
go
|
func (c *LRUCache) Peek(key interface{}) (value interface{}, ok bool) {
defer c.mutex.Unlock()
c.mutex.Lock()
if ele, hit := c.cache[key]; hit {
entry := ele.Value.(*cacheRecord)
return entry.value, true
}
return nil, false
}
|
[
"func",
"(",
"c",
"*",
"LRUCache",
")",
"Peek",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"value",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"if",
"ele",
",",
"hit",
":=",
"c",
".",
"cache",
"[",
"key",
"]",
";",
"hit",
"{",
"entry",
":=",
"ele",
".",
"Value",
".",
"(",
"*",
"cacheRecord",
")",
"\n",
"return",
"entry",
".",
"value",
",",
"true",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// Get the value without updating the expiration or last used or stats
|
[
"Get",
"the",
"value",
"without",
"updating",
"the",
"expiration",
"or",
"last",
"used",
"or",
"stats"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/lru_cache.go#L185-L194
|
17,117 |
mailgun/holster
|
priority_queue.go
|
Update
|
func (p *PriorityQueue) Update(el *PQItem, priority int) {
heap.Remove(p.impl, el.index)
el.Priority = priority
heap.Push(p.impl, el)
}
|
go
|
func (p *PriorityQueue) Update(el *PQItem, priority int) {
heap.Remove(p.impl, el.index)
el.Priority = priority
heap.Push(p.impl, el)
}
|
[
"func",
"(",
"p",
"*",
"PriorityQueue",
")",
"Update",
"(",
"el",
"*",
"PQItem",
",",
"priority",
"int",
")",
"{",
"heap",
".",
"Remove",
"(",
"p",
".",
"impl",
",",
"el",
".",
"index",
")",
"\n",
"el",
".",
"Priority",
"=",
"priority",
"\n",
"heap",
".",
"Push",
"(",
"p",
".",
"impl",
",",
"el",
")",
"\n",
"}"
] |
// Modifies the priority and value of an Item in the queue.
|
[
"Modifies",
"the",
"priority",
"and",
"value",
"of",
"an",
"Item",
"in",
"the",
"queue",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/priority_queue.go#L57-L61
|
17,118 |
mailgun/holster
|
random/random.go
|
Bytes
|
func (c *CSPRNG) Bytes(bytes int) ([]byte, error) {
n := make([]byte, bytes)
// get bytes-bit random number from /dev/urandom
_, err := io.ReadFull(rand.Reader, n)
if err != nil {
return nil, err
}
return n, nil
}
|
go
|
func (c *CSPRNG) Bytes(bytes int) ([]byte, error) {
n := make([]byte, bytes)
// get bytes-bit random number from /dev/urandom
_, err := io.ReadFull(rand.Reader, n)
if err != nil {
return nil, err
}
return n, nil
}
|
[
"func",
"(",
"c",
"*",
"CSPRNG",
")",
"Bytes",
"(",
"bytes",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"n",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"bytes",
")",
"\n\n",
"// get bytes-bit random number from /dev/urandom",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"rand",
".",
"Reader",
",",
"n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] |
// Return n-bytes of random values from the CSPRNG.
|
[
"Return",
"n",
"-",
"bytes",
"of",
"random",
"values",
"from",
"the",
"CSPRNG",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/random/random.go#L37-L47
|
17,119 |
mailgun/holster
|
waitgroup.go
|
Run
|
func (wg *WaitGroup) Run(callBack func(interface{}) error, data interface{}) {
wg.wg.Add(1)
go func() {
err := callBack(data)
if err == nil {
wg.wg.Done()
return
}
wg.mutex.Lock()
wg.errs = append(wg.errs, err)
wg.wg.Done()
wg.mutex.Unlock()
}()
}
|
go
|
func (wg *WaitGroup) Run(callBack func(interface{}) error, data interface{}) {
wg.wg.Add(1)
go func() {
err := callBack(data)
if err == nil {
wg.wg.Done()
return
}
wg.mutex.Lock()
wg.errs = append(wg.errs, err)
wg.wg.Done()
wg.mutex.Unlock()
}()
}
|
[
"func",
"(",
"wg",
"*",
"WaitGroup",
")",
"Run",
"(",
"callBack",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"wg",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"err",
":=",
"callBack",
"(",
"data",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"wg",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"wg",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"wg",
".",
"errs",
"=",
"append",
"(",
"wg",
".",
"errs",
",",
"err",
")",
"\n",
"wg",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"wg",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// Run a routine and collect errors if any
|
[
"Run",
"a",
"routine",
"and",
"collect",
"errors",
"if",
"any"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/waitgroup.go#L28-L41
|
17,120 |
mailgun/holster
|
waitgroup.go
|
Go
|
func (wg *WaitGroup) Go(cb func()) {
wg.wg.Add(1)
go func() {
cb()
wg.wg.Done()
}()
}
|
go
|
func (wg *WaitGroup) Go(cb func()) {
wg.wg.Add(1)
go func() {
cb()
wg.wg.Done()
}()
}
|
[
"func",
"(",
"wg",
"*",
"WaitGroup",
")",
"Go",
"(",
"cb",
"func",
"(",
")",
")",
"{",
"wg",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"cb",
"(",
")",
"\n",
"wg",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// Execute a long running routine
|
[
"Execute",
"a",
"long",
"running",
"routine"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/waitgroup.go#L44-L50
|
17,121 |
mailgun/holster
|
waitgroup.go
|
Loop
|
func (wg *WaitGroup) Loop(callBack func() bool) {
wg.wg.Add(1)
go func() {
for {
if !callBack() {
wg.wg.Done()
break
}
}
}()
}
|
go
|
func (wg *WaitGroup) Loop(callBack func() bool) {
wg.wg.Add(1)
go func() {
for {
if !callBack() {
wg.wg.Done()
break
}
}
}()
}
|
[
"func",
"(",
"wg",
"*",
"WaitGroup",
")",
"Loop",
"(",
"callBack",
"func",
"(",
")",
"bool",
")",
"{",
"wg",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"if",
"!",
"callBack",
"(",
")",
"{",
"wg",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// Run a goroutine in a loop continuously, if the callBack returns false the loop is broken
|
[
"Run",
"a",
"goroutine",
"in",
"a",
"loop",
"continuously",
"if",
"the",
"callBack",
"returns",
"false",
"the",
"loop",
"is",
"broken"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/waitgroup.go#L85-L95
|
17,122 |
mailgun/holster
|
waitgroup.go
|
Wait
|
func (wg *WaitGroup) Wait() []error {
wg.wg.Wait()
wg.mutex.Lock()
defer wg.mutex.Unlock()
if len(wg.errs) == 0 {
return nil
}
return wg.errs
}
|
go
|
func (wg *WaitGroup) Wait() []error {
wg.wg.Wait()
wg.mutex.Lock()
defer wg.mutex.Unlock()
if len(wg.errs) == 0 {
return nil
}
return wg.errs
}
|
[
"func",
"(",
"wg",
"*",
"WaitGroup",
")",
"Wait",
"(",
")",
"[",
"]",
"error",
"{",
"wg",
".",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"wg",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wg",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"wg",
".",
"errs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"wg",
".",
"errs",
"\n",
"}"
] |
// Wait for all the routines to complete and return any errors collected
|
[
"Wait",
"for",
"all",
"the",
"routines",
"to",
"complete",
"and",
"return",
"any",
"errors",
"collected"
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/waitgroup.go#L98-L108
|
17,123 |
mailgun/holster
|
cmd/lemma/main.go
|
generateKey
|
func generateKey(keypath string, salt []byte, keyiter int) (key *[secret.SecretKeyLength]byte, isPass bool, err error) {
// if a keypath is given try and use it
if keypath != "" {
key, err := secret.ReadKeyFromDisk(keypath)
if err != nil {
return nil, false, fmt.Errorf("unable to build secret service: %v", err)
}
return key, false, nil
}
// otherwise read in a passphrase from disk and use that, remember to reset your terminal afterwards
var passphrase string
fmt.Printf("Passphrase: ")
fmt.Scanln(&passphrase)
// derive key and return it
keySlice := pbkdf2.Key([]byte(passphrase), salt, keyiter, 32, sha256.New)
keyBytes, err := secret.KeySliceToArray(keySlice)
if err != nil {
return nil, true, err
}
return keyBytes, true, nil
}
|
go
|
func generateKey(keypath string, salt []byte, keyiter int) (key *[secret.SecretKeyLength]byte, isPass bool, err error) {
// if a keypath is given try and use it
if keypath != "" {
key, err := secret.ReadKeyFromDisk(keypath)
if err != nil {
return nil, false, fmt.Errorf("unable to build secret service: %v", err)
}
return key, false, nil
}
// otherwise read in a passphrase from disk and use that, remember to reset your terminal afterwards
var passphrase string
fmt.Printf("Passphrase: ")
fmt.Scanln(&passphrase)
// derive key and return it
keySlice := pbkdf2.Key([]byte(passphrase), salt, keyiter, 32, sha256.New)
keyBytes, err := secret.KeySliceToArray(keySlice)
if err != nil {
return nil, true, err
}
return keyBytes, true, nil
}
|
[
"func",
"generateKey",
"(",
"keypath",
"string",
",",
"salt",
"[",
"]",
"byte",
",",
"keyiter",
"int",
")",
"(",
"key",
"*",
"[",
"secret",
".",
"SecretKeyLength",
"]",
"byte",
",",
"isPass",
"bool",
",",
"err",
"error",
")",
"{",
"// if a keypath is given try and use it",
"if",
"keypath",
"!=",
"\"",
"\"",
"{",
"key",
",",
"err",
":=",
"secret",
".",
"ReadKeyFromDisk",
"(",
"keypath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"key",
",",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"// otherwise read in a passphrase from disk and use that, remember to reset your terminal afterwards",
"var",
"passphrase",
"string",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Scanln",
"(",
"&",
"passphrase",
")",
"\n\n",
"// derive key and return it",
"keySlice",
":=",
"pbkdf2",
".",
"Key",
"(",
"[",
"]",
"byte",
"(",
"passphrase",
")",
",",
"salt",
",",
"keyiter",
",",
"32",
",",
"sha256",
".",
"New",
")",
"\n",
"keyBytes",
",",
"err",
":=",
"secret",
".",
"KeySliceToArray",
"(",
"keySlice",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"true",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"keyBytes",
",",
"true",
",",
"nil",
"\n",
"}"
] |
// Returns key from keypath or uses salt + passphrase to generate key using a KDF.
|
[
"Returns",
"key",
"from",
"keypath",
"or",
"uses",
"salt",
"+",
"passphrase",
"to",
"generate",
"key",
"using",
"a",
"KDF",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/cmd/lemma/main.go#L152-L175
|
17,124 |
mailgun/holster
|
cmd/lemma/main.go
|
writeCiphertext
|
func writeCiphertext(salt []byte, keyiter int, isPass bool, sealed secret.SealedData, filename string) error {
// fill in the ciphertext fields
ec := EncodedCiphertext{
CiphertextNonce: sealed.NonceBytes(),
Ciphertext: sealed.CiphertextBytes(),
CipherAlgorithm: "salsa20_poly1305",
}
// if we used a passphrase, also set the passphrase fields
if isPass == true {
ec.KeySalt = salt
ec.KeyIter = keyiter
ec.KeyAlgorithm = "pbkdf#2"
}
// marshal encoded ciphertext into a json string
b, err := json.MarshalIndent(ec, "", " ")
if err != nil {
return err
}
// write to disk with read only permissions for the current user
return ioutil.WriteFile(filename, b, 0600)
}
|
go
|
func writeCiphertext(salt []byte, keyiter int, isPass bool, sealed secret.SealedData, filename string) error {
// fill in the ciphertext fields
ec := EncodedCiphertext{
CiphertextNonce: sealed.NonceBytes(),
Ciphertext: sealed.CiphertextBytes(),
CipherAlgorithm: "salsa20_poly1305",
}
// if we used a passphrase, also set the passphrase fields
if isPass == true {
ec.KeySalt = salt
ec.KeyIter = keyiter
ec.KeyAlgorithm = "pbkdf#2"
}
// marshal encoded ciphertext into a json string
b, err := json.MarshalIndent(ec, "", " ")
if err != nil {
return err
}
// write to disk with read only permissions for the current user
return ioutil.WriteFile(filename, b, 0600)
}
|
[
"func",
"writeCiphertext",
"(",
"salt",
"[",
"]",
"byte",
",",
"keyiter",
"int",
",",
"isPass",
"bool",
",",
"sealed",
"secret",
".",
"SealedData",
",",
"filename",
"string",
")",
"error",
"{",
"// fill in the ciphertext fields",
"ec",
":=",
"EncodedCiphertext",
"{",
"CiphertextNonce",
":",
"sealed",
".",
"NonceBytes",
"(",
")",
",",
"Ciphertext",
":",
"sealed",
".",
"CiphertextBytes",
"(",
")",
",",
"CipherAlgorithm",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"// if we used a passphrase, also set the passphrase fields",
"if",
"isPass",
"==",
"true",
"{",
"ec",
".",
"KeySalt",
"=",
"salt",
"\n",
"ec",
".",
"KeyIter",
"=",
"keyiter",
"\n",
"ec",
".",
"KeyAlgorithm",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// marshal encoded ciphertext into a json string",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"ec",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// write to disk with read only permissions for the current user",
"return",
"ioutil",
".",
"WriteFile",
"(",
"filename",
",",
"b",
",",
"0600",
")",
"\n",
"}"
] |
// Encodes all data needed to decrypt message into a JSON string and writes it to disk.
|
[
"Encodes",
"all",
"data",
"needed",
"to",
"decrypt",
"message",
"into",
"a",
"JSON",
"string",
"and",
"writes",
"it",
"to",
"disk",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/cmd/lemma/main.go#L178-L201
|
17,125 |
mailgun/holster
|
cmd/lemma/main.go
|
readCiphertext
|
func readCiphertext(filename string) ([]byte, int, *secret.SealedBytes, error) {
plaintextBytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, 0, nil, err
}
var ec EncodedCiphertext
err = json.Unmarshal(plaintextBytes, &ec)
if err != nil {
return nil, 0, nil, err
}
sealedBytes := &secret.SealedBytes{
Ciphertext: ec.Ciphertext,
Nonce: ec.CiphertextNonce,
}
return ec.KeySalt, ec.KeyIter, sealedBytes, nil
}
|
go
|
func readCiphertext(filename string) ([]byte, int, *secret.SealedBytes, error) {
plaintextBytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, 0, nil, err
}
var ec EncodedCiphertext
err = json.Unmarshal(plaintextBytes, &ec)
if err != nil {
return nil, 0, nil, err
}
sealedBytes := &secret.SealedBytes{
Ciphertext: ec.Ciphertext,
Nonce: ec.CiphertextNonce,
}
return ec.KeySalt, ec.KeyIter, sealedBytes, nil
}
|
[
"func",
"readCiphertext",
"(",
"filename",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"int",
",",
"*",
"secret",
".",
"SealedBytes",
",",
"error",
")",
"{",
"plaintextBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"ec",
"EncodedCiphertext",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"plaintextBytes",
",",
"&",
"ec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"sealedBytes",
":=",
"&",
"secret",
".",
"SealedBytes",
"{",
"Ciphertext",
":",
"ec",
".",
"Ciphertext",
",",
"Nonce",
":",
"ec",
".",
"CiphertextNonce",
",",
"}",
"\n\n",
"return",
"ec",
".",
"KeySalt",
",",
"ec",
".",
"KeyIter",
",",
"sealedBytes",
",",
"nil",
"\n",
"}"
] |
// Reads in encoded ciphertext from disk and breaks into component parts.
|
[
"Reads",
"in",
"encoded",
"ciphertext",
"from",
"disk",
"and",
"breaks",
"into",
"component",
"parts",
"."
] |
769f8d7f9b18d38062e704a0c26c8861702f0ea6
|
https://github.com/mailgun/holster/blob/769f8d7f9b18d38062e704a0c26c8861702f0ea6/cmd/lemma/main.go#L204-L222
|
17,126 |
ipfs/go-ds-flatfs
|
flatfs.go
|
Begin
|
func (m *opMap) Begin(name string) *opResult {
for {
myOp := &opResult{opMap: m, name: name}
myOp.mu.Lock()
opIface, loaded := m.ops.LoadOrStore(name, myOp)
if !loaded { // no one else doing ops with this key
return myOp
}
op := opIface.(*opResult)
// someone else doing ops with this key, wait for
// the result
op.mu.RLock()
if op.success {
return nil
}
// if we are here, we will retry the operation
}
}
|
go
|
func (m *opMap) Begin(name string) *opResult {
for {
myOp := &opResult{opMap: m, name: name}
myOp.mu.Lock()
opIface, loaded := m.ops.LoadOrStore(name, myOp)
if !loaded { // no one else doing ops with this key
return myOp
}
op := opIface.(*opResult)
// someone else doing ops with this key, wait for
// the result
op.mu.RLock()
if op.success {
return nil
}
// if we are here, we will retry the operation
}
}
|
[
"func",
"(",
"m",
"*",
"opMap",
")",
"Begin",
"(",
"name",
"string",
")",
"*",
"opResult",
"{",
"for",
"{",
"myOp",
":=",
"&",
"opResult",
"{",
"opMap",
":",
"m",
",",
"name",
":",
"name",
"}",
"\n",
"myOp",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"opIface",
",",
"loaded",
":=",
"m",
".",
"ops",
".",
"LoadOrStore",
"(",
"name",
",",
"myOp",
")",
"\n",
"if",
"!",
"loaded",
"{",
"// no one else doing ops with this key",
"return",
"myOp",
"\n",
"}",
"\n\n",
"op",
":=",
"opIface",
".",
"(",
"*",
"opResult",
")",
"\n",
"// someone else doing ops with this key, wait for",
"// the result",
"op",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"if",
"op",
".",
"success",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// if we are here, we will retry the operation",
"}",
"\n",
"}"
] |
// Returns nil if there's nothing to do.
|
[
"Returns",
"nil",
"if",
"there",
"s",
"nothing",
"to",
"do",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L170-L189
|
17,127 |
ipfs/go-ds-flatfs
|
flatfs.go
|
renameAndUpdateDiskUsage
|
func (fs *Datastore) renameAndUpdateDiskUsage(tmpPath, path string) error {
fi, err := os.Stat(path)
// Destination exists, we need to discount it from diskUsage
if fs != nil && err == nil {
atomic.AddInt64(&fs.diskUsage, -fi.Size())
} else if !os.IsNotExist(err) {
return err
}
// Rename and add new file's diskUsage. If the rename fails,
// it will either a) Re-add the size of an existing file, which
// was sustracted before b) Add 0 if there is no existing file.
err = os.Rename(tmpPath, path)
fs.updateDiskUsage(path, true)
return err
}
|
go
|
func (fs *Datastore) renameAndUpdateDiskUsage(tmpPath, path string) error {
fi, err := os.Stat(path)
// Destination exists, we need to discount it from diskUsage
if fs != nil && err == nil {
atomic.AddInt64(&fs.diskUsage, -fi.Size())
} else if !os.IsNotExist(err) {
return err
}
// Rename and add new file's diskUsage. If the rename fails,
// it will either a) Re-add the size of an existing file, which
// was sustracted before b) Add 0 if there is no existing file.
err = os.Rename(tmpPath, path)
fs.updateDiskUsage(path, true)
return err
}
|
[
"func",
"(",
"fs",
"*",
"Datastore",
")",
"renameAndUpdateDiskUsage",
"(",
"tmpPath",
",",
"path",
"string",
")",
"error",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
"\n\n",
"// Destination exists, we need to discount it from diskUsage",
"if",
"fs",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"fs",
".",
"diskUsage",
",",
"-",
"fi",
".",
"Size",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Rename and add new file's diskUsage. If the rename fails,",
"// it will either a) Re-add the size of an existing file, which",
"// was sustracted before b) Add 0 if there is no existing file.",
"err",
"=",
"os",
".",
"Rename",
"(",
"tmpPath",
",",
"path",
")",
"\n",
"fs",
".",
"updateDiskUsage",
"(",
"path",
",",
"true",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// This function always runs under an opLock. Therefore, only one thread is
// touching the affected files.
|
[
"This",
"function",
"always",
"runs",
"under",
"an",
"opLock",
".",
"Therefore",
"only",
"one",
"thread",
"is",
"touching",
"the",
"affected",
"files",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L333-L349
|
17,128 |
ipfs/go-ds-flatfs
|
flatfs.go
|
doDelete
|
func (fs *Datastore) doDelete(key datastore.Key) error {
_, path := fs.encode(key)
fSize := fileSize(path)
switch err := os.Remove(path); {
case err == nil:
atomic.AddInt64(&fs.diskUsage, -fSize)
fs.checkpointDiskUsage()
return nil
case os.IsNotExist(err):
return datastore.ErrNotFound
default:
return err
}
}
|
go
|
func (fs *Datastore) doDelete(key datastore.Key) error {
_, path := fs.encode(key)
fSize := fileSize(path)
switch err := os.Remove(path); {
case err == nil:
atomic.AddInt64(&fs.diskUsage, -fSize)
fs.checkpointDiskUsage()
return nil
case os.IsNotExist(err):
return datastore.ErrNotFound
default:
return err
}
}
|
[
"func",
"(",
"fs",
"*",
"Datastore",
")",
"doDelete",
"(",
"key",
"datastore",
".",
"Key",
")",
"error",
"{",
"_",
",",
"path",
":=",
"fs",
".",
"encode",
"(",
"key",
")",
"\n\n",
"fSize",
":=",
"fileSize",
"(",
"path",
")",
"\n\n",
"switch",
"err",
":=",
"os",
".",
"Remove",
"(",
"path",
")",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"atomic",
".",
"AddInt64",
"(",
"&",
"fs",
".",
"diskUsage",
",",
"-",
"fSize",
")",
"\n",
"fs",
".",
"checkpointDiskUsage",
"(",
")",
"\n",
"return",
"nil",
"\n",
"case",
"os",
".",
"IsNotExist",
"(",
"err",
")",
":",
"return",
"datastore",
".",
"ErrNotFound",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] |
// This function always runs within an opLock for the given
// key, and not concurrently.
|
[
"This",
"function",
"always",
"runs",
"within",
"an",
"opLock",
"for",
"the",
"given",
"key",
"and",
"not",
"concurrently",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L628-L643
|
17,129 |
ipfs/go-ds-flatfs
|
flatfs.go
|
folderSize
|
func folderSize(path string, deadline time.Time) (int64, initAccuracy, error) {
var du int64
folder, err := os.Open(path)
if err != nil {
return 0, "", err
}
defer folder.Close()
stat, err := folder.Stat()
if err != nil {
return 0, "", err
}
files, err := folder.Readdirnames(-1)
if err != nil {
return 0, "", err
}
totalFiles := len(files)
i := 0
filesProcessed := 0
maxFiles := DiskUsageFilesAverage
if maxFiles <= 0 {
maxFiles = totalFiles
}
// randomize file order
// https://stackoverflow.com/a/42776696
for i := len(files) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
files[i], files[j] = files[j], files[i]
}
accuracy := exactA
for {
// Do not process any files after deadline is over
if time.Now().After(deadline) {
accuracy = timedoutA
break
}
if i >= totalFiles || filesProcessed >= maxFiles {
if filesProcessed >= maxFiles {
accuracy = approxA
}
break
}
// Stat the file
fname := files[i]
subpath := filepath.Join(path, fname)
st, err := os.Stat(subpath)
if err != nil {
return 0, "", err
}
// Find folder size recursively
if st.IsDir() {
du2, acc, err := folderSize(filepath.Join(subpath), deadline)
if err != nil {
return 0, "", err
}
accuracy = combineAccuracy(acc, accuracy)
du += du2
filesProcessed++
} else { // in any other case, add the file size
du += st.Size()
filesProcessed++
}
i++
}
nonProcessed := totalFiles - filesProcessed
// Avg is total size in this folder up to now / total files processed
// it includes folders ant not folders
avg := 0.0
if filesProcessed > 0 {
avg = float64(du) / float64(filesProcessed)
}
duEstimation := int64(avg * float64(nonProcessed))
du += duEstimation
du += stat.Size()
//fmt.Println(path, "total:", totalFiles, "totalStat:", i, "totalFile:", filesProcessed, "left:", nonProcessed, "avg:", int(avg), "est:", int(duEstimation), "du:", du)
return du, accuracy, nil
}
|
go
|
func folderSize(path string, deadline time.Time) (int64, initAccuracy, error) {
var du int64
folder, err := os.Open(path)
if err != nil {
return 0, "", err
}
defer folder.Close()
stat, err := folder.Stat()
if err != nil {
return 0, "", err
}
files, err := folder.Readdirnames(-1)
if err != nil {
return 0, "", err
}
totalFiles := len(files)
i := 0
filesProcessed := 0
maxFiles := DiskUsageFilesAverage
if maxFiles <= 0 {
maxFiles = totalFiles
}
// randomize file order
// https://stackoverflow.com/a/42776696
for i := len(files) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
files[i], files[j] = files[j], files[i]
}
accuracy := exactA
for {
// Do not process any files after deadline is over
if time.Now().After(deadline) {
accuracy = timedoutA
break
}
if i >= totalFiles || filesProcessed >= maxFiles {
if filesProcessed >= maxFiles {
accuracy = approxA
}
break
}
// Stat the file
fname := files[i]
subpath := filepath.Join(path, fname)
st, err := os.Stat(subpath)
if err != nil {
return 0, "", err
}
// Find folder size recursively
if st.IsDir() {
du2, acc, err := folderSize(filepath.Join(subpath), deadline)
if err != nil {
return 0, "", err
}
accuracy = combineAccuracy(acc, accuracy)
du += du2
filesProcessed++
} else { // in any other case, add the file size
du += st.Size()
filesProcessed++
}
i++
}
nonProcessed := totalFiles - filesProcessed
// Avg is total size in this folder up to now / total files processed
// it includes folders ant not folders
avg := 0.0
if filesProcessed > 0 {
avg = float64(du) / float64(filesProcessed)
}
duEstimation := int64(avg * float64(nonProcessed))
du += duEstimation
du += stat.Size()
//fmt.Println(path, "total:", totalFiles, "totalStat:", i, "totalFile:", filesProcessed, "left:", nonProcessed, "avg:", int(avg), "est:", int(duEstimation), "du:", du)
return du, accuracy, nil
}
|
[
"func",
"folderSize",
"(",
"path",
"string",
",",
"deadline",
"time",
".",
"Time",
")",
"(",
"int64",
",",
"initAccuracy",
",",
"error",
")",
"{",
"var",
"du",
"int64",
"\n\n",
"folder",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"folder",
".",
"Close",
"(",
")",
"\n\n",
"stat",
",",
"err",
":=",
"folder",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"files",
",",
"err",
":=",
"folder",
".",
"Readdirnames",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"totalFiles",
":=",
"len",
"(",
"files",
")",
"\n",
"i",
":=",
"0",
"\n",
"filesProcessed",
":=",
"0",
"\n",
"maxFiles",
":=",
"DiskUsageFilesAverage",
"\n",
"if",
"maxFiles",
"<=",
"0",
"{",
"maxFiles",
"=",
"totalFiles",
"\n",
"}",
"\n\n",
"// randomize file order",
"// https://stackoverflow.com/a/42776696",
"for",
"i",
":=",
"len",
"(",
"files",
")",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"j",
":=",
"rand",
".",
"Intn",
"(",
"i",
"+",
"1",
")",
"\n",
"files",
"[",
"i",
"]",
",",
"files",
"[",
"j",
"]",
"=",
"files",
"[",
"j",
"]",
",",
"files",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"accuracy",
":=",
"exactA",
"\n",
"for",
"{",
"// Do not process any files after deadline is over",
"if",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"deadline",
")",
"{",
"accuracy",
"=",
"timedoutA",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"i",
">=",
"totalFiles",
"||",
"filesProcessed",
">=",
"maxFiles",
"{",
"if",
"filesProcessed",
">=",
"maxFiles",
"{",
"accuracy",
"=",
"approxA",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"// Stat the file",
"fname",
":=",
"files",
"[",
"i",
"]",
"\n",
"subpath",
":=",
"filepath",
".",
"Join",
"(",
"path",
",",
"fname",
")",
"\n",
"st",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"subpath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// Find folder size recursively",
"if",
"st",
".",
"IsDir",
"(",
")",
"{",
"du2",
",",
"acc",
",",
"err",
":=",
"folderSize",
"(",
"filepath",
".",
"Join",
"(",
"subpath",
")",
",",
"deadline",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"accuracy",
"=",
"combineAccuracy",
"(",
"acc",
",",
"accuracy",
")",
"\n",
"du",
"+=",
"du2",
"\n",
"filesProcessed",
"++",
"\n",
"}",
"else",
"{",
"// in any other case, add the file size",
"du",
"+=",
"st",
".",
"Size",
"(",
")",
"\n",
"filesProcessed",
"++",
"\n",
"}",
"\n\n",
"i",
"++",
"\n",
"}",
"\n\n",
"nonProcessed",
":=",
"totalFiles",
"-",
"filesProcessed",
"\n\n",
"// Avg is total size in this folder up to now / total files processed",
"// it includes folders ant not folders",
"avg",
":=",
"0.0",
"\n",
"if",
"filesProcessed",
">",
"0",
"{",
"avg",
"=",
"float64",
"(",
"du",
")",
"/",
"float64",
"(",
"filesProcessed",
")",
"\n",
"}",
"\n",
"duEstimation",
":=",
"int64",
"(",
"avg",
"*",
"float64",
"(",
"nonProcessed",
")",
")",
"\n",
"du",
"+=",
"duEstimation",
"\n",
"du",
"+=",
"stat",
".",
"Size",
"(",
")",
"\n",
"//fmt.Println(path, \"total:\", totalFiles, \"totalStat:\", i, \"totalFile:\", filesProcessed, \"left:\", nonProcessed, \"avg:\", int(avg), \"est:\", int(duEstimation), \"du:\", du)",
"return",
"du",
",",
"accuracy",
",",
"nil",
"\n",
"}"
] |
// folderSize estimates the diskUsage of a folder by reading
// up to DiskUsageFilesAverage entries in it and assumming any
// other files will have an avereage size.
|
[
"folderSize",
"estimates",
"the",
"diskUsage",
"of",
"a",
"folder",
"by",
"reading",
"up",
"to",
"DiskUsageFilesAverage",
"entries",
"in",
"it",
"and",
"assumming",
"any",
"other",
"files",
"will",
"have",
"an",
"avereage",
"size",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L708-L795
|
17,130 |
ipfs/go-ds-flatfs
|
flatfs.go
|
updateDiskUsage
|
func (fs *Datastore) updateDiskUsage(path string, add bool) {
fsize := fileSize(path)
if !add {
fsize = -fsize
}
if fsize != 0 {
atomic.AddInt64(&fs.diskUsage, fsize)
fs.checkpointDiskUsage()
}
}
|
go
|
func (fs *Datastore) updateDiskUsage(path string, add bool) {
fsize := fileSize(path)
if !add {
fsize = -fsize
}
if fsize != 0 {
atomic.AddInt64(&fs.diskUsage, fsize)
fs.checkpointDiskUsage()
}
}
|
[
"func",
"(",
"fs",
"*",
"Datastore",
")",
"updateDiskUsage",
"(",
"path",
"string",
",",
"add",
"bool",
")",
"{",
"fsize",
":=",
"fileSize",
"(",
"path",
")",
"\n",
"if",
"!",
"add",
"{",
"fsize",
"=",
"-",
"fsize",
"\n",
"}",
"\n\n",
"if",
"fsize",
"!=",
"0",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"fs",
".",
"diskUsage",
",",
"fsize",
")",
"\n",
"fs",
".",
"checkpointDiskUsage",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// updateDiskUsage reads the size of path and atomically
// increases or decreases the diskUsage variable.
// setting add to false will subtract from disk usage.
|
[
"updateDiskUsage",
"reads",
"the",
"size",
"of",
"path",
"and",
"atomically",
"increases",
"or",
"decreases",
"the",
"diskUsage",
"variable",
".",
"setting",
"add",
"to",
"false",
"will",
"subtract",
"from",
"disk",
"usage",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L848-L858
|
17,131 |
ipfs/go-ds-flatfs
|
flatfs.go
|
DiskUsage
|
func (fs *Datastore) DiskUsage() (uint64, error) {
// it may differ from real disk values if
// the filesystem has allocated for blocks
// for a directory because it has many files in it
// we don't account for "resized" directories.
// In a large datastore, the differences should be
// are negligible though.
du := atomic.LoadInt64(&fs.diskUsage)
return uint64(du), nil
}
|
go
|
func (fs *Datastore) DiskUsage() (uint64, error) {
// it may differ from real disk values if
// the filesystem has allocated for blocks
// for a directory because it has many files in it
// we don't account for "resized" directories.
// In a large datastore, the differences should be
// are negligible though.
du := atomic.LoadInt64(&fs.diskUsage)
return uint64(du), nil
}
|
[
"func",
"(",
"fs",
"*",
"Datastore",
")",
"DiskUsage",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"// it may differ from real disk values if",
"// the filesystem has allocated for blocks",
"// for a directory because it has many files in it",
"// we don't account for \"resized\" directories.",
"// In a large datastore, the differences should be",
"// are negligible though.",
"du",
":=",
"atomic",
".",
"LoadInt64",
"(",
"&",
"fs",
".",
"diskUsage",
")",
"\n",
"return",
"uint64",
"(",
"du",
")",
",",
"nil",
"\n",
"}"
] |
// DiskUsage implements the PersistentDatastore interface
// and returns the current disk usage in bytes used by
// this datastore.
//
// The size is approximative and may slightly differ from
// the real disk values.
|
[
"DiskUsage",
"implements",
"the",
"PersistentDatastore",
"interface",
"and",
"returns",
"the",
"current",
"disk",
"usage",
"in",
"bytes",
"used",
"by",
"this",
"datastore",
".",
"The",
"size",
"is",
"approximative",
"and",
"may",
"slightly",
"differ",
"from",
"the",
"real",
"disk",
"values",
"."
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L977-L987
|
17,132 |
ipfs/go-ds-flatfs
|
flatfs.go
|
deactivate
|
func (fs *Datastore) deactivate() error {
fs.shutdownLock.Lock()
defer fs.shutdownLock.Unlock()
if fs.shutdown {
return nil
}
fs.shutdown = true
close(fs.checkpointCh)
<-fs.done
return nil
}
|
go
|
func (fs *Datastore) deactivate() error {
fs.shutdownLock.Lock()
defer fs.shutdownLock.Unlock()
if fs.shutdown {
return nil
}
fs.shutdown = true
close(fs.checkpointCh)
<-fs.done
return nil
}
|
[
"func",
"(",
"fs",
"*",
"Datastore",
")",
"deactivate",
"(",
")",
"error",
"{",
"fs",
".",
"shutdownLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fs",
".",
"shutdownLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"fs",
".",
"shutdown",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"fs",
".",
"shutdown",
"=",
"true",
"\n",
"close",
"(",
"fs",
".",
"checkpointCh",
")",
"\n",
"<-",
"fs",
".",
"done",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Deactivate closes background maintenance threads, most write
// operations will fail but readonly operations will continue to
// function
|
[
"Deactivate",
"closes",
"background",
"maintenance",
"threads",
"most",
"write",
"operations",
"will",
"fail",
"but",
"readonly",
"operations",
"will",
"continue",
"to",
"function"
] |
d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd
|
https://github.com/ipfs/go-ds-flatfs/blob/d5e3c1fa14d2fcc187a4a996eea3f48de9d7a5cd/flatfs.go#L1048-L1058
|
17,133 |
alexbrainman/odbc
|
param.go
|
StoreStrLen_or_IndPtr
|
func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN {
p.StrLen_or_IndPtr = v
return &p.StrLen_or_IndPtr
}
|
go
|
func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN {
p.StrLen_or_IndPtr = v
return &p.StrLen_or_IndPtr
}
|
[
"func",
"(",
"p",
"*",
"Parameter",
")",
"StoreStrLen_or_IndPtr",
"(",
"v",
"api",
".",
"SQLLEN",
")",
"*",
"api",
".",
"SQLLEN",
"{",
"p",
".",
"StrLen_or_IndPtr",
"=",
"v",
"\n",
"return",
"&",
"p",
".",
"StrLen_or_IndPtr",
"\n\n",
"}"
] |
// StoreStrLen_or_IndPtr stores v into StrLen_or_IndPtr field of p
// and returns address of that field.
|
[
"StoreStrLen_or_IndPtr",
"stores",
"v",
"into",
"StrLen_or_IndPtr",
"field",
"of",
"p",
"and",
"returns",
"address",
"of",
"that",
"field",
"."
] |
cf37ce29077901df2bcf307b80084697697fee26
|
https://github.com/alexbrainman/odbc/blob/cf37ce29077901df2bcf307b80084697697fee26/param.go#L29-L33
|
17,134 |
alexbrainman/odbc
|
utf16.go
|
utf16toutf8
|
func utf16toutf8(s []uint16) []byte {
for i, v := range s {
if v == 0 {
s = s[0:i]
break
}
}
buf := make([]byte, 0, len(s)*2) // allow 2 bytes for every rune
b := make([]byte, 4)
for i := 0; i < len(s); i++ {
var rr rune
switch r := s[i]; {
case surr1 <= r && r < surr2 && i+1 < len(s) &&
surr2 <= s[i+1] && s[i+1] < surr3:
// valid surrogate sequence
rr = utf16.DecodeRune(rune(r), rune(s[i+1]))
i++
case surr1 <= r && r < surr3:
// invalid surrogate sequence
rr = replacementChar
default:
// normal rune
rr = rune(r)
}
b := b[:cap(b)]
n := utf8.EncodeRune(b, rr)
b = b[:n]
buf = append(buf, b...)
}
return buf
}
|
go
|
func utf16toutf8(s []uint16) []byte {
for i, v := range s {
if v == 0 {
s = s[0:i]
break
}
}
buf := make([]byte, 0, len(s)*2) // allow 2 bytes for every rune
b := make([]byte, 4)
for i := 0; i < len(s); i++ {
var rr rune
switch r := s[i]; {
case surr1 <= r && r < surr2 && i+1 < len(s) &&
surr2 <= s[i+1] && s[i+1] < surr3:
// valid surrogate sequence
rr = utf16.DecodeRune(rune(r), rune(s[i+1]))
i++
case surr1 <= r && r < surr3:
// invalid surrogate sequence
rr = replacementChar
default:
// normal rune
rr = rune(r)
}
b := b[:cap(b)]
n := utf8.EncodeRune(b, rr)
b = b[:n]
buf = append(buf, b...)
}
return buf
}
|
[
"func",
"utf16toutf8",
"(",
"s",
"[",
"]",
"uint16",
")",
"[",
"]",
"byte",
"{",
"for",
"i",
",",
"v",
":=",
"range",
"s",
"{",
"if",
"v",
"==",
"0",
"{",
"s",
"=",
"s",
"[",
"0",
":",
"i",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"s",
")",
"*",
"2",
")",
"// allow 2 bytes for every rune",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"var",
"rr",
"rune",
"\n",
"switch",
"r",
":=",
"s",
"[",
"i",
"]",
";",
"{",
"case",
"surr1",
"<=",
"r",
"&&",
"r",
"<",
"surr2",
"&&",
"i",
"+",
"1",
"<",
"len",
"(",
"s",
")",
"&&",
"surr2",
"<=",
"s",
"[",
"i",
"+",
"1",
"]",
"&&",
"s",
"[",
"i",
"+",
"1",
"]",
"<",
"surr3",
":",
"// valid surrogate sequence",
"rr",
"=",
"utf16",
".",
"DecodeRune",
"(",
"rune",
"(",
"r",
")",
",",
"rune",
"(",
"s",
"[",
"i",
"+",
"1",
"]",
")",
")",
"\n",
"i",
"++",
"\n",
"case",
"surr1",
"<=",
"r",
"&&",
"r",
"<",
"surr3",
":",
"// invalid surrogate sequence",
"rr",
"=",
"replacementChar",
"\n",
"default",
":",
"// normal rune",
"rr",
"=",
"rune",
"(",
"r",
")",
"\n",
"}",
"\n",
"b",
":=",
"b",
"[",
":",
"cap",
"(",
"b",
")",
"]",
"\n",
"n",
":=",
"utf8",
".",
"EncodeRune",
"(",
"b",
",",
"rr",
")",
"\n",
"b",
"=",
"b",
"[",
":",
"n",
"]",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"b",
"...",
")",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] |
// utf16toutf8 returns the UTF-8 encoding of the UTF-16 sequence s,
// with a terminating NUL removed.
|
[
"utf16toutf8",
"returns",
"the",
"UTF",
"-",
"8",
"encoding",
"of",
"the",
"UTF",
"-",
"16",
"sequence",
"s",
"with",
"a",
"terminating",
"NUL",
"removed",
"."
] |
cf37ce29077901df2bcf307b80084697697fee26
|
https://github.com/alexbrainman/odbc/blob/cf37ce29077901df2bcf307b80084697697fee26/utf16.go#L25-L55
|
17,135 |
OpenBazaar/spvwallet
|
gui/bootstrap/server.go
|
serve
|
func serve(baseDirectoryPath string, fnR AdaptRouter, fnT TemplateData) (ln net.Listener) {
// Init router
var r = httprouter.New()
// Static files
r.ServeFiles("/static/*filepath", http.Dir(filepath.Join(baseDirectoryPath, "resources", "static")))
// Dynamic pages
r.GET("/templates/*page", handleTemplates(fnT))
// Adapt router
if fnR != nil {
fnR(r)
}
// Parse templates
var err error
if templates, err = astitemplate.ParseDirectory(filepath.Join(baseDirectoryPath, "resources", "templates"), ".html"); err != nil {
astilog.Fatal(err)
}
// Listen
if ln, err = net.Listen("tcp", "127.0.0.1:"); err != nil {
astilog.Fatal(err)
}
astilog.Debugf("Listening on %s", ln.Addr())
// Serve
go http.Serve(ln, r)
return
}
|
go
|
func serve(baseDirectoryPath string, fnR AdaptRouter, fnT TemplateData) (ln net.Listener) {
// Init router
var r = httprouter.New()
// Static files
r.ServeFiles("/static/*filepath", http.Dir(filepath.Join(baseDirectoryPath, "resources", "static")))
// Dynamic pages
r.GET("/templates/*page", handleTemplates(fnT))
// Adapt router
if fnR != nil {
fnR(r)
}
// Parse templates
var err error
if templates, err = astitemplate.ParseDirectory(filepath.Join(baseDirectoryPath, "resources", "templates"), ".html"); err != nil {
astilog.Fatal(err)
}
// Listen
if ln, err = net.Listen("tcp", "127.0.0.1:"); err != nil {
astilog.Fatal(err)
}
astilog.Debugf("Listening on %s", ln.Addr())
// Serve
go http.Serve(ln, r)
return
}
|
[
"func",
"serve",
"(",
"baseDirectoryPath",
"string",
",",
"fnR",
"AdaptRouter",
",",
"fnT",
"TemplateData",
")",
"(",
"ln",
"net",
".",
"Listener",
")",
"{",
"// Init router",
"var",
"r",
"=",
"httprouter",
".",
"New",
"(",
")",
"\n\n",
"// Static files",
"r",
".",
"ServeFiles",
"(",
"\"",
"\"",
",",
"http",
".",
"Dir",
"(",
"filepath",
".",
"Join",
"(",
"baseDirectoryPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
")",
")",
"\n\n",
"// Dynamic pages",
"r",
".",
"GET",
"(",
"\"",
"\"",
",",
"handleTemplates",
"(",
"fnT",
")",
")",
"\n\n",
"// Adapt router",
"if",
"fnR",
"!=",
"nil",
"{",
"fnR",
"(",
"r",
")",
"\n",
"}",
"\n\n",
"// Parse templates",
"var",
"err",
"error",
"\n",
"if",
"templates",
",",
"err",
"=",
"astitemplate",
".",
"ParseDirectory",
"(",
"filepath",
".",
"Join",
"(",
"baseDirectoryPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"astilog",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Listen",
"if",
"ln",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"astilog",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"astilog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"ln",
".",
"Addr",
"(",
")",
")",
"\n\n",
"// Serve",
"go",
"http",
".",
"Serve",
"(",
"ln",
",",
"r",
")",
"\n",
"return",
"\n",
"}"
] |
// serve initialize an HTTP server
|
[
"serve",
"initialize",
"an",
"HTTP",
"server"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/gui/bootstrap/server.go#L21-L51
|
17,136 |
OpenBazaar/spvwallet
|
gui/bootstrap/server.go
|
handleTemplates
|
func handleTemplates(fn TemplateData) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Check if template exists
var name = p.ByName("page") + ".html"
if templates.Lookup(name) == nil {
rw.WriteHeader(http.StatusNotFound)
return
}
// Get data
var d interface{}
var err error
if fn != nil {
if d, err = fn(name, r, p); err != nil {
astilog.Errorf("%s while retrieving data for template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
// Execute template
if err = templates.ExecuteTemplate(rw, name, d); err != nil {
astilog.Errorf("%s while handling template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
|
go
|
func handleTemplates(fn TemplateData) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Check if template exists
var name = p.ByName("page") + ".html"
if templates.Lookup(name) == nil {
rw.WriteHeader(http.StatusNotFound)
return
}
// Get data
var d interface{}
var err error
if fn != nil {
if d, err = fn(name, r, p); err != nil {
astilog.Errorf("%s while retrieving data for template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
// Execute template
if err = templates.ExecuteTemplate(rw, name, d); err != nil {
astilog.Errorf("%s while handling template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
|
[
"func",
"handleTemplates",
"(",
"fn",
"TemplateData",
")",
"httprouter",
".",
"Handle",
"{",
"return",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"// Check if template exists",
"var",
"name",
"=",
"p",
".",
"ByName",
"(",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"\n",
"if",
"templates",
".",
"Lookup",
"(",
"name",
")",
"==",
"nil",
"{",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get data",
"var",
"d",
"interface",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"fn",
"!=",
"nil",
"{",
"if",
"d",
",",
"err",
"=",
"fn",
"(",
"name",
",",
"r",
",",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"astilog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"name",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Execute template",
"if",
"err",
"=",
"templates",
".",
"ExecuteTemplate",
"(",
"rw",
",",
"name",
",",
"d",
")",
";",
"err",
"!=",
"nil",
"{",
"astilog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"name",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// handleTemplate handles templates
|
[
"handleTemplate",
"handles",
"templates"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/gui/bootstrap/server.go#L54-L81
|
17,137 |
OpenBazaar/spvwallet
|
eight333.go
|
Start
|
func (ws *WireService) Start() {
ws.quit = make(chan struct{})
best, err := ws.chain.BestBlock()
if err != nil {
log.Error(err)
}
log.Infof("Starting wire service at height %d", int(best.height))
out:
for {
select {
case m := <-ws.msgChan:
switch msg := m.(type) {
case newPeerMsg:
ws.handleNewPeerMsg(msg.peer)
case donePeerMsg:
ws.handleDonePeerMsg(msg.peer)
case headersMsg:
ws.handleHeadersMsg(&msg)
case merkleBlockMsg:
ws.handleMerkleBlockMsg(&msg)
case invMsg:
ws.handleInvMsg(&msg)
case txMsg:
ws.handleTxMsg(&msg)
case updateFiltersMsg:
ws.handleUpdateFiltersMsg()
default:
log.Warningf("Unknown message type sent to WireService message chan: %T", msg)
}
case <-ws.quit:
break out
}
}
}
|
go
|
func (ws *WireService) Start() {
ws.quit = make(chan struct{})
best, err := ws.chain.BestBlock()
if err != nil {
log.Error(err)
}
log.Infof("Starting wire service at height %d", int(best.height))
out:
for {
select {
case m := <-ws.msgChan:
switch msg := m.(type) {
case newPeerMsg:
ws.handleNewPeerMsg(msg.peer)
case donePeerMsg:
ws.handleDonePeerMsg(msg.peer)
case headersMsg:
ws.handleHeadersMsg(&msg)
case merkleBlockMsg:
ws.handleMerkleBlockMsg(&msg)
case invMsg:
ws.handleInvMsg(&msg)
case txMsg:
ws.handleTxMsg(&msg)
case updateFiltersMsg:
ws.handleUpdateFiltersMsg()
default:
log.Warningf("Unknown message type sent to WireService message chan: %T", msg)
}
case <-ws.quit:
break out
}
}
}
|
[
"func",
"(",
"ws",
"*",
"WireService",
")",
"Start",
"(",
")",
"{",
"ws",
".",
"quit",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"best",
",",
"err",
":=",
"ws",
".",
"chain",
".",
"BestBlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"int",
"(",
"best",
".",
"height",
")",
")",
"\n",
"out",
":",
"for",
"{",
"select",
"{",
"case",
"m",
":=",
"<-",
"ws",
".",
"msgChan",
":",
"switch",
"msg",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"newPeerMsg",
":",
"ws",
".",
"handleNewPeerMsg",
"(",
"msg",
".",
"peer",
")",
"\n",
"case",
"donePeerMsg",
":",
"ws",
".",
"handleDonePeerMsg",
"(",
"msg",
".",
"peer",
")",
"\n",
"case",
"headersMsg",
":",
"ws",
".",
"handleHeadersMsg",
"(",
"&",
"msg",
")",
"\n",
"case",
"merkleBlockMsg",
":",
"ws",
".",
"handleMerkleBlockMsg",
"(",
"&",
"msg",
")",
"\n",
"case",
"invMsg",
":",
"ws",
".",
"handleInvMsg",
"(",
"&",
"msg",
")",
"\n",
"case",
"txMsg",
":",
"ws",
".",
"handleTxMsg",
"(",
"&",
"msg",
")",
"\n",
"case",
"updateFiltersMsg",
":",
"ws",
".",
"handleUpdateFiltersMsg",
"(",
")",
"\n",
"default",
":",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"msg",
")",
"\n",
"}",
"\n",
"case",
"<-",
"ws",
".",
"quit",
":",
"break",
"out",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// The start function must be run in its own goroutine. The entire WireService is single
// threaded which means all messages are processed sequentially removing the need for complex
// locking.
|
[
"The",
"start",
"function",
"must",
"be",
"run",
"in",
"its",
"own",
"goroutine",
".",
"The",
"entire",
"WireService",
"is",
"single",
"threaded",
"which",
"means",
"all",
"messages",
"are",
"processed",
"sequentially",
"removing",
"the",
"need",
"for",
"complex",
"locking",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/eight333.go#L120-L153
|
17,138 |
OpenBazaar/spvwallet
|
gui/bootstrap/message.go
|
handleMessages
|
func handleMessages(w *astilectron.Window, messageHandler MessageHandler) astilectron.ListenerMessage {
return func(e *astilectron.EventMessage) (v interface{}) {
// Unmarshal message
var m MessageIn
var err error
if err = e.Unmarshal(&m); err != nil {
astilog.Errorf("Unmarshaling message %+v failed", *e)
return
}
// Handle message
messageHandler(w, m)
return
}
}
|
go
|
func handleMessages(w *astilectron.Window, messageHandler MessageHandler) astilectron.ListenerMessage {
return func(e *astilectron.EventMessage) (v interface{}) {
// Unmarshal message
var m MessageIn
var err error
if err = e.Unmarshal(&m); err != nil {
astilog.Errorf("Unmarshaling message %+v failed", *e)
return
}
// Handle message
messageHandler(w, m)
return
}
}
|
[
"func",
"handleMessages",
"(",
"w",
"*",
"astilectron",
".",
"Window",
",",
"messageHandler",
"MessageHandler",
")",
"astilectron",
".",
"ListenerMessage",
"{",
"return",
"func",
"(",
"e",
"*",
"astilectron",
".",
"EventMessage",
")",
"(",
"v",
"interface",
"{",
"}",
")",
"{",
"// Unmarshal message",
"var",
"m",
"MessageIn",
"\n",
"var",
"err",
"error",
"\n",
"if",
"err",
"=",
"e",
".",
"Unmarshal",
"(",
"&",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"astilog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"e",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Handle message",
"messageHandler",
"(",
"w",
",",
"m",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// handleMessages handles messages
|
[
"handleMessages",
"handles",
"messages"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/gui/bootstrap/message.go#L23-L37
|
17,139 |
OpenBazaar/spvwallet
|
sortsignsend.go
|
EstimateSpendFee
|
func (w *SPVWallet) EstimateSpendFee(amount int64, feeLevel wallet.FeeLevel) (uint64, error) {
// Since this is an estimate we can use a dummy output address. Let's use a long one so we don't under estimate.
addr, err := btc.DecodeAddress("bc1qxtq7ha2l5qg70atpwp3fus84fx3w0v2w4r2my7gt89ll3w0vnlgspu349h", w.params)
if err != nil {
return 0, err
}
tx, err := w.buildTx(amount, addr, feeLevel, nil)
if err != nil {
return 0, err
}
var outval int64
for _, output := range tx.TxOut {
outval += output.Value
}
var inval int64
utxos, err := w.txstore.Utxos().GetAll()
if err != nil {
return 0, err
}
for _, input := range tx.TxIn {
for _, utxo := range utxos {
if utxo.Op.Hash.IsEqual(&input.PreviousOutPoint.Hash) && utxo.Op.Index == input.PreviousOutPoint.Index {
inval += utxo.Value
break
}
}
}
if inval < outval {
return 0, errors.New("Error building transaction: inputs less than outputs")
}
return uint64(inval - outval), err
}
|
go
|
func (w *SPVWallet) EstimateSpendFee(amount int64, feeLevel wallet.FeeLevel) (uint64, error) {
// Since this is an estimate we can use a dummy output address. Let's use a long one so we don't under estimate.
addr, err := btc.DecodeAddress("bc1qxtq7ha2l5qg70atpwp3fus84fx3w0v2w4r2my7gt89ll3w0vnlgspu349h", w.params)
if err != nil {
return 0, err
}
tx, err := w.buildTx(amount, addr, feeLevel, nil)
if err != nil {
return 0, err
}
var outval int64
for _, output := range tx.TxOut {
outval += output.Value
}
var inval int64
utxos, err := w.txstore.Utxos().GetAll()
if err != nil {
return 0, err
}
for _, input := range tx.TxIn {
for _, utxo := range utxos {
if utxo.Op.Hash.IsEqual(&input.PreviousOutPoint.Hash) && utxo.Op.Index == input.PreviousOutPoint.Index {
inval += utxo.Value
break
}
}
}
if inval < outval {
return 0, errors.New("Error building transaction: inputs less than outputs")
}
return uint64(inval - outval), err
}
|
[
"func",
"(",
"w",
"*",
"SPVWallet",
")",
"EstimateSpendFee",
"(",
"amount",
"int64",
",",
"feeLevel",
"wallet",
".",
"FeeLevel",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"// Since this is an estimate we can use a dummy output address. Let's use a long one so we don't under estimate.",
"addr",
",",
"err",
":=",
"btc",
".",
"DecodeAddress",
"(",
"\"",
"\"",
",",
"w",
".",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"w",
".",
"buildTx",
"(",
"amount",
",",
"addr",
",",
"feeLevel",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"var",
"outval",
"int64",
"\n",
"for",
"_",
",",
"output",
":=",
"range",
"tx",
".",
"TxOut",
"{",
"outval",
"+=",
"output",
".",
"Value",
"\n",
"}",
"\n",
"var",
"inval",
"int64",
"\n",
"utxos",
",",
"err",
":=",
"w",
".",
"txstore",
".",
"Utxos",
"(",
")",
".",
"GetAll",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"input",
":=",
"range",
"tx",
".",
"TxIn",
"{",
"for",
"_",
",",
"utxo",
":=",
"range",
"utxos",
"{",
"if",
"utxo",
".",
"Op",
".",
"Hash",
".",
"IsEqual",
"(",
"&",
"input",
".",
"PreviousOutPoint",
".",
"Hash",
")",
"&&",
"utxo",
".",
"Op",
".",
"Index",
"==",
"input",
".",
"PreviousOutPoint",
".",
"Index",
"{",
"inval",
"+=",
"utxo",
".",
"Value",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"inval",
"<",
"outval",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"uint64",
"(",
"inval",
"-",
"outval",
")",
",",
"err",
"\n",
"}"
] |
// Build a spend transaction for the amount and return the transaction fee
|
[
"Build",
"a",
"spend",
"transaction",
"for",
"the",
"amount",
"and",
"return",
"the",
"transaction",
"fee"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/sortsignsend.go#L232-L263
|
17,140 |
OpenBazaar/spvwallet
|
txstore.go
|
GimmeFilter
|
func (ts *TxStore) GimmeFilter() (*bloom.Filter, error) {
ts.PopulateAdrs()
// get all utxos to add outpoints to filter
allUtxos, err := ts.Utxos().GetAll()
if err != nil {
return nil, err
}
allStxos, err := ts.Stxos().GetAll()
if err != nil {
return nil, err
}
ts.addrMutex.Lock()
elem := uint32(len(ts.adrs)+len(allUtxos)+len(allStxos)) + uint32(len(ts.watchedScripts))
f := bloom.NewFilter(elem, 0, 0.00003, wire.BloomUpdateAll)
// note there could be false positives since we're just looking
// for the 20 byte PKH without the opcodes.
for _, a := range ts.adrs { // add 20-byte pubkeyhash
f.Add(a.ScriptAddress())
}
ts.addrMutex.Unlock()
for _, u := range allUtxos {
f.AddOutPoint(&u.Op)
}
for _, s := range allStxos {
f.AddOutPoint(&s.Utxo.Op)
}
for _, w := range ts.watchedScripts {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(w, ts.params)
if err != nil {
continue
}
f.Add(addrs[0].ScriptAddress())
}
return f, nil
}
|
go
|
func (ts *TxStore) GimmeFilter() (*bloom.Filter, error) {
ts.PopulateAdrs()
// get all utxos to add outpoints to filter
allUtxos, err := ts.Utxos().GetAll()
if err != nil {
return nil, err
}
allStxos, err := ts.Stxos().GetAll()
if err != nil {
return nil, err
}
ts.addrMutex.Lock()
elem := uint32(len(ts.adrs)+len(allUtxos)+len(allStxos)) + uint32(len(ts.watchedScripts))
f := bloom.NewFilter(elem, 0, 0.00003, wire.BloomUpdateAll)
// note there could be false positives since we're just looking
// for the 20 byte PKH without the opcodes.
for _, a := range ts.adrs { // add 20-byte pubkeyhash
f.Add(a.ScriptAddress())
}
ts.addrMutex.Unlock()
for _, u := range allUtxos {
f.AddOutPoint(&u.Op)
}
for _, s := range allStxos {
f.AddOutPoint(&s.Utxo.Op)
}
for _, w := range ts.watchedScripts {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(w, ts.params)
if err != nil {
continue
}
f.Add(addrs[0].ScriptAddress())
}
return f, nil
}
|
[
"func",
"(",
"ts",
"*",
"TxStore",
")",
"GimmeFilter",
"(",
")",
"(",
"*",
"bloom",
".",
"Filter",
",",
"error",
")",
"{",
"ts",
".",
"PopulateAdrs",
"(",
")",
"\n\n",
"// get all utxos to add outpoints to filter",
"allUtxos",
",",
"err",
":=",
"ts",
".",
"Utxos",
"(",
")",
".",
"GetAll",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"allStxos",
",",
"err",
":=",
"ts",
".",
"Stxos",
"(",
")",
".",
"GetAll",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ts",
".",
"addrMutex",
".",
"Lock",
"(",
")",
"\n",
"elem",
":=",
"uint32",
"(",
"len",
"(",
"ts",
".",
"adrs",
")",
"+",
"len",
"(",
"allUtxos",
")",
"+",
"len",
"(",
"allStxos",
")",
")",
"+",
"uint32",
"(",
"len",
"(",
"ts",
".",
"watchedScripts",
")",
")",
"\n",
"f",
":=",
"bloom",
".",
"NewFilter",
"(",
"elem",
",",
"0",
",",
"0.00003",
",",
"wire",
".",
"BloomUpdateAll",
")",
"\n\n",
"// note there could be false positives since we're just looking",
"// for the 20 byte PKH without the opcodes.",
"for",
"_",
",",
"a",
":=",
"range",
"ts",
".",
"adrs",
"{",
"// add 20-byte pubkeyhash",
"f",
".",
"Add",
"(",
"a",
".",
"ScriptAddress",
"(",
")",
")",
"\n",
"}",
"\n",
"ts",
".",
"addrMutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"u",
":=",
"range",
"allUtxos",
"{",
"f",
".",
"AddOutPoint",
"(",
"&",
"u",
".",
"Op",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"allStxos",
"{",
"f",
".",
"AddOutPoint",
"(",
"&",
"s",
".",
"Utxo",
".",
"Op",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"ts",
".",
"watchedScripts",
"{",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"w",
",",
"ts",
".",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"f",
".",
"Add",
"(",
"addrs",
"[",
"0",
"]",
".",
"ScriptAddress",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] |
// ... or I'm gonna fade away
|
[
"...",
"or",
"I",
"m",
"gonna",
"fade",
"away"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/txstore.go#L56-L95
|
17,141 |
OpenBazaar/spvwallet
|
txstore.go
|
CheckDoubleSpends
|
func (ts *TxStore) CheckDoubleSpends(argTx *wire.MsgTx) ([]*chainhash.Hash, error) {
var dubs []*chainhash.Hash // slice of all double-spent txs
argTxid := argTx.TxHash()
txs, err := ts.Txns().GetAll(true)
if err != nil {
return dubs, err
}
for _, compTx := range txs {
if compTx.Height < 0 {
continue
}
r := bytes.NewReader(compTx.Bytes)
msgTx := wire.NewMsgTx(1)
msgTx.BtcDecode(r, 1, wire.WitnessEncoding)
compTxid := msgTx.TxHash()
for _, argIn := range argTx.TxIn {
// iterate through inputs of compTx
for _, compIn := range msgTx.TxIn {
if outPointsEqual(argIn.PreviousOutPoint, compIn.PreviousOutPoint) && !compTxid.IsEqual(&argTxid) {
// found double spend
dubs = append(dubs, &compTxid)
break // back to argIn loop
}
}
}
}
return dubs, nil
}
|
go
|
func (ts *TxStore) CheckDoubleSpends(argTx *wire.MsgTx) ([]*chainhash.Hash, error) {
var dubs []*chainhash.Hash // slice of all double-spent txs
argTxid := argTx.TxHash()
txs, err := ts.Txns().GetAll(true)
if err != nil {
return dubs, err
}
for _, compTx := range txs {
if compTx.Height < 0 {
continue
}
r := bytes.NewReader(compTx.Bytes)
msgTx := wire.NewMsgTx(1)
msgTx.BtcDecode(r, 1, wire.WitnessEncoding)
compTxid := msgTx.TxHash()
for _, argIn := range argTx.TxIn {
// iterate through inputs of compTx
for _, compIn := range msgTx.TxIn {
if outPointsEqual(argIn.PreviousOutPoint, compIn.PreviousOutPoint) && !compTxid.IsEqual(&argTxid) {
// found double spend
dubs = append(dubs, &compTxid)
break // back to argIn loop
}
}
}
}
return dubs, nil
}
|
[
"func",
"(",
"ts",
"*",
"TxStore",
")",
"CheckDoubleSpends",
"(",
"argTx",
"*",
"wire",
".",
"MsgTx",
")",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"var",
"dubs",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
"// slice of all double-spent txs",
"\n",
"argTxid",
":=",
"argTx",
".",
"TxHash",
"(",
")",
"\n",
"txs",
",",
"err",
":=",
"ts",
".",
"Txns",
"(",
")",
".",
"GetAll",
"(",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"dubs",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"compTx",
":=",
"range",
"txs",
"{",
"if",
"compTx",
".",
"Height",
"<",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"r",
":=",
"bytes",
".",
"NewReader",
"(",
"compTx",
".",
"Bytes",
")",
"\n",
"msgTx",
":=",
"wire",
".",
"NewMsgTx",
"(",
"1",
")",
"\n",
"msgTx",
".",
"BtcDecode",
"(",
"r",
",",
"1",
",",
"wire",
".",
"WitnessEncoding",
")",
"\n",
"compTxid",
":=",
"msgTx",
".",
"TxHash",
"(",
")",
"\n",
"for",
"_",
",",
"argIn",
":=",
"range",
"argTx",
".",
"TxIn",
"{",
"// iterate through inputs of compTx",
"for",
"_",
",",
"compIn",
":=",
"range",
"msgTx",
".",
"TxIn",
"{",
"if",
"outPointsEqual",
"(",
"argIn",
".",
"PreviousOutPoint",
",",
"compIn",
".",
"PreviousOutPoint",
")",
"&&",
"!",
"compTxid",
".",
"IsEqual",
"(",
"&",
"argTxid",
")",
"{",
"// found double spend",
"dubs",
"=",
"append",
"(",
"dubs",
",",
"&",
"compTxid",
")",
"\n",
"break",
"// back to argIn loop",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"dubs",
",",
"nil",
"\n",
"}"
] |
// CheckDoubleSpends takes a transaction and compares it with
// all transactions in the db. It returns a slice of all txids in the db
// which are double spent by the received tx.
|
[
"CheckDoubleSpends",
"takes",
"a",
"transaction",
"and",
"compares",
"it",
"with",
"all",
"transactions",
"in",
"the",
"db",
".",
"It",
"returns",
"a",
"slice",
"of",
"all",
"txids",
"in",
"the",
"db",
"which",
"are",
"double",
"spent",
"by",
"the",
"received",
"tx",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/txstore.go#L100-L127
|
17,142 |
OpenBazaar/spvwallet
|
txstore.go
|
PopulateAdrs
|
func (ts *TxStore) PopulateAdrs() error {
keys := ts.keyManager.GetKeys()
ts.addrMutex.Lock()
ts.adrs = []btcutil.Address{}
for _, k := range keys {
addr, err := k.Address(ts.params)
if err != nil {
continue
}
ts.adrs = append(ts.adrs, addr)
}
ts.addrMutex.Unlock()
ts.watchedScripts, _ = ts.WatchedScripts().GetAll()
txns, _ := ts.Txns().GetAll(true)
ts.txidsMutex.Lock()
for _, t := range txns {
ts.txids[t.Txid] = t.Height
}
ts.txidsMutex.Unlock()
return nil
}
|
go
|
func (ts *TxStore) PopulateAdrs() error {
keys := ts.keyManager.GetKeys()
ts.addrMutex.Lock()
ts.adrs = []btcutil.Address{}
for _, k := range keys {
addr, err := k.Address(ts.params)
if err != nil {
continue
}
ts.adrs = append(ts.adrs, addr)
}
ts.addrMutex.Unlock()
ts.watchedScripts, _ = ts.WatchedScripts().GetAll()
txns, _ := ts.Txns().GetAll(true)
ts.txidsMutex.Lock()
for _, t := range txns {
ts.txids[t.Txid] = t.Height
}
ts.txidsMutex.Unlock()
return nil
}
|
[
"func",
"(",
"ts",
"*",
"TxStore",
")",
"PopulateAdrs",
"(",
")",
"error",
"{",
"keys",
":=",
"ts",
".",
"keyManager",
".",
"GetKeys",
"(",
")",
"\n",
"ts",
".",
"addrMutex",
".",
"Lock",
"(",
")",
"\n",
"ts",
".",
"adrs",
"=",
"[",
"]",
"btcutil",
".",
"Address",
"{",
"}",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"keys",
"{",
"addr",
",",
"err",
":=",
"k",
".",
"Address",
"(",
"ts",
".",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"ts",
".",
"adrs",
"=",
"append",
"(",
"ts",
".",
"adrs",
",",
"addr",
")",
"\n",
"}",
"\n",
"ts",
".",
"addrMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"ts",
".",
"watchedScripts",
",",
"_",
"=",
"ts",
".",
"WatchedScripts",
"(",
")",
".",
"GetAll",
"(",
")",
"\n",
"txns",
",",
"_",
":=",
"ts",
".",
"Txns",
"(",
")",
".",
"GetAll",
"(",
"true",
")",
"\n",
"ts",
".",
"txidsMutex",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"txns",
"{",
"ts",
".",
"txids",
"[",
"t",
".",
"Txid",
"]",
"=",
"t",
".",
"Height",
"\n",
"}",
"\n",
"ts",
".",
"txidsMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// PopulateAdrs just puts a bunch of adrs in ram; it doesn't touch the DB
|
[
"PopulateAdrs",
"just",
"puts",
"a",
"bunch",
"of",
"adrs",
"in",
"ram",
";",
"it",
"doesn",
"t",
"touch",
"the",
"DB"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/txstore.go#L172-L194
|
17,143 |
OpenBazaar/spvwallet
|
mblock.go
|
inDeadZone
|
func inDeadZone(pos, size uint32) bool {
msb := nextPowerOfTwo(size)
last := size - 1 // last valid position is 1 less than size
if pos > (msb<<1)-2 { // greater than root; not even in the tree
log.Debug(" ?? greater than root ")
return true
}
h := msb
for pos >= h {
h = h>>1 | msb
last = last>>1 | msb
}
return pos > last
}
|
go
|
func inDeadZone(pos, size uint32) bool {
msb := nextPowerOfTwo(size)
last := size - 1 // last valid position is 1 less than size
if pos > (msb<<1)-2 { // greater than root; not even in the tree
log.Debug(" ?? greater than root ")
return true
}
h := msb
for pos >= h {
h = h>>1 | msb
last = last>>1 | msb
}
return pos > last
}
|
[
"func",
"inDeadZone",
"(",
"pos",
",",
"size",
"uint32",
")",
"bool",
"{",
"msb",
":=",
"nextPowerOfTwo",
"(",
"size",
")",
"\n",
"last",
":=",
"size",
"-",
"1",
"// last valid position is 1 less than size",
"\n",
"if",
"pos",
">",
"(",
"msb",
"<<",
"1",
")",
"-",
"2",
"{",
"// greater than root; not even in the tree",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"h",
":=",
"msb",
"\n",
"for",
"pos",
">=",
"h",
"{",
"h",
"=",
"h",
">>",
"1",
"|",
"msb",
"\n",
"last",
"=",
"last",
">>",
"1",
"|",
"msb",
"\n",
"}",
"\n",
"return",
"pos",
">",
"last",
"\n",
"}"
] |
// check if a node is populated based on node position and size of tree
|
[
"check",
"if",
"a",
"node",
"is",
"populated",
"based",
"on",
"node",
"position",
"and",
"size",
"of",
"tree"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/mblock.go#L53-L66
|
17,144 |
OpenBazaar/spvwallet
|
keys.go
|
MarkKeyAsUsed
|
func (km *KeyManager) MarkKeyAsUsed(scriptAddress []byte) error {
if err := km.datastore.MarkKeyAsUsed(scriptAddress); err != nil {
return err
}
return km.lookahead()
}
|
go
|
func (km *KeyManager) MarkKeyAsUsed(scriptAddress []byte) error {
if err := km.datastore.MarkKeyAsUsed(scriptAddress); err != nil {
return err
}
return km.lookahead()
}
|
[
"func",
"(",
"km",
"*",
"KeyManager",
")",
"MarkKeyAsUsed",
"(",
"scriptAddress",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"err",
":=",
"km",
".",
"datastore",
".",
"MarkKeyAsUsed",
"(",
"scriptAddress",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"km",
".",
"lookahead",
"(",
")",
"\n",
"}"
] |
// Mark the given key as used and extend the lookahead window
|
[
"Mark",
"the",
"given",
"key",
"as",
"used",
"and",
"extend",
"the",
"lookahead",
"window"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/keys.go#L145-L150
|
17,145 |
OpenBazaar/spvwallet
|
blockchain.go
|
calcRequiredWork
|
func (b *Blockchain) calcRequiredWork(header wire.BlockHeader, height int32, prevHeader StoredHeader) (uint32, error) {
// If this is not a difficulty adjustment period
if height%epochLength != 0 {
// If we are on testnet
if b.params.ReduceMinDifficulty {
// If it's been more than 20 minutes since the last header return the minimum difficulty
if header.Timestamp.After(prevHeader.header.Timestamp.Add(targetSpacing * 2)) {
return b.params.PowLimitBits, nil
} else { // Otherwise return the difficulty of the last block not using special difficulty rules
for {
var err error = nil
for err == nil && int32(prevHeader.height)%epochLength != 0 && prevHeader.header.Bits == b.params.PowLimitBits {
var sh StoredHeader
sh, err = b.db.GetPreviousHeader(prevHeader.header)
// Error should only be non-nil if prevHeader is the checkpoint.
// In that case we should just return checkpoint bits
if err == nil {
prevHeader = sh
}
}
return prevHeader.header.Bits, nil
}
}
}
// Just return the bits from the last header
return prevHeader.header.Bits, nil
}
// We are on a difficulty adjustment period so we need to correctly calculate the new difficulty.
epoch, err := b.GetEpoch()
if err != nil {
log.Error(err)
return 0, err
}
return calcDiffAdjust(*epoch, prevHeader.header, b.params), nil
}
|
go
|
func (b *Blockchain) calcRequiredWork(header wire.BlockHeader, height int32, prevHeader StoredHeader) (uint32, error) {
// If this is not a difficulty adjustment period
if height%epochLength != 0 {
// If we are on testnet
if b.params.ReduceMinDifficulty {
// If it's been more than 20 minutes since the last header return the minimum difficulty
if header.Timestamp.After(prevHeader.header.Timestamp.Add(targetSpacing * 2)) {
return b.params.PowLimitBits, nil
} else { // Otherwise return the difficulty of the last block not using special difficulty rules
for {
var err error = nil
for err == nil && int32(prevHeader.height)%epochLength != 0 && prevHeader.header.Bits == b.params.PowLimitBits {
var sh StoredHeader
sh, err = b.db.GetPreviousHeader(prevHeader.header)
// Error should only be non-nil if prevHeader is the checkpoint.
// In that case we should just return checkpoint bits
if err == nil {
prevHeader = sh
}
}
return prevHeader.header.Bits, nil
}
}
}
// Just return the bits from the last header
return prevHeader.header.Bits, nil
}
// We are on a difficulty adjustment period so we need to correctly calculate the new difficulty.
epoch, err := b.GetEpoch()
if err != nil {
log.Error(err)
return 0, err
}
return calcDiffAdjust(*epoch, prevHeader.header, b.params), nil
}
|
[
"func",
"(",
"b",
"*",
"Blockchain",
")",
"calcRequiredWork",
"(",
"header",
"wire",
".",
"BlockHeader",
",",
"height",
"int32",
",",
"prevHeader",
"StoredHeader",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"// If this is not a difficulty adjustment period",
"if",
"height",
"%",
"epochLength",
"!=",
"0",
"{",
"// If we are on testnet",
"if",
"b",
".",
"params",
".",
"ReduceMinDifficulty",
"{",
"// If it's been more than 20 minutes since the last header return the minimum difficulty",
"if",
"header",
".",
"Timestamp",
".",
"After",
"(",
"prevHeader",
".",
"header",
".",
"Timestamp",
".",
"Add",
"(",
"targetSpacing",
"*",
"2",
")",
")",
"{",
"return",
"b",
".",
"params",
".",
"PowLimitBits",
",",
"nil",
"\n",
"}",
"else",
"{",
"// Otherwise return the difficulty of the last block not using special difficulty rules",
"for",
"{",
"var",
"err",
"error",
"=",
"nil",
"\n",
"for",
"err",
"==",
"nil",
"&&",
"int32",
"(",
"prevHeader",
".",
"height",
")",
"%",
"epochLength",
"!=",
"0",
"&&",
"prevHeader",
".",
"header",
".",
"Bits",
"==",
"b",
".",
"params",
".",
"PowLimitBits",
"{",
"var",
"sh",
"StoredHeader",
"\n",
"sh",
",",
"err",
"=",
"b",
".",
"db",
".",
"GetPreviousHeader",
"(",
"prevHeader",
".",
"header",
")",
"\n",
"// Error should only be non-nil if prevHeader is the checkpoint.",
"// In that case we should just return checkpoint bits",
"if",
"err",
"==",
"nil",
"{",
"prevHeader",
"=",
"sh",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"prevHeader",
".",
"header",
".",
"Bits",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Just return the bits from the last header",
"return",
"prevHeader",
".",
"header",
".",
"Bits",
",",
"nil",
"\n",
"}",
"\n",
"// We are on a difficulty adjustment period so we need to correctly calculate the new difficulty.",
"epoch",
",",
"err",
":=",
"b",
".",
"GetEpoch",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"calcDiffAdjust",
"(",
"*",
"epoch",
",",
"prevHeader",
".",
"header",
",",
"b",
".",
"params",
")",
",",
"nil",
"\n",
"}"
] |
// Get the PoW target this block should meet. We may need to handle a difficulty adjustment
// or testnet difficulty rules.
|
[
"Get",
"the",
"PoW",
"target",
"this",
"block",
"should",
"meet",
".",
"We",
"may",
"need",
"to",
"handle",
"a",
"difficulty",
"adjustment",
"or",
"testnet",
"difficulty",
"rules",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/blockchain.go#L170-L205
|
17,146 |
OpenBazaar/spvwallet
|
blockchain.go
|
GetCommonAncestor
|
func (b *Blockchain) GetCommonAncestor(bestHeader, prevBestHeader StoredHeader) (*StoredHeader, error) {
var err error
rollback := func(parent StoredHeader, n int) (StoredHeader, error) {
for i := 0; i < n; i++ {
parent, err = b.db.GetPreviousHeader(parent.header)
if err != nil {
return parent, err
}
}
return parent, nil
}
majority := bestHeader
minority := prevBestHeader
if bestHeader.height > prevBestHeader.height {
majority, err = rollback(majority, int(bestHeader.height-prevBestHeader.height))
if err != nil {
return nil, err
}
} else if prevBestHeader.height > bestHeader.height {
minority, err = rollback(minority, int(prevBestHeader.height-bestHeader.height))
if err != nil {
return nil, err
}
}
for {
majorityHash := majority.header.BlockHash()
minorityHash := minority.header.BlockHash()
if majorityHash.IsEqual(&minorityHash) {
return &majority, nil
}
majority, err = b.db.GetPreviousHeader(majority.header)
if err != nil {
return nil, err
}
minority, err = b.db.GetPreviousHeader(minority.header)
if err != nil {
return nil, err
}
}
}
|
go
|
func (b *Blockchain) GetCommonAncestor(bestHeader, prevBestHeader StoredHeader) (*StoredHeader, error) {
var err error
rollback := func(parent StoredHeader, n int) (StoredHeader, error) {
for i := 0; i < n; i++ {
parent, err = b.db.GetPreviousHeader(parent.header)
if err != nil {
return parent, err
}
}
return parent, nil
}
majority := bestHeader
minority := prevBestHeader
if bestHeader.height > prevBestHeader.height {
majority, err = rollback(majority, int(bestHeader.height-prevBestHeader.height))
if err != nil {
return nil, err
}
} else if prevBestHeader.height > bestHeader.height {
minority, err = rollback(minority, int(prevBestHeader.height-bestHeader.height))
if err != nil {
return nil, err
}
}
for {
majorityHash := majority.header.BlockHash()
minorityHash := minority.header.BlockHash()
if majorityHash.IsEqual(&minorityHash) {
return &majority, nil
}
majority, err = b.db.GetPreviousHeader(majority.header)
if err != nil {
return nil, err
}
minority, err = b.db.GetPreviousHeader(minority.header)
if err != nil {
return nil, err
}
}
}
|
[
"func",
"(",
"b",
"*",
"Blockchain",
")",
"GetCommonAncestor",
"(",
"bestHeader",
",",
"prevBestHeader",
"StoredHeader",
")",
"(",
"*",
"StoredHeader",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"rollback",
":=",
"func",
"(",
"parent",
"StoredHeader",
",",
"n",
"int",
")",
"(",
"StoredHeader",
",",
"error",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"parent",
",",
"err",
"=",
"b",
".",
"db",
".",
"GetPreviousHeader",
"(",
"parent",
".",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"parent",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"parent",
",",
"nil",
"\n",
"}",
"\n\n",
"majority",
":=",
"bestHeader",
"\n",
"minority",
":=",
"prevBestHeader",
"\n",
"if",
"bestHeader",
".",
"height",
">",
"prevBestHeader",
".",
"height",
"{",
"majority",
",",
"err",
"=",
"rollback",
"(",
"majority",
",",
"int",
"(",
"bestHeader",
".",
"height",
"-",
"prevBestHeader",
".",
"height",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"prevBestHeader",
".",
"height",
">",
"bestHeader",
".",
"height",
"{",
"minority",
",",
"err",
"=",
"rollback",
"(",
"minority",
",",
"int",
"(",
"prevBestHeader",
".",
"height",
"-",
"bestHeader",
".",
"height",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"{",
"majorityHash",
":=",
"majority",
".",
"header",
".",
"BlockHash",
"(",
")",
"\n",
"minorityHash",
":=",
"minority",
".",
"header",
".",
"BlockHash",
"(",
")",
"\n",
"if",
"majorityHash",
".",
"IsEqual",
"(",
"&",
"minorityHash",
")",
"{",
"return",
"&",
"majority",
",",
"nil",
"\n",
"}",
"\n",
"majority",
",",
"err",
"=",
"b",
".",
"db",
".",
"GetPreviousHeader",
"(",
"majority",
".",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"minority",
",",
"err",
"=",
"b",
".",
"db",
".",
"GetPreviousHeader",
"(",
"minority",
".",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// GetCommonAncestor returns last header before reorg point
|
[
"GetCommonAncestor",
"returns",
"last",
"header",
"before",
"reorg",
"point"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/blockchain.go#L300-L341
|
17,147 |
OpenBazaar/spvwallet
|
blockchain.go
|
Rollback
|
func (b *Blockchain) Rollback(t time.Time) error {
b.lock.Lock()
defer b.lock.Unlock()
checkpoint := GetCheckpoint(b.crationDate, b.params)
checkPointHash := checkpoint.Header.BlockHash()
sh, err := b.db.GetBestHeader()
if err != nil {
return err
}
// If t is greater than the timestamp at the tip then do nothing
if sh.header.Timestamp.Before(t) {
return nil
}
// If the tip is our checkpoint then do nothing
checkHash := sh.header.BlockHash()
if checkHash.IsEqual(&checkPointHash) {
return nil
}
rollbackHeight := uint32(0)
for i := 0; i < 1000000000; i++ {
sh, err = b.db.GetPreviousHeader(sh.header)
if err != nil {
return err
}
checkHash := sh.header.BlockHash()
// If we rolled back to the checkpoint then stop here and set the checkpoint as the tip
if checkHash.IsEqual(&checkPointHash) {
rollbackHeight = checkpoint.Height
break
}
// If we hit a header created before t then stop here and set this header as the tip
if sh.header.Timestamp.Before(t) {
rollbackHeight = sh.height
break
}
}
err = b.db.DeleteAfter(rollbackHeight)
if err != nil {
return err
}
return b.db.Put(sh, true)
}
|
go
|
func (b *Blockchain) Rollback(t time.Time) error {
b.lock.Lock()
defer b.lock.Unlock()
checkpoint := GetCheckpoint(b.crationDate, b.params)
checkPointHash := checkpoint.Header.BlockHash()
sh, err := b.db.GetBestHeader()
if err != nil {
return err
}
// If t is greater than the timestamp at the tip then do nothing
if sh.header.Timestamp.Before(t) {
return nil
}
// If the tip is our checkpoint then do nothing
checkHash := sh.header.BlockHash()
if checkHash.IsEqual(&checkPointHash) {
return nil
}
rollbackHeight := uint32(0)
for i := 0; i < 1000000000; i++ {
sh, err = b.db.GetPreviousHeader(sh.header)
if err != nil {
return err
}
checkHash := sh.header.BlockHash()
// If we rolled back to the checkpoint then stop here and set the checkpoint as the tip
if checkHash.IsEqual(&checkPointHash) {
rollbackHeight = checkpoint.Height
break
}
// If we hit a header created before t then stop here and set this header as the tip
if sh.header.Timestamp.Before(t) {
rollbackHeight = sh.height
break
}
}
err = b.db.DeleteAfter(rollbackHeight)
if err != nil {
return err
}
return b.db.Put(sh, true)
}
|
[
"func",
"(",
"b",
"*",
"Blockchain",
")",
"Rollback",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"checkpoint",
":=",
"GetCheckpoint",
"(",
"b",
".",
"crationDate",
",",
"b",
".",
"params",
")",
"\n",
"checkPointHash",
":=",
"checkpoint",
".",
"Header",
".",
"BlockHash",
"(",
")",
"\n",
"sh",
",",
"err",
":=",
"b",
".",
"db",
".",
"GetBestHeader",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// If t is greater than the timestamp at the tip then do nothing",
"if",
"sh",
".",
"header",
".",
"Timestamp",
".",
"Before",
"(",
"t",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// If the tip is our checkpoint then do nothing",
"checkHash",
":=",
"sh",
".",
"header",
".",
"BlockHash",
"(",
")",
"\n",
"if",
"checkHash",
".",
"IsEqual",
"(",
"&",
"checkPointHash",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"rollbackHeight",
":=",
"uint32",
"(",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"1000000000",
";",
"i",
"++",
"{",
"sh",
",",
"err",
"=",
"b",
".",
"db",
".",
"GetPreviousHeader",
"(",
"sh",
".",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"checkHash",
":=",
"sh",
".",
"header",
".",
"BlockHash",
"(",
")",
"\n",
"// If we rolled back to the checkpoint then stop here and set the checkpoint as the tip",
"if",
"checkHash",
".",
"IsEqual",
"(",
"&",
"checkPointHash",
")",
"{",
"rollbackHeight",
"=",
"checkpoint",
".",
"Height",
"\n",
"break",
"\n",
"}",
"\n",
"// If we hit a header created before t then stop here and set this header as the tip",
"if",
"sh",
".",
"header",
".",
"Timestamp",
".",
"Before",
"(",
"t",
")",
"{",
"rollbackHeight",
"=",
"sh",
".",
"height",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"b",
".",
"db",
".",
"DeleteAfter",
"(",
"rollbackHeight",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"b",
".",
"db",
".",
"Put",
"(",
"sh",
",",
"true",
")",
"\n",
"}"
] |
// Rollback the header database to the last header before time t.
// We shouldn't go back further than the checkpoint
|
[
"Rollback",
"the",
"header",
"database",
"to",
"the",
"last",
"header",
"before",
"time",
"t",
".",
"We",
"shouldn",
"t",
"go",
"back",
"further",
"than",
"the",
"checkpoint"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/blockchain.go#L345-L386
|
17,148 |
OpenBazaar/spvwallet
|
blockchain.go
|
checkProofOfWork
|
func checkProofOfWork(header wire.BlockHeader, p *chaincfg.Params) bool {
target := blockchain.CompactToBig(header.Bits)
// The target must more than 0. Why can you even encode negative...
if target.Sign() <= 0 {
log.Debugf("Block target %064x is neagtive(??)\n", target.Bytes())
return false
}
// The target must be less than the maximum allowed (difficulty 1)
if target.Cmp(p.PowLimit) > 0 {
log.Debugf("Block target %064x is "+
"higher than max of %064x", target, p.PowLimit.Bytes())
return false
}
// The header hash must be less than the claimed target in the header.
blockHash := header.BlockHash()
hashNum := blockchain.HashToBig(&blockHash)
if hashNum.Cmp(target) > 0 {
log.Debugf("Block hash %064x is higher than "+
"required target of %064x", hashNum, target)
return false
}
return true
}
|
go
|
func checkProofOfWork(header wire.BlockHeader, p *chaincfg.Params) bool {
target := blockchain.CompactToBig(header.Bits)
// The target must more than 0. Why can you even encode negative...
if target.Sign() <= 0 {
log.Debugf("Block target %064x is neagtive(??)\n", target.Bytes())
return false
}
// The target must be less than the maximum allowed (difficulty 1)
if target.Cmp(p.PowLimit) > 0 {
log.Debugf("Block target %064x is "+
"higher than max of %064x", target, p.PowLimit.Bytes())
return false
}
// The header hash must be less than the claimed target in the header.
blockHash := header.BlockHash()
hashNum := blockchain.HashToBig(&blockHash)
if hashNum.Cmp(target) > 0 {
log.Debugf("Block hash %064x is higher than "+
"required target of %064x", hashNum, target)
return false
}
return true
}
|
[
"func",
"checkProofOfWork",
"(",
"header",
"wire",
".",
"BlockHeader",
",",
"p",
"*",
"chaincfg",
".",
"Params",
")",
"bool",
"{",
"target",
":=",
"blockchain",
".",
"CompactToBig",
"(",
"header",
".",
"Bits",
")",
"\n\n",
"// The target must more than 0. Why can you even encode negative...",
"if",
"target",
".",
"Sign",
"(",
")",
"<=",
"0",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"target",
".",
"Bytes",
"(",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"// The target must be less than the maximum allowed (difficulty 1)",
"if",
"target",
".",
"Cmp",
"(",
"p",
".",
"PowLimit",
")",
">",
"0",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"target",
",",
"p",
".",
"PowLimit",
".",
"Bytes",
"(",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"// The header hash must be less than the claimed target in the header.",
"blockHash",
":=",
"header",
".",
"BlockHash",
"(",
")",
"\n",
"hashNum",
":=",
"blockchain",
".",
"HashToBig",
"(",
"&",
"blockHash",
")",
"\n",
"if",
"hashNum",
".",
"Cmp",
"(",
"target",
")",
">",
"0",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"hashNum",
",",
"target",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Verifies the header hashes into something lower than specified by the 4-byte bits field.
|
[
"Verifies",
"the",
"header",
"hashes",
"into",
"something",
"lower",
"than",
"specified",
"by",
"the",
"4",
"-",
"byte",
"bits",
"field",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/blockchain.go#L410-L433
|
17,149 |
OpenBazaar/spvwallet
|
blockchain.go
|
calcDiffAdjust
|
func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
duration := end.Timestamp.UnixNano() - start.Timestamp.UnixNano()
if duration < minRetargetTimespan {
log.Debugf("Whoa there, block %s off-scale high 4X diff adjustment!",
end.BlockHash().String())
duration = minRetargetTimespan
} else if duration > maxRetargetTimespan {
log.Debugf("Uh-oh! block %s off-scale low 0.25X diff adjustment!\n",
end.BlockHash().String())
duration = maxRetargetTimespan
}
// calculation of new 32-byte difficulty target
// first turn the previous target into a big int
prevTarget := blockchain.CompactToBig(end.Bits)
// new target is old * duration...
newTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))
// divided by 2 weeks
newTarget.Div(newTarget, big.NewInt(int64(targetTimespan)))
// clip again if above minimum target (too easy)
if newTarget.Cmp(p.PowLimit) > 0 {
newTarget.Set(p.PowLimit)
}
return blockchain.BigToCompact(newTarget)
}
|
go
|
func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
duration := end.Timestamp.UnixNano() - start.Timestamp.UnixNano()
if duration < minRetargetTimespan {
log.Debugf("Whoa there, block %s off-scale high 4X diff adjustment!",
end.BlockHash().String())
duration = minRetargetTimespan
} else if duration > maxRetargetTimespan {
log.Debugf("Uh-oh! block %s off-scale low 0.25X diff adjustment!\n",
end.BlockHash().String())
duration = maxRetargetTimespan
}
// calculation of new 32-byte difficulty target
// first turn the previous target into a big int
prevTarget := blockchain.CompactToBig(end.Bits)
// new target is old * duration...
newTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))
// divided by 2 weeks
newTarget.Div(newTarget, big.NewInt(int64(targetTimespan)))
// clip again if above minimum target (too easy)
if newTarget.Cmp(p.PowLimit) > 0 {
newTarget.Set(p.PowLimit)
}
return blockchain.BigToCompact(newTarget)
}
|
[
"func",
"calcDiffAdjust",
"(",
"start",
",",
"end",
"wire",
".",
"BlockHeader",
",",
"p",
"*",
"chaincfg",
".",
"Params",
")",
"uint32",
"{",
"duration",
":=",
"end",
".",
"Timestamp",
".",
"UnixNano",
"(",
")",
"-",
"start",
".",
"Timestamp",
".",
"UnixNano",
"(",
")",
"\n",
"if",
"duration",
"<",
"minRetargetTimespan",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"end",
".",
"BlockHash",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"duration",
"=",
"minRetargetTimespan",
"\n",
"}",
"else",
"if",
"duration",
">",
"maxRetargetTimespan",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"end",
".",
"BlockHash",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"duration",
"=",
"maxRetargetTimespan",
"\n",
"}",
"\n\n",
"// calculation of new 32-byte difficulty target",
"// first turn the previous target into a big int",
"prevTarget",
":=",
"blockchain",
".",
"CompactToBig",
"(",
"end",
".",
"Bits",
")",
"\n",
"// new target is old * duration...",
"newTarget",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Mul",
"(",
"prevTarget",
",",
"big",
".",
"NewInt",
"(",
"duration",
")",
")",
"\n",
"// divided by 2 weeks",
"newTarget",
".",
"Div",
"(",
"newTarget",
",",
"big",
".",
"NewInt",
"(",
"int64",
"(",
"targetTimespan",
")",
")",
")",
"\n\n",
"// clip again if above minimum target (too easy)",
"if",
"newTarget",
".",
"Cmp",
"(",
"p",
".",
"PowLimit",
")",
">",
"0",
"{",
"newTarget",
".",
"Set",
"(",
"p",
".",
"PowLimit",
")",
"\n",
"}",
"\n\n",
"return",
"blockchain",
".",
"BigToCompact",
"(",
"newTarget",
")",
"\n",
"}"
] |
// This function takes in a start and end block header and uses the timestamps in each
// to calculate how much of a difficulty adjustment is needed. It returns a new compact
// difficulty target.
|
[
"This",
"function",
"takes",
"in",
"a",
"start",
"and",
"end",
"block",
"header",
"and",
"uses",
"the",
"timestamps",
"in",
"each",
"to",
"calculate",
"how",
"much",
"of",
"a",
"difficulty",
"adjustment",
"is",
"needed",
".",
"It",
"returns",
"a",
"new",
"compact",
"difficulty",
"target",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/blockchain.go#L438-L464
|
17,150 |
OpenBazaar/spvwallet
|
gui/bootstrap/provisioner.go
|
provision
|
func provision(baseDirectoryPath string, fnA RestoreAssets, fnP CustomProvision) (err error) {
// Provision resources
// TODO Handle upgrades and therefore removing the resources folder accordingly
var pr = filepath.Join(baseDirectoryPath, "resources")
if _, err = os.Stat(pr); os.IsNotExist(err) {
// Restore assets
astilog.Debugf("Restoring assets in %s", baseDirectoryPath)
if err = fnA(baseDirectoryPath, "resources"); err != nil {
err = errors.Wrapf(err, "restoring assets in %s failed", baseDirectoryPath)
return
}
} else if err != nil {
err = errors.Wrapf(err, "stating %s failed", pr)
return
} else {
astilog.Debugf("%s already exists, skipping restoring assets...", pr)
}
// Custom provision
if fnP != nil {
if err = fnP(baseDirectoryPath); err != nil {
err = errors.Wrap(err, "custom provisioning failed")
return
}
}
return
}
|
go
|
func provision(baseDirectoryPath string, fnA RestoreAssets, fnP CustomProvision) (err error) {
// Provision resources
// TODO Handle upgrades and therefore removing the resources folder accordingly
var pr = filepath.Join(baseDirectoryPath, "resources")
if _, err = os.Stat(pr); os.IsNotExist(err) {
// Restore assets
astilog.Debugf("Restoring assets in %s", baseDirectoryPath)
if err = fnA(baseDirectoryPath, "resources"); err != nil {
err = errors.Wrapf(err, "restoring assets in %s failed", baseDirectoryPath)
return
}
} else if err != nil {
err = errors.Wrapf(err, "stating %s failed", pr)
return
} else {
astilog.Debugf("%s already exists, skipping restoring assets...", pr)
}
// Custom provision
if fnP != nil {
if err = fnP(baseDirectoryPath); err != nil {
err = errors.Wrap(err, "custom provisioning failed")
return
}
}
return
}
|
[
"func",
"provision",
"(",
"baseDirectoryPath",
"string",
",",
"fnA",
"RestoreAssets",
",",
"fnP",
"CustomProvision",
")",
"(",
"err",
"error",
")",
"{",
"// Provision resources",
"// TODO Handle upgrades and therefore removing the resources folder accordingly",
"var",
"pr",
"=",
"filepath",
".",
"Join",
"(",
"baseDirectoryPath",
",",
"\"",
"\"",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"pr",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"// Restore assets",
"astilog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"baseDirectoryPath",
")",
"\n",
"if",
"err",
"=",
"fnA",
"(",
"baseDirectoryPath",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"baseDirectoryPath",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"pr",
")",
"\n",
"return",
"\n",
"}",
"else",
"{",
"astilog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"pr",
")",
"\n",
"}",
"\n\n",
"// Custom provision",
"if",
"fnP",
"!=",
"nil",
"{",
"if",
"err",
"=",
"fnP",
"(",
"baseDirectoryPath",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// provision provisions the resources as well as the custom provision
|
[
"provision",
"provisions",
"the",
"resources",
"as",
"well",
"as",
"the",
"custom",
"provision"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/gui/bootstrap/provisioner.go#L12-L38
|
17,151 |
OpenBazaar/spvwallet
|
peers.go
|
getNewAddress
|
func (pm *PeerManager) getNewAddress() (net.Addr, error) {
// If we have a trusted peer we'll just return it
if pm.trustedPeer == nil {
pm.peerMutex.Lock()
defer pm.peerMutex.Unlock()
// We're going to loop here and pull addresses from the addrManager until we get one that we
// are not currently connect to or haven't recently tried.
loop:
for tries := 0; tries < 100; tries++ {
ka := pm.addrManager.GetAddress()
if ka == nil {
continue
}
// only allow recent nodes (10mins) after we failed 30
// times
if tries < 30 && time.Since(ka.LastAttempt()) < 10*time.Minute {
continue
}
// allow nondefault ports after 50 failed tries.
if tries < 50 && fmt.Sprintf("%d", ka.NetAddress().Port) != pm.peerConfig.ChainParams.DefaultPort {
continue
}
knownAddress := ka.NetAddress()
// Don't return addresses we're still connected to
for _, p := range pm.connectedPeers {
if p.NA().IP.String() == knownAddress.IP.String() {
continue loop
}
}
addr := &net.TCPAddr{
Port: int(knownAddress.Port),
IP: knownAddress.IP,
}
pm.addrManager.Attempt(knownAddress)
return addr, nil
}
return nil, errors.New("failed to find appropriate address to return")
} else {
return pm.trustedPeer, nil
}
}
|
go
|
func (pm *PeerManager) getNewAddress() (net.Addr, error) {
// If we have a trusted peer we'll just return it
if pm.trustedPeer == nil {
pm.peerMutex.Lock()
defer pm.peerMutex.Unlock()
// We're going to loop here and pull addresses from the addrManager until we get one that we
// are not currently connect to or haven't recently tried.
loop:
for tries := 0; tries < 100; tries++ {
ka := pm.addrManager.GetAddress()
if ka == nil {
continue
}
// only allow recent nodes (10mins) after we failed 30
// times
if tries < 30 && time.Since(ka.LastAttempt()) < 10*time.Minute {
continue
}
// allow nondefault ports after 50 failed tries.
if tries < 50 && fmt.Sprintf("%d", ka.NetAddress().Port) != pm.peerConfig.ChainParams.DefaultPort {
continue
}
knownAddress := ka.NetAddress()
// Don't return addresses we're still connected to
for _, p := range pm.connectedPeers {
if p.NA().IP.String() == knownAddress.IP.String() {
continue loop
}
}
addr := &net.TCPAddr{
Port: int(knownAddress.Port),
IP: knownAddress.IP,
}
pm.addrManager.Attempt(knownAddress)
return addr, nil
}
return nil, errors.New("failed to find appropriate address to return")
} else {
return pm.trustedPeer, nil
}
}
|
[
"func",
"(",
"pm",
"*",
"PeerManager",
")",
"getNewAddress",
"(",
")",
"(",
"net",
".",
"Addr",
",",
"error",
")",
"{",
"// If we have a trusted peer we'll just return it",
"if",
"pm",
".",
"trustedPeer",
"==",
"nil",
"{",
"pm",
".",
"peerMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pm",
".",
"peerMutex",
".",
"Unlock",
"(",
")",
"\n",
"// We're going to loop here and pull addresses from the addrManager until we get one that we",
"// are not currently connect to or haven't recently tried.",
"loop",
":",
"for",
"tries",
":=",
"0",
";",
"tries",
"<",
"100",
";",
"tries",
"++",
"{",
"ka",
":=",
"pm",
".",
"addrManager",
".",
"GetAddress",
"(",
")",
"\n",
"if",
"ka",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// only allow recent nodes (10mins) after we failed 30",
"// times",
"if",
"tries",
"<",
"30",
"&&",
"time",
".",
"Since",
"(",
"ka",
".",
"LastAttempt",
"(",
")",
")",
"<",
"10",
"*",
"time",
".",
"Minute",
"{",
"continue",
"\n",
"}",
"\n\n",
"// allow nondefault ports after 50 failed tries.",
"if",
"tries",
"<",
"50",
"&&",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ka",
".",
"NetAddress",
"(",
")",
".",
"Port",
")",
"!=",
"pm",
".",
"peerConfig",
".",
"ChainParams",
".",
"DefaultPort",
"{",
"continue",
"\n",
"}",
"\n\n",
"knownAddress",
":=",
"ka",
".",
"NetAddress",
"(",
")",
"\n\n",
"// Don't return addresses we're still connected to",
"for",
"_",
",",
"p",
":=",
"range",
"pm",
".",
"connectedPeers",
"{",
"if",
"p",
".",
"NA",
"(",
")",
".",
"IP",
".",
"String",
"(",
")",
"==",
"knownAddress",
".",
"IP",
".",
"String",
"(",
")",
"{",
"continue",
"loop",
"\n",
"}",
"\n",
"}",
"\n",
"addr",
":=",
"&",
"net",
".",
"TCPAddr",
"{",
"Port",
":",
"int",
"(",
"knownAddress",
".",
"Port",
")",
",",
"IP",
":",
"knownAddress",
".",
"IP",
",",
"}",
"\n",
"pm",
".",
"addrManager",
".",
"Attempt",
"(",
"knownAddress",
")",
"\n",
"return",
"addr",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"pm",
".",
"trustedPeer",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Called by connManager when it adds a new connection
|
[
"Called",
"by",
"connManager",
"when",
"it",
"adds",
"a",
"new",
"connection"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/peers.go#L240-L284
|
17,152 |
OpenBazaar/spvwallet
|
peers.go
|
queryDNSSeeds
|
func (pm *PeerManager) queryDNSSeeds() {
wg := new(sync.WaitGroup)
for _, seed := range pm.peerConfig.ChainParams.DNSSeeds {
wg.Add(1)
go func(host string) {
returnedAddresses := 0
var addrs []string
var err error
if pm.proxy != nil {
for i := 0; i < 5; i++ {
ips, err := TorLookupIP(host)
if err != nil {
wg.Done()
return
}
for _, ip := range ips {
addrs = append(addrs, ip.String())
}
}
} else {
addrs, err = net.LookupHost(host)
if err != nil {
wg.Done()
return
}
}
for _, addr := range addrs {
netAddr := wire.NewNetAddressIPPort(net.ParseIP(addr), defaultPort, 0)
pm.addrManager.AddAddress(netAddr, pm.sourceAddr)
returnedAddresses++
}
log.Debugf("%s returned %s addresses\n", host, strconv.Itoa(returnedAddresses))
wg.Done()
}(seed.Host)
}
wg.Wait()
}
|
go
|
func (pm *PeerManager) queryDNSSeeds() {
wg := new(sync.WaitGroup)
for _, seed := range pm.peerConfig.ChainParams.DNSSeeds {
wg.Add(1)
go func(host string) {
returnedAddresses := 0
var addrs []string
var err error
if pm.proxy != nil {
for i := 0; i < 5; i++ {
ips, err := TorLookupIP(host)
if err != nil {
wg.Done()
return
}
for _, ip := range ips {
addrs = append(addrs, ip.String())
}
}
} else {
addrs, err = net.LookupHost(host)
if err != nil {
wg.Done()
return
}
}
for _, addr := range addrs {
netAddr := wire.NewNetAddressIPPort(net.ParseIP(addr), defaultPort, 0)
pm.addrManager.AddAddress(netAddr, pm.sourceAddr)
returnedAddresses++
}
log.Debugf("%s returned %s addresses\n", host, strconv.Itoa(returnedAddresses))
wg.Done()
}(seed.Host)
}
wg.Wait()
}
|
[
"func",
"(",
"pm",
"*",
"PeerManager",
")",
"queryDNSSeeds",
"(",
")",
"{",
"wg",
":=",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
"\n",
"for",
"_",
",",
"seed",
":=",
"range",
"pm",
".",
"peerConfig",
".",
"ChainParams",
".",
"DNSSeeds",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"host",
"string",
")",
"{",
"returnedAddresses",
":=",
"0",
"\n",
"var",
"addrs",
"[",
"]",
"string",
"\n",
"var",
"err",
"error",
"\n",
"if",
"pm",
".",
"proxy",
"!=",
"nil",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"5",
";",
"i",
"++",
"{",
"ips",
",",
"err",
":=",
"TorLookupIP",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wg",
".",
"Done",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"ips",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"ip",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"addrs",
",",
"err",
"=",
"net",
".",
"LookupHost",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wg",
".",
"Done",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"netAddr",
":=",
"wire",
".",
"NewNetAddressIPPort",
"(",
"net",
".",
"ParseIP",
"(",
"addr",
")",
",",
"defaultPort",
",",
"0",
")",
"\n",
"pm",
".",
"addrManager",
".",
"AddAddress",
"(",
"netAddr",
",",
"pm",
".",
"sourceAddr",
")",
"\n",
"returnedAddresses",
"++",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"host",
",",
"strconv",
".",
"Itoa",
"(",
"returnedAddresses",
")",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"seed",
".",
"Host",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] |
// Query the DNS seeds and pass the addresses into the address manager.
|
[
"Query",
"the",
"DNS",
"seeds",
"and",
"pass",
"the",
"addresses",
"into",
"the",
"address",
"manager",
"."
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/peers.go#L287-L323
|
17,153 |
OpenBazaar/spvwallet
|
peers.go
|
getMoreAddresses
|
func (pm *PeerManager) getMoreAddresses() {
if pm.addrManager.NeedMoreAddresses() {
pm.peerMutex.RLock()
defer pm.peerMutex.RUnlock()
if len(pm.connectedPeers) > 0 {
log.Debug("Querying peers for more addresses")
for _, p := range pm.connectedPeers {
p.QueueMessage(wire.NewMsgGetAddr(), nil)
}
} else {
pm.queryDNSSeeds()
}
}
}
|
go
|
func (pm *PeerManager) getMoreAddresses() {
if pm.addrManager.NeedMoreAddresses() {
pm.peerMutex.RLock()
defer pm.peerMutex.RUnlock()
if len(pm.connectedPeers) > 0 {
log.Debug("Querying peers for more addresses")
for _, p := range pm.connectedPeers {
p.QueueMessage(wire.NewMsgGetAddr(), nil)
}
} else {
pm.queryDNSSeeds()
}
}
}
|
[
"func",
"(",
"pm",
"*",
"PeerManager",
")",
"getMoreAddresses",
"(",
")",
"{",
"if",
"pm",
".",
"addrManager",
".",
"NeedMoreAddresses",
"(",
")",
"{",
"pm",
".",
"peerMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"pm",
".",
"peerMutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"pm",
".",
"connectedPeers",
")",
">",
"0",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"pm",
".",
"connectedPeers",
"{",
"p",
".",
"QueueMessage",
"(",
"wire",
".",
"NewMsgGetAddr",
"(",
")",
",",
"nil",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"pm",
".",
"queryDNSSeeds",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// If we have connected peers let's use them to get more addresses. If not, use the DNS seeds
|
[
"If",
"we",
"have",
"connected",
"peers",
"let",
"s",
"use",
"them",
"to",
"get",
"more",
"addresses",
".",
"If",
"not",
"use",
"the",
"DNS",
"seeds"
] |
49419d61fdffd995a0039f84441b543656520bb9
|
https://github.com/OpenBazaar/spvwallet/blob/49419d61fdffd995a0039f84441b543656520bb9/peers.go#L326-L339
|
17,154 |
paulsmith/gogeos
|
geos/geom.go
|
geomFromPtr
|
func geomFromPtr(ptr *C.GEOSGeometry) *Geometry {
g := &Geometry{g: ptr}
runtime.SetFinalizer(g, func(g *Geometry) {
cGEOSGeom_destroy(ptr)
})
return g
}
|
go
|
func geomFromPtr(ptr *C.GEOSGeometry) *Geometry {
g := &Geometry{g: ptr}
runtime.SetFinalizer(g, func(g *Geometry) {
cGEOSGeom_destroy(ptr)
})
return g
}
|
[
"func",
"geomFromPtr",
"(",
"ptr",
"*",
"C",
".",
"GEOSGeometry",
")",
"*",
"Geometry",
"{",
"g",
":=",
"&",
"Geometry",
"{",
"g",
":",
"ptr",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"g",
",",
"func",
"(",
"g",
"*",
"Geometry",
")",
"{",
"cGEOSGeom_destroy",
"(",
"ptr",
")",
"\n",
"}",
")",
"\n",
"return",
"g",
"\n",
"}"
] |
// geomFromPtr returns a new Geometry that's been initialized with a C pointer
// to the GEOS C API object.
//
// This constructor should be used when the caller has ownership of the
// underlying C object.
|
[
"geomFromPtr",
"returns",
"a",
"new",
"Geometry",
"that",
"s",
"been",
"initialized",
"with",
"a",
"C",
"pointer",
"to",
"the",
"GEOS",
"C",
"API",
"object",
".",
"This",
"constructor",
"should",
"be",
"used",
"when",
"the",
"caller",
"has",
"ownership",
"of",
"the",
"underlying",
"C",
"object",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L34-L40
|
17,155 |
paulsmith/gogeos
|
geos/geom.go
|
geomFromPtrUnowned
|
func geomFromPtrUnowned(ptr *C.GEOSGeometry) (*Geometry, error) {
if ptr == nil {
return nil, Error()
}
return &Geometry{g: ptr}, nil
}
|
go
|
func geomFromPtrUnowned(ptr *C.GEOSGeometry) (*Geometry, error) {
if ptr == nil {
return nil, Error()
}
return &Geometry{g: ptr}, nil
}
|
[
"func",
"geomFromPtrUnowned",
"(",
"ptr",
"*",
"C",
".",
"GEOSGeometry",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"if",
"ptr",
"==",
"nil",
"{",
"return",
"nil",
",",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"&",
"Geometry",
"{",
"g",
":",
"ptr",
"}",
",",
"nil",
"\n",
"}"
] |
// geomFromPtrUnowned returns a new Geometry that's been initialized with
// a C pointer to the GEOS C API object.
//
// This constructor should be used when the caller doesn't have ownership of the
// underlying C object.
|
[
"geomFromPtrUnowned",
"returns",
"a",
"new",
"Geometry",
"that",
"s",
"been",
"initialized",
"with",
"a",
"C",
"pointer",
"to",
"the",
"GEOS",
"C",
"API",
"object",
".",
"This",
"constructor",
"should",
"be",
"used",
"when",
"the",
"caller",
"doesn",
"t",
"have",
"ownership",
"of",
"the",
"underlying",
"C",
"object",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L47-L52
|
17,156 |
paulsmith/gogeos
|
geos/geom.go
|
Project
|
func (g *Geometry) Project(p *Geometry) float64 {
// XXX: error if wrong geometry types
return float64(cGEOSProject(g.g, p.g))
}
|
go
|
func (g *Geometry) Project(p *Geometry) float64 {
// XXX: error if wrong geometry types
return float64(cGEOSProject(g.g, p.g))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Project",
"(",
"p",
"*",
"Geometry",
")",
"float64",
"{",
"// XXX: error if wrong geometry types",
"return",
"float64",
"(",
"cGEOSProject",
"(",
"g",
".",
"g",
",",
"p",
".",
"g",
")",
")",
"\n",
"}"
] |
// Linearref functions
// Project returns distance of point projected on this geometry from origin.
// This must be a lineal geometry.
|
[
"Linearref",
"functions",
"Project",
"returns",
"distance",
"of",
"point",
"projected",
"on",
"this",
"geometry",
"from",
"origin",
".",
"This",
"must",
"be",
"a",
"lineal",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L108-L111
|
17,157 |
paulsmith/gogeos
|
geos/geom.go
|
ProjectNormalized
|
func (g *Geometry) ProjectNormalized(p *Geometry) float64 {
// XXX: error if wrong geometry types
return float64(cGEOSProjectNormalized(g.g, p.g))
}
|
go
|
func (g *Geometry) ProjectNormalized(p *Geometry) float64 {
// XXX: error if wrong geometry types
return float64(cGEOSProjectNormalized(g.g, p.g))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"ProjectNormalized",
"(",
"p",
"*",
"Geometry",
")",
"float64",
"{",
"// XXX: error if wrong geometry types",
"return",
"float64",
"(",
"cGEOSProjectNormalized",
"(",
"g",
".",
"g",
",",
"p",
".",
"g",
")",
")",
"\n",
"}"
] |
// ProjectNormalized returns distance of point projected on this geometry from
// origin, divided by its length.
// This must be a lineal geometry.
|
[
"ProjectNormalized",
"returns",
"distance",
"of",
"point",
"projected",
"on",
"this",
"geometry",
"from",
"origin",
"divided",
"by",
"its",
"length",
".",
"This",
"must",
"be",
"a",
"lineal",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L116-L119
|
17,158 |
paulsmith/gogeos
|
geos/geom.go
|
Interpolate
|
func (g *Geometry) Interpolate(dist float64) (*Geometry, error) {
return geomFromC("Interpolate", cGEOSInterpolate(g.g, C.double(dist)))
}
|
go
|
func (g *Geometry) Interpolate(dist float64) (*Geometry, error) {
return geomFromC("Interpolate", cGEOSInterpolate(g.g, C.double(dist)))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Interpolate",
"(",
"dist",
"float64",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"geomFromC",
"(",
"\"",
"\"",
",",
"cGEOSInterpolate",
"(",
"g",
".",
"g",
",",
"C",
".",
"double",
"(",
"dist",
")",
")",
")",
"\n",
"}"
] |
// Interpolate returns the closest point to given distance within geometry.
// This geometry must be a LineString.
|
[
"Interpolate",
"returns",
"the",
"closest",
"point",
"to",
"given",
"distance",
"within",
"geometry",
".",
"This",
"geometry",
"must",
"be",
"a",
"LineString",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L123-L125
|
17,159 |
paulsmith/gogeos
|
geos/geom.go
|
LineInterpolatePoint
|
func (g *Geometry) LineInterpolatePoint(dist float64) (*Geometry, error) {
// This code ported from LWGEOM_line_interpolate_point in postgis,
// by [email protected] and [email protected].
if dist < 0 || dist > 1 {
return nil, ErrLineInterpolatePointDist
}
typ, err := g.Type()
if err != nil {
return nil, err
}
if typ != LINESTRING {
return nil, ErrLineInterpolatePointType
}
empty, err := g.IsEmpty()
if err != nil {
return nil, err
}
if empty {
pt, err := NewPoint()
if err != nil {
return nil, err
}
return pt, nil
}
// If distance is one of two extremes, return the point on that end.
if dist == 0.0 || dist == 1.0 {
var (
pt *Geometry
err error
)
if dist == 0.0 {
pt, err = g.StartPoint()
} else {
pt, err = g.EndPoint()
}
if err != nil {
return nil, err
}
return pt, nil
}
// Interpolate a point on the line.
nsegs, err := g.NPoint()
if err != nil {
return nil, err
}
nsegs--
length, err := g.Length()
if err != nil {
return nil, err
}
var tlength float64
for i := 0; i < nsegs; i++ {
a, err := g.Point(i)
if err != nil {
return nil, err
}
b, err := g.Point(i + 1)
if err != nil {
return nil, err
}
// Find the relative length of this segment.
slength, err := a.Distance(b)
if err != nil {
return nil, err
}
slength /= length
if dist < tlength+slength {
dseg := (dist - tlength) / slength
pt, err := interpolatePoint2D(a, b, dseg)
if err != nil {
return nil, err
}
return pt, nil
}
tlength += slength
}
// Return the last point on the line. This shouldn't happen, but could if
// there's some floating point rounding errors.
return g.EndPoint()
}
|
go
|
func (g *Geometry) LineInterpolatePoint(dist float64) (*Geometry, error) {
// This code ported from LWGEOM_line_interpolate_point in postgis,
// by [email protected] and [email protected].
if dist < 0 || dist > 1 {
return nil, ErrLineInterpolatePointDist
}
typ, err := g.Type()
if err != nil {
return nil, err
}
if typ != LINESTRING {
return nil, ErrLineInterpolatePointType
}
empty, err := g.IsEmpty()
if err != nil {
return nil, err
}
if empty {
pt, err := NewPoint()
if err != nil {
return nil, err
}
return pt, nil
}
// If distance is one of two extremes, return the point on that end.
if dist == 0.0 || dist == 1.0 {
var (
pt *Geometry
err error
)
if dist == 0.0 {
pt, err = g.StartPoint()
} else {
pt, err = g.EndPoint()
}
if err != nil {
return nil, err
}
return pt, nil
}
// Interpolate a point on the line.
nsegs, err := g.NPoint()
if err != nil {
return nil, err
}
nsegs--
length, err := g.Length()
if err != nil {
return nil, err
}
var tlength float64
for i := 0; i < nsegs; i++ {
a, err := g.Point(i)
if err != nil {
return nil, err
}
b, err := g.Point(i + 1)
if err != nil {
return nil, err
}
// Find the relative length of this segment.
slength, err := a.Distance(b)
if err != nil {
return nil, err
}
slength /= length
if dist < tlength+slength {
dseg := (dist - tlength) / slength
pt, err := interpolatePoint2D(a, b, dseg)
if err != nil {
return nil, err
}
return pt, nil
}
tlength += slength
}
// Return the last point on the line. This shouldn't happen, but could if
// there's some floating point rounding errors.
return g.EndPoint()
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"LineInterpolatePoint",
"(",
"dist",
"float64",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"// This code ported from LWGEOM_line_interpolate_point in postgis,",
"// by [email protected] and [email protected].",
"if",
"dist",
"<",
"0",
"||",
"dist",
">",
"1",
"{",
"return",
"nil",
",",
"ErrLineInterpolatePointDist",
"\n",
"}",
"\n\n",
"typ",
",",
"err",
":=",
"g",
".",
"Type",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"typ",
"!=",
"LINESTRING",
"{",
"return",
"nil",
",",
"ErrLineInterpolatePointType",
"\n",
"}",
"\n\n",
"empty",
",",
"err",
":=",
"g",
".",
"IsEmpty",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"empty",
"{",
"pt",
",",
"err",
":=",
"NewPoint",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pt",
",",
"nil",
"\n",
"}",
"\n\n",
"// If distance is one of two extremes, return the point on that end.",
"if",
"dist",
"==",
"0.0",
"||",
"dist",
"==",
"1.0",
"{",
"var",
"(",
"pt",
"*",
"Geometry",
"\n",
"err",
"error",
"\n",
")",
"\n",
"if",
"dist",
"==",
"0.0",
"{",
"pt",
",",
"err",
"=",
"g",
".",
"StartPoint",
"(",
")",
"\n",
"}",
"else",
"{",
"pt",
",",
"err",
"=",
"g",
".",
"EndPoint",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pt",
",",
"nil",
"\n",
"}",
"\n\n",
"// Interpolate a point on the line.",
"nsegs",
",",
"err",
":=",
"g",
".",
"NPoint",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"nsegs",
"--",
"\n\n",
"length",
",",
"err",
":=",
"g",
".",
"Length",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"tlength",
"float64",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nsegs",
";",
"i",
"++",
"{",
"a",
",",
"err",
":=",
"g",
".",
"Point",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"g",
".",
"Point",
"(",
"i",
"+",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Find the relative length of this segment.",
"slength",
",",
"err",
":=",
"a",
".",
"Distance",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"slength",
"/=",
"length",
"\n\n",
"if",
"dist",
"<",
"tlength",
"+",
"slength",
"{",
"dseg",
":=",
"(",
"dist",
"-",
"tlength",
")",
"/",
"slength",
"\n",
"pt",
",",
"err",
":=",
"interpolatePoint2D",
"(",
"a",
",",
"b",
",",
"dseg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pt",
",",
"nil",
"\n",
"}",
"\n",
"tlength",
"+=",
"slength",
"\n",
"}",
"\n\n",
"// Return the last point on the line. This shouldn't happen, but could if",
"// there's some floating point rounding errors.",
"return",
"g",
".",
"EndPoint",
"(",
")",
"\n",
"}"
] |
// LineInterpolatePoint interpolates a point along a line.
|
[
"LineInterpolatePoint",
"interpolates",
"a",
"point",
"along",
"a",
"line",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L137-L228
|
17,160 |
paulsmith/gogeos
|
geos/geom.go
|
OffsetCurve
|
func (g *Geometry) OffsetCurve(distance float64, opts BufferOpts) (*Geometry, error) {
return geomFromC("OffsetCurve", cGEOSOffsetCurve(g.g, C.double(distance), C.int(opts.QuadSegs), C.int(opts.JoinStyle), C.double(opts.MitreLimit)))
}
|
go
|
func (g *Geometry) OffsetCurve(distance float64, opts BufferOpts) (*Geometry, error) {
return geomFromC("OffsetCurve", cGEOSOffsetCurve(g.g, C.double(distance), C.int(opts.QuadSegs), C.int(opts.JoinStyle), C.double(opts.MitreLimit)))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"OffsetCurve",
"(",
"distance",
"float64",
",",
"opts",
"BufferOpts",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"geomFromC",
"(",
"\"",
"\"",
",",
"cGEOSOffsetCurve",
"(",
"g",
".",
"g",
",",
"C",
".",
"double",
"(",
"distance",
")",
",",
"C",
".",
"int",
"(",
"opts",
".",
"QuadSegs",
")",
",",
"C",
".",
"int",
"(",
"opts",
".",
"JoinStyle",
")",
",",
"C",
".",
"double",
"(",
"opts",
".",
"MitreLimit",
")",
")",
")",
"\n",
"}"
] |
// OffsetCurve computes a new linestring that is offset from the input
// linestring by the given distance and buffer options. A negative distance is
// offset on the right side; positive distance offset on the left side.
|
[
"OffsetCurve",
"computes",
"a",
"new",
"linestring",
"that",
"is",
"offset",
"from",
"the",
"input",
"linestring",
"by",
"the",
"given",
"distance",
"and",
"buffer",
"options",
".",
"A",
"negative",
"distance",
"is",
"offset",
"on",
"the",
"right",
"side",
";",
"positive",
"distance",
"offset",
"on",
"the",
"left",
"side",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L326-L328
|
17,161 |
paulsmith/gogeos
|
geos/geom.go
|
SimplifyP
|
func (g *Geometry) SimplifyP(tolerance float64) (*Geometry, error) {
return g.simplify("simplify", cGEOSTopologyPreserveSimplify, tolerance)
}
|
go
|
func (g *Geometry) SimplifyP(tolerance float64) (*Geometry, error) {
return g.simplify("simplify", cGEOSTopologyPreserveSimplify, tolerance)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"SimplifyP",
"(",
"tolerance",
"float64",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"g",
".",
"simplify",
"(",
"\"",
"\"",
",",
"cGEOSTopologyPreserveSimplify",
",",
"tolerance",
")",
"\n",
"}"
] |
// SimplifyP returns a geometry simplified by amount given by tolerance.
// Unlike Simplify, SimplifyP guarantees it will preserve topology.
|
[
"SimplifyP",
"returns",
"a",
"geometry",
"simplified",
"by",
"amount",
"given",
"by",
"tolerance",
".",
"Unlike",
"Simplify",
"SimplifyP",
"guarantees",
"it",
"will",
"preserve",
"topology",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L497-L499
|
17,162 |
paulsmith/gogeos
|
geos/geom.go
|
Snap
|
func (g *Geometry) Snap(other *Geometry, tolerance float64) (*Geometry, error) {
return geomFromC("Snap", cGEOSSnap(g.g, other.g, C.double(tolerance)))
}
|
go
|
func (g *Geometry) Snap(other *Geometry, tolerance float64) (*Geometry, error) {
return geomFromC("Snap", cGEOSSnap(g.g, other.g, C.double(tolerance)))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Snap",
"(",
"other",
"*",
"Geometry",
",",
"tolerance",
"float64",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"geomFromC",
"(",
"\"",
"\"",
",",
"cGEOSSnap",
"(",
"g",
".",
"g",
",",
"other",
".",
"g",
",",
"C",
".",
"double",
"(",
"tolerance",
")",
")",
")",
"\n",
"}"
] |
// Snap returns a new geometry where the geometry is snapped to the given
// geometry by given tolerance.
|
[
"Snap",
"returns",
"a",
"new",
"geometry",
"where",
"the",
"geometry",
"is",
"snapped",
"to",
"the",
"given",
"geometry",
"by",
"given",
"tolerance",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L516-L518
|
17,163 |
paulsmith/gogeos
|
geos/geom.go
|
Intersection
|
func (g *Geometry) Intersection(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Intersection", cGEOSIntersection, other)
}
|
go
|
func (g *Geometry) Intersection(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Intersection", cGEOSIntersection, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Intersection",
"(",
"other",
"*",
"Geometry",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryTopo",
"(",
"\"",
"\"",
",",
"cGEOSIntersection",
",",
"other",
")",
"\n",
"}"
] |
// Binary topology functions
// Intersection returns a new geometry representing the points shared by this
// geometry and the other.
|
[
"Binary",
"topology",
"functions",
"Intersection",
"returns",
"a",
"new",
"geometry",
"representing",
"the",
"points",
"shared",
"by",
"this",
"geometry",
"and",
"the",
"other",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L529-L531
|
17,164 |
paulsmith/gogeos
|
geos/geom.go
|
Difference
|
func (g *Geometry) Difference(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Difference", cGEOSDifference, other)
}
|
go
|
func (g *Geometry) Difference(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Difference", cGEOSDifference, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Difference",
"(",
"other",
"*",
"Geometry",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryTopo",
"(",
"\"",
"\"",
",",
"cGEOSDifference",
",",
"other",
")",
"\n",
"}"
] |
// Difference returns a new geometry representing the points making up this
// geometry that do not make up the other.
|
[
"Difference",
"returns",
"a",
"new",
"geometry",
"representing",
"the",
"points",
"making",
"up",
"this",
"geometry",
"that",
"do",
"not",
"make",
"up",
"the",
"other",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L535-L537
|
17,165 |
paulsmith/gogeos
|
geos/geom.go
|
SymDifference
|
func (g *Geometry) SymDifference(other *Geometry) (*Geometry, error) {
return g.binaryTopo("SymDifference", cGEOSSymDifference, other)
}
|
go
|
func (g *Geometry) SymDifference(other *Geometry) (*Geometry, error) {
return g.binaryTopo("SymDifference", cGEOSSymDifference, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"SymDifference",
"(",
"other",
"*",
"Geometry",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryTopo",
"(",
"\"",
"\"",
",",
"cGEOSSymDifference",
",",
"other",
")",
"\n",
"}"
] |
// SymDifference returns a new geometry representing the set combining the
// points in this geometry not in the other, and the points in the other
// geometry and not in this.
|
[
"SymDifference",
"returns",
"a",
"new",
"geometry",
"representing",
"the",
"set",
"combining",
"the",
"points",
"in",
"this",
"geometry",
"not",
"in",
"the",
"other",
"and",
"the",
"points",
"in",
"the",
"other",
"geometry",
"and",
"not",
"in",
"this",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L542-L544
|
17,166 |
paulsmith/gogeos
|
geos/geom.go
|
Union
|
func (g *Geometry) Union(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Union", cGEOSUnion, other)
}
|
go
|
func (g *Geometry) Union(other *Geometry) (*Geometry, error) {
return g.binaryTopo("Union", cGEOSUnion, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Union",
"(",
"other",
"*",
"Geometry",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryTopo",
"(",
"\"",
"\"",
",",
"cGEOSUnion",
",",
"other",
")",
"\n",
"}"
] |
// Union returns a new geometry representing all points in this geometry and the
// other.
|
[
"Union",
"returns",
"a",
"new",
"geometry",
"representing",
"all",
"points",
"in",
"this",
"geometry",
"and",
"the",
"other",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L548-L550
|
17,167 |
paulsmith/gogeos
|
geos/geom.go
|
Disjoint
|
func (g *Geometry) Disjoint(other *Geometry) (bool, error) {
return g.binaryPred("Disjoint", cGEOSDisjoint, other)
}
|
go
|
func (g *Geometry) Disjoint(other *Geometry) (bool, error) {
return g.binaryPred("Disjoint", cGEOSDisjoint, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Disjoint",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSDisjoint",
",",
"other",
")",
"\n",
"}"
] |
// Binary predicate functions
// Disjoint returns true if the two geometries have no point in common.
|
[
"Binary",
"predicate",
"functions",
"Disjoint",
"returns",
"true",
"if",
"the",
"two",
"geometries",
"have",
"no",
"point",
"in",
"common",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L555-L557
|
17,168 |
paulsmith/gogeos
|
geos/geom.go
|
Touches
|
func (g *Geometry) Touches(other *Geometry) (bool, error) {
return g.binaryPred("Touches", cGEOSTouches, other)
}
|
go
|
func (g *Geometry) Touches(other *Geometry) (bool, error) {
return g.binaryPred("Touches", cGEOSTouches, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Touches",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSTouches",
",",
"other",
")",
"\n",
"}"
] |
// Touches returns true if the two geometries have at least one point in common,
// but their interiors do not intersect.
|
[
"Touches",
"returns",
"true",
"if",
"the",
"two",
"geometries",
"have",
"at",
"least",
"one",
"point",
"in",
"common",
"but",
"their",
"interiors",
"do",
"not",
"intersect",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L561-L563
|
17,169 |
paulsmith/gogeos
|
geos/geom.go
|
Intersects
|
func (g *Geometry) Intersects(other *Geometry) (bool, error) {
return g.binaryPred("Intersects", cGEOSIntersects, other)
}
|
go
|
func (g *Geometry) Intersects(other *Geometry) (bool, error) {
return g.binaryPred("Intersects", cGEOSIntersects, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Intersects",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSIntersects",
",",
"other",
")",
"\n",
"}"
] |
// Intersects returns true if the two geometries have at least one point in
// common.
|
[
"Intersects",
"returns",
"true",
"if",
"the",
"two",
"geometries",
"have",
"at",
"least",
"one",
"point",
"in",
"common",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L567-L569
|
17,170 |
paulsmith/gogeos
|
geos/geom.go
|
Crosses
|
func (g *Geometry) Crosses(other *Geometry) (bool, error) {
return g.binaryPred("Crosses", cGEOSCrosses, other)
}
|
go
|
func (g *Geometry) Crosses(other *Geometry) (bool, error) {
return g.binaryPred("Crosses", cGEOSCrosses, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Crosses",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSCrosses",
",",
"other",
")",
"\n",
"}"
] |
// Crosses returns true if the two geometries have some but not all interior
// points in common.
|
[
"Crosses",
"returns",
"true",
"if",
"the",
"two",
"geometries",
"have",
"some",
"but",
"not",
"all",
"interior",
"points",
"in",
"common",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L573-L575
|
17,171 |
paulsmith/gogeos
|
geos/geom.go
|
Within
|
func (g *Geometry) Within(other *Geometry) (bool, error) {
return g.binaryPred("Within", cGEOSWithin, other)
}
|
go
|
func (g *Geometry) Within(other *Geometry) (bool, error) {
return g.binaryPred("Within", cGEOSWithin, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Within",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSWithin",
",",
"other",
")",
"\n",
"}"
] |
// Within returns true if every point of this geometry is a point of the other,
// and the interiors of the two geometries have at least one point in common.
|
[
"Within",
"returns",
"true",
"if",
"every",
"point",
"of",
"this",
"geometry",
"is",
"a",
"point",
"of",
"the",
"other",
"and",
"the",
"interiors",
"of",
"the",
"two",
"geometries",
"have",
"at",
"least",
"one",
"point",
"in",
"common",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L579-L581
|
17,172 |
paulsmith/gogeos
|
geos/geom.go
|
Contains
|
func (g *Geometry) Contains(other *Geometry) (bool, error) {
return g.binaryPred("Contains", cGEOSContains, other)
}
|
go
|
func (g *Geometry) Contains(other *Geometry) (bool, error) {
return g.binaryPred("Contains", cGEOSContains, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Contains",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSContains",
",",
"other",
")",
"\n",
"}"
] |
// Contains returns true if every point of the other is a point of this geometry,
// and the interiors of the two geometries have at least one point in common.
|
[
"Contains",
"returns",
"true",
"if",
"every",
"point",
"of",
"the",
"other",
"is",
"a",
"point",
"of",
"this",
"geometry",
"and",
"the",
"interiors",
"of",
"the",
"two",
"geometries",
"have",
"at",
"least",
"one",
"point",
"in",
"common",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L585-L587
|
17,173 |
paulsmith/gogeos
|
geos/geom.go
|
Overlaps
|
func (g *Geometry) Overlaps(other *Geometry) (bool, error) {
return g.binaryPred("Overlaps", cGEOSOverlaps, other)
}
|
go
|
func (g *Geometry) Overlaps(other *Geometry) (bool, error) {
return g.binaryPred("Overlaps", cGEOSOverlaps, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Overlaps",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSOverlaps",
",",
"other",
")",
"\n",
"}"
] |
// Overlaps returns true if the geometries have some but not all points in
// common, they have the same dimension, and the intersection of the interiors
// of the two geometries has the same dimension as the geometries themselves.
|
[
"Overlaps",
"returns",
"true",
"if",
"the",
"geometries",
"have",
"some",
"but",
"not",
"all",
"points",
"in",
"common",
"they",
"have",
"the",
"same",
"dimension",
"and",
"the",
"intersection",
"of",
"the",
"interiors",
"of",
"the",
"two",
"geometries",
"has",
"the",
"same",
"dimension",
"as",
"the",
"geometries",
"themselves",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L592-L594
|
17,174 |
paulsmith/gogeos
|
geos/geom.go
|
Equals
|
func (g *Geometry) Equals(other *Geometry) (bool, error) {
return g.binaryPred("Equals", cGEOSEquals, other)
}
|
go
|
func (g *Geometry) Equals(other *Geometry) (bool, error) {
return g.binaryPred("Equals", cGEOSEquals, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Equals",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSEquals",
",",
"other",
")",
"\n",
"}"
] |
// Equals returns true if the two geometries have at least one point in common,
// and no point of either geometry lies in the exterior of the other geometry.
|
[
"Equals",
"returns",
"true",
"if",
"the",
"two",
"geometries",
"have",
"at",
"least",
"one",
"point",
"in",
"common",
"and",
"no",
"point",
"of",
"either",
"geometry",
"lies",
"in",
"the",
"exterior",
"of",
"the",
"other",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L598-L600
|
17,175 |
paulsmith/gogeos
|
geos/geom.go
|
Covers
|
func (g *Geometry) Covers(other *Geometry) (bool, error) {
return g.binaryPred("Covers", cGEOSCovers, other)
}
|
go
|
func (g *Geometry) Covers(other *Geometry) (bool, error) {
return g.binaryPred("Covers", cGEOSCovers, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Covers",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSCovers",
",",
"other",
")",
"\n",
"}"
] |
// Covers returns true if every point of the other geometry is a point of this
// geometry.
|
[
"Covers",
"returns",
"true",
"if",
"every",
"point",
"of",
"the",
"other",
"geometry",
"is",
"a",
"point",
"of",
"this",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L604-L606
|
17,176 |
paulsmith/gogeos
|
geos/geom.go
|
CoveredBy
|
func (g *Geometry) CoveredBy(other *Geometry) (bool, error) {
return g.binaryPred("CoveredBy", cGEOSCoveredBy, other)
}
|
go
|
func (g *Geometry) CoveredBy(other *Geometry) (bool, error) {
return g.binaryPred("CoveredBy", cGEOSCoveredBy, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"CoveredBy",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryPred",
"(",
"\"",
"\"",
",",
"cGEOSCoveredBy",
",",
"other",
")",
"\n",
"}"
] |
// CoveredBy returns true if every point of this geometry is a point of the
// other geometry.
|
[
"CoveredBy",
"returns",
"true",
"if",
"every",
"point",
"of",
"this",
"geometry",
"is",
"a",
"point",
"of",
"the",
"other",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L610-L612
|
17,177 |
paulsmith/gogeos
|
geos/geom.go
|
EqualsExact
|
func (g *Geometry) EqualsExact(other *Geometry, tolerance float64) (bool, error) {
return boolFromC("EqualsExact", cGEOSEqualsExact(g.g, other.g, C.double(tolerance)))
}
|
go
|
func (g *Geometry) EqualsExact(other *Geometry, tolerance float64) (bool, error) {
return boolFromC("EqualsExact", cGEOSEqualsExact(g.g, other.g, C.double(tolerance)))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"EqualsExact",
"(",
"other",
"*",
"Geometry",
",",
"tolerance",
"float64",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"boolFromC",
"(",
"\"",
"\"",
",",
"cGEOSEqualsExact",
"(",
"g",
".",
"g",
",",
"other",
".",
"g",
",",
"C",
".",
"double",
"(",
"tolerance",
")",
")",
")",
"\n",
"}"
] |
// EqualsExact returns true if both geometries are Equal, as evaluated by their
// points being within the given tolerance.
|
[
"EqualsExact",
"returns",
"true",
"if",
"both",
"geometries",
"are",
"Equal",
"as",
"evaluated",
"by",
"their",
"points",
"being",
"within",
"the",
"given",
"tolerance",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L616-L618
|
17,178 |
paulsmith/gogeos
|
geos/geom.go
|
Type
|
func (g *Geometry) Type() (GeometryType, error) {
i := cGEOSGeomTypeId(g.g)
if i == -1 {
// XXX: error
return -1, Error()
}
return cGeomTypeIds[i], nil
}
|
go
|
func (g *Geometry) Type() (GeometryType, error) {
i := cGEOSGeomTypeId(g.g)
if i == -1 {
// XXX: error
return -1, Error()
}
return cGeomTypeIds[i], nil
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Type",
"(",
")",
"(",
"GeometryType",
",",
"error",
")",
"{",
"i",
":=",
"cGEOSGeomTypeId",
"(",
"g",
".",
"g",
")",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"// XXX: error",
"return",
"-",
"1",
",",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"cGeomTypeIds",
"[",
"i",
"]",
",",
"nil",
"\n",
"}"
] |
// Geometry info functions
// Type returns the SFS type of the geometry.
|
[
"Geometry",
"info",
"functions",
"Type",
"returns",
"the",
"SFS",
"type",
"of",
"the",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L652-L659
|
17,179 |
paulsmith/gogeos
|
geos/geom.go
|
SetSRID
|
func (g *Geometry) SetSRID(srid int) {
cGEOSSetSRID(g.g, C.int(srid))
}
|
go
|
func (g *Geometry) SetSRID(srid int) {
cGEOSSetSRID(g.g, C.int(srid))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"SetSRID",
"(",
"srid",
"int",
")",
"{",
"cGEOSSetSRID",
"(",
"g",
".",
"g",
",",
"C",
".",
"int",
"(",
"srid",
")",
")",
"\n",
"}"
] |
// SetSRID sets the geometry's SRID.
|
[
"SetSRID",
"sets",
"the",
"geometry",
"s",
"SRID",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L667-L669
|
17,180 |
paulsmith/gogeos
|
geos/geom.go
|
Coords
|
func (g *Geometry) Coords() ([]Coord, error) {
ptr := cGEOSGeom_getCoordSeq(g.g)
if ptr == nil {
return nil, Error()
}
//cs := coordSeqFromPtr(ptr)
cs := &coordSeq{c: ptr}
return coordSlice(cs)
}
|
go
|
func (g *Geometry) Coords() ([]Coord, error) {
ptr := cGEOSGeom_getCoordSeq(g.g)
if ptr == nil {
return nil, Error()
}
//cs := coordSeqFromPtr(ptr)
cs := &coordSeq{c: ptr}
return coordSlice(cs)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Coords",
"(",
")",
"(",
"[",
"]",
"Coord",
",",
"error",
")",
"{",
"ptr",
":=",
"cGEOSGeom_getCoordSeq",
"(",
"g",
".",
"g",
")",
"\n",
"if",
"ptr",
"==",
"nil",
"{",
"return",
"nil",
",",
"Error",
"(",
")",
"\n",
"}",
"\n",
"//cs := coordSeqFromPtr(ptr)",
"cs",
":=",
"&",
"coordSeq",
"{",
"c",
":",
"ptr",
"}",
"\n",
"return",
"coordSlice",
"(",
"cs",
")",
"\n",
"}"
] |
// Coords returns a slice of Coord, a sequence of coordinates underlying the
// point, linestring, or linear ring.
|
[
"Coords",
"returns",
"a",
"slice",
"of",
"Coord",
"a",
"sequence",
"of",
"coordinates",
"underlying",
"the",
"point",
"linestring",
"or",
"linear",
"ring",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L753-L761
|
17,181 |
paulsmith/gogeos
|
geos/geom.go
|
Point
|
func (g *Geometry) Point(n int) (*Geometry, error) {
return geomFromC("Point", cGEOSGeomGetPointN(g.g, C.int(n)))
}
|
go
|
func (g *Geometry) Point(n int) (*Geometry, error) {
return geomFromC("Point", cGEOSGeomGetPointN(g.g, C.int(n)))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Point",
"(",
"n",
"int",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"return",
"geomFromC",
"(",
"\"",
"\"",
",",
"cGEOSGeomGetPointN",
"(",
"g",
".",
"g",
",",
"C",
".",
"int",
"(",
"n",
")",
")",
")",
"\n",
"}"
] |
// Point returns the nth point of the geometry.
// Geometry must be LineString.
|
[
"Point",
"returns",
"the",
"nth",
"point",
"of",
"the",
"geometry",
".",
"Geometry",
"must",
"be",
"LineString",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L777-L779
|
17,182 |
paulsmith/gogeos
|
geos/geom.go
|
Distance
|
func (g *Geometry) Distance(other *Geometry) (float64, error) {
return g.binaryFloat("Distance", cGEOSDistance, other)
}
|
go
|
func (g *Geometry) Distance(other *Geometry) (float64, error) {
return g.binaryFloat("Distance", cGEOSDistance, other)
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"Distance",
"(",
"other",
"*",
"Geometry",
")",
"(",
"float64",
",",
"error",
")",
"{",
"return",
"g",
".",
"binaryFloat",
"(",
"\"",
"\"",
",",
"cGEOSDistance",
",",
"other",
")",
"\n",
"}"
] |
// Distance returns the Cartesian distance between the two geometries.
|
[
"Distance",
"returns",
"the",
"Cartesian",
"distance",
"between",
"the",
"two",
"geometries",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L808-L810
|
17,183 |
paulsmith/gogeos
|
geos/geom.go
|
RelatePat
|
func (g *Geometry) RelatePat(other *Geometry, pat string) (bool, error) {
cs := C.CString(pat)
defer C.free(unsafe.Pointer(cs))
return boolFromC("RelatePat", cGEOSRelatePattern(g.g, other.g, cs))
}
|
go
|
func (g *Geometry) RelatePat(other *Geometry, pat string) (bool, error) {
cs := C.CString(pat)
defer C.free(unsafe.Pointer(cs))
return boolFromC("RelatePat", cGEOSRelatePattern(g.g, other.g, cs))
}
|
[
"func",
"(",
"g",
"*",
"Geometry",
")",
"RelatePat",
"(",
"other",
"*",
"Geometry",
",",
"pat",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"cs",
":=",
"C",
".",
"CString",
"(",
"pat",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cs",
")",
")",
"\n",
"return",
"boolFromC",
"(",
"\"",
"\"",
",",
"cGEOSRelatePattern",
"(",
"g",
".",
"g",
",",
"other",
".",
"g",
",",
"cs",
")",
")",
"\n",
"}"
] |
// RelatePat returns true if the DE-9IM matrix equals the intersection matrix of
// the two geometries.
|
[
"RelatePat",
"returns",
"true",
"if",
"the",
"DE",
"-",
"9IM",
"matrix",
"equals",
"the",
"intersection",
"matrix",
"of",
"the",
"two",
"geometries",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/geom.go#L843-L847
|
17,184 |
paulsmith/gogeos
|
geos/coord.go
|
coordSlice
|
func coordSlice(cs *coordSeq) ([]Coord, error) {
size, err := cs.size()
if err != nil {
return nil, err
}
coords := make([]Coord, size)
for i := 0; i < size; i++ {
x, err := cs.x(i)
if err != nil {
return nil, err
}
y, err := cs.y(i)
if err != nil {
return nil, err
}
coords[i] = Coord{X: x, Y: y}
}
return coords, nil
}
|
go
|
func coordSlice(cs *coordSeq) ([]Coord, error) {
size, err := cs.size()
if err != nil {
return nil, err
}
coords := make([]Coord, size)
for i := 0; i < size; i++ {
x, err := cs.x(i)
if err != nil {
return nil, err
}
y, err := cs.y(i)
if err != nil {
return nil, err
}
coords[i] = Coord{X: x, Y: y}
}
return coords, nil
}
|
[
"func",
"coordSlice",
"(",
"cs",
"*",
"coordSeq",
")",
"(",
"[",
"]",
"Coord",
",",
"error",
")",
"{",
"size",
",",
"err",
":=",
"cs",
".",
"size",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"coords",
":=",
"make",
"(",
"[",
"]",
"Coord",
",",
"size",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
"{",
"x",
",",
"err",
":=",
"cs",
".",
"x",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"y",
",",
"err",
":=",
"cs",
".",
"y",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"coords",
"[",
"i",
"]",
"=",
"Coord",
"{",
"X",
":",
"x",
",",
"Y",
":",
"y",
"}",
"\n",
"}",
"\n",
"return",
"coords",
",",
"nil",
"\n",
"}"
] |
// coordSlice constructs a slice of Coord objects from a coordinate sequence.
|
[
"coordSlice",
"constructs",
"a",
"slice",
"of",
"Coord",
"objects",
"from",
"a",
"coordinate",
"sequence",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/coord.go#L23-L41
|
17,185 |
paulsmith/gogeos
|
geos/wkt.go
|
newWktDecoder
|
func newWktDecoder() *wktDecoder {
r := cGEOSWKTReader_create()
if r == nil {
return nil
}
d := &wktDecoder{r}
runtime.SetFinalizer(d, (*wktDecoder).destroy)
return d
}
|
go
|
func newWktDecoder() *wktDecoder {
r := cGEOSWKTReader_create()
if r == nil {
return nil
}
d := &wktDecoder{r}
runtime.SetFinalizer(d, (*wktDecoder).destroy)
return d
}
|
[
"func",
"newWktDecoder",
"(",
")",
"*",
"wktDecoder",
"{",
"r",
":=",
"cGEOSWKTReader_create",
"(",
")",
"\n",
"if",
"r",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"d",
":=",
"&",
"wktDecoder",
"{",
"r",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"d",
",",
"(",
"*",
"wktDecoder",
")",
".",
"destroy",
")",
"\n",
"return",
"d",
"\n",
"}"
] |
// Creates a new WKT decoder, can be nil if initialization in the C API fails
|
[
"Creates",
"a",
"new",
"WKT",
"decoder",
"can",
"be",
"nil",
"if",
"initialization",
"in",
"the",
"C",
"API",
"fails"
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/wkt.go#L19-L27
|
17,186 |
paulsmith/gogeos
|
geos/wkt.go
|
decode
|
func (d *wktDecoder) decode(wkt string) (*Geometry, error) {
cstr := C.CString(wkt)
defer C.free(unsafe.Pointer(cstr))
g := cGEOSWKTReader_read(d.r, cstr)
if g == nil {
return nil, Error()
}
return geomFromPtr(g), nil
}
|
go
|
func (d *wktDecoder) decode(wkt string) (*Geometry, error) {
cstr := C.CString(wkt)
defer C.free(unsafe.Pointer(cstr))
g := cGEOSWKTReader_read(d.r, cstr)
if g == nil {
return nil, Error()
}
return geomFromPtr(g), nil
}
|
[
"func",
"(",
"d",
"*",
"wktDecoder",
")",
"decode",
"(",
"wkt",
"string",
")",
"(",
"*",
"Geometry",
",",
"error",
")",
"{",
"cstr",
":=",
"C",
".",
"CString",
"(",
"wkt",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cstr",
")",
")",
"\n",
"g",
":=",
"cGEOSWKTReader_read",
"(",
"d",
".",
"r",
",",
"cstr",
")",
"\n",
"if",
"g",
"==",
"nil",
"{",
"return",
"nil",
",",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"geomFromPtr",
"(",
"g",
")",
",",
"nil",
"\n",
"}"
] |
// decode decodes the WKT string and returns a geometry
|
[
"decode",
"decodes",
"the",
"WKT",
"string",
"and",
"returns",
"a",
"geometry"
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/wkt.go#L30-L38
|
17,187 |
paulsmith/gogeos
|
geos/wkt.go
|
encode
|
func (e *wktEncoder) encode(g *Geometry) (string, error) {
cstr := cGEOSWKTWriter_write(e.w, g.g)
if cstr == nil {
return "", Error()
}
return C.GoString(cstr), nil
}
|
go
|
func (e *wktEncoder) encode(g *Geometry) (string, error) {
cstr := cGEOSWKTWriter_write(e.w, g.g)
if cstr == nil {
return "", Error()
}
return C.GoString(cstr), nil
}
|
[
"func",
"(",
"e",
"*",
"wktEncoder",
")",
"encode",
"(",
"g",
"*",
"Geometry",
")",
"(",
"string",
",",
"error",
")",
"{",
"cstr",
":=",
"cGEOSWKTWriter_write",
"(",
"e",
".",
"w",
",",
"g",
".",
"g",
")",
"\n",
"if",
"cstr",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"C",
".",
"GoString",
"(",
"cstr",
")",
",",
"nil",
"\n",
"}"
] |
// Encode returns a string that is the geometry encoded as WKT
|
[
"Encode",
"returns",
"a",
"string",
"that",
"is",
"the",
"geometry",
"encoded",
"as",
"WKT"
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/wkt.go#L61-L67
|
17,188 |
paulsmith/gogeos
|
geos/prepared.go
|
PrepareGeometry
|
func PrepareGeometry(g *Geometry) *PGeometry {
ptr := cGEOSPrepare(g.g)
p := &PGeometry{ptr}
runtime.SetFinalizer(p, (*PGeometry).destroy)
return p
}
|
go
|
func PrepareGeometry(g *Geometry) *PGeometry {
ptr := cGEOSPrepare(g.g)
p := &PGeometry{ptr}
runtime.SetFinalizer(p, (*PGeometry).destroy)
return p
}
|
[
"func",
"PrepareGeometry",
"(",
"g",
"*",
"Geometry",
")",
"*",
"PGeometry",
"{",
"ptr",
":=",
"cGEOSPrepare",
"(",
"g",
".",
"g",
")",
"\n",
"p",
":=",
"&",
"PGeometry",
"{",
"ptr",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"p",
",",
"(",
"*",
"PGeometry",
")",
".",
"destroy",
")",
"\n",
"return",
"p",
"\n",
"}"
] |
// PrepareGeometry constructs a prepared geometry from a normal geometry object.
|
[
"PrepareGeometry",
"constructs",
"a",
"prepared",
"geometry",
"from",
"a",
"normal",
"geometry",
"object",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L20-L25
|
17,189 |
paulsmith/gogeos
|
geos/prepared.go
|
Contains
|
func (p *PGeometry) Contains(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContains, other)
}
|
go
|
func (p *PGeometry) Contains(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContains, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Contains",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedContains",
",",
"other",
")",
"\n",
"}"
] |
// Prepared geometry binary predicates
// Contains computes whether the prepared geometry contains the other prepared
// geometry.
|
[
"Prepared",
"geometry",
"binary",
"predicates",
"Contains",
"computes",
"whether",
"the",
"prepared",
"geometry",
"contains",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L36-L38
|
17,190 |
paulsmith/gogeos
|
geos/prepared.go
|
ContainsP
|
func (p *PGeometry) ContainsP(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContainsProperly, other)
}
|
go
|
func (p *PGeometry) ContainsP(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContainsProperly, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"ContainsP",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedContainsProperly",
",",
"other",
")",
"\n",
"}"
] |
// ContainsP computes whether the prepared geometry properly contains the other
// prepared geometry.
|
[
"ContainsP",
"computes",
"whether",
"the",
"prepared",
"geometry",
"properly",
"contains",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L42-L44
|
17,191 |
paulsmith/gogeos
|
geos/prepared.go
|
CoveredBy
|
func (p *PGeometry) CoveredBy(other *Geometry) (bool, error) {
return p.predicate("covered by", cGEOSPreparedCoveredBy, other)
}
|
go
|
func (p *PGeometry) CoveredBy(other *Geometry) (bool, error) {
return p.predicate("covered by", cGEOSPreparedCoveredBy, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"CoveredBy",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedCoveredBy",
",",
"other",
")",
"\n",
"}"
] |
// CoveredBy computes whether the prepared geometry is covered by the other
// prepared geometry.
|
[
"CoveredBy",
"computes",
"whether",
"the",
"prepared",
"geometry",
"is",
"covered",
"by",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L48-L50
|
17,192 |
paulsmith/gogeos
|
geos/prepared.go
|
Covers
|
func (p *PGeometry) Covers(other *Geometry) (bool, error) {
return p.predicate("covers", cGEOSPreparedCovers, other)
}
|
go
|
func (p *PGeometry) Covers(other *Geometry) (bool, error) {
return p.predicate("covers", cGEOSPreparedCovers, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Covers",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedCovers",
",",
"other",
")",
"\n",
"}"
] |
// Covers computes whether the prepared geometry covers the other prepared
// geometry.
|
[
"Covers",
"computes",
"whether",
"the",
"prepared",
"geometry",
"covers",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L54-L56
|
17,193 |
paulsmith/gogeos
|
geos/prepared.go
|
Crosses
|
func (p *PGeometry) Crosses(other *Geometry) (bool, error) {
return p.predicate("crosses", cGEOSPreparedCrosses, other)
}
|
go
|
func (p *PGeometry) Crosses(other *Geometry) (bool, error) {
return p.predicate("crosses", cGEOSPreparedCrosses, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Crosses",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedCrosses",
",",
"other",
")",
"\n",
"}"
] |
// Crosses computes whether the prepared geometry crosses the other prepared
// geometry.
|
[
"Crosses",
"computes",
"whether",
"the",
"prepared",
"geometry",
"crosses",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L60-L62
|
17,194 |
paulsmith/gogeos
|
geos/prepared.go
|
Disjoint
|
func (p *PGeometry) Disjoint(other *Geometry) (bool, error) {
return p.predicate("disjoint", cGEOSPreparedDisjoint, other)
}
|
go
|
func (p *PGeometry) Disjoint(other *Geometry) (bool, error) {
return p.predicate("disjoint", cGEOSPreparedDisjoint, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Disjoint",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedDisjoint",
",",
"other",
")",
"\n",
"}"
] |
// Disjoint computes whether the prepared geometry is disjoint from the other
// prepared geometry.
|
[
"Disjoint",
"computes",
"whether",
"the",
"prepared",
"geometry",
"is",
"disjoint",
"from",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L66-L68
|
17,195 |
paulsmith/gogeos
|
geos/prepared.go
|
Intersects
|
func (p *PGeometry) Intersects(other *Geometry) (bool, error) {
return p.predicate("intersects", cGEOSPreparedIntersects, other)
}
|
go
|
func (p *PGeometry) Intersects(other *Geometry) (bool, error) {
return p.predicate("intersects", cGEOSPreparedIntersects, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Intersects",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedIntersects",
",",
"other",
")",
"\n",
"}"
] |
// Intersects computes whether the prepared geometry intersects the other
// prepared geometry.
|
[
"Intersects",
"computes",
"whether",
"the",
"prepared",
"geometry",
"intersects",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L72-L74
|
17,196 |
paulsmith/gogeos
|
geos/prepared.go
|
Overlaps
|
func (p *PGeometry) Overlaps(other *Geometry) (bool, error) {
return p.predicate("overlaps", cGEOSPreparedOverlaps, other)
}
|
go
|
func (p *PGeometry) Overlaps(other *Geometry) (bool, error) {
return p.predicate("overlaps", cGEOSPreparedOverlaps, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Overlaps",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedOverlaps",
",",
"other",
")",
"\n",
"}"
] |
// Overlaps computes whether the prepared geometry overlaps the other
// prepared geometry.
|
[
"Overlaps",
"computes",
"whether",
"the",
"prepared",
"geometry",
"overlaps",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L78-L80
|
17,197 |
paulsmith/gogeos
|
geos/prepared.go
|
Touches
|
func (p *PGeometry) Touches(other *Geometry) (bool, error) {
return p.predicate("touches", cGEOSPreparedTouches, other)
}
|
go
|
func (p *PGeometry) Touches(other *Geometry) (bool, error) {
return p.predicate("touches", cGEOSPreparedTouches, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Touches",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedTouches",
",",
"other",
")",
"\n",
"}"
] |
// Touches computes whether the prepared geometry touches the other
// prepared geometry.
|
[
"Touches",
"computes",
"whether",
"the",
"prepared",
"geometry",
"touches",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L84-L86
|
17,198 |
paulsmith/gogeos
|
geos/prepared.go
|
Within
|
func (p *PGeometry) Within(other *Geometry) (bool, error) {
return p.predicate("within", cGEOSPreparedWithin, other)
}
|
go
|
func (p *PGeometry) Within(other *Geometry) (bool, error) {
return p.predicate("within", cGEOSPreparedWithin, other)
}
|
[
"func",
"(",
"p",
"*",
"PGeometry",
")",
"Within",
"(",
"other",
"*",
"Geometry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"p",
".",
"predicate",
"(",
"\"",
"\"",
",",
"cGEOSPreparedWithin",
",",
"other",
")",
"\n",
"}"
] |
// Within computes whether the prepared geometry is within the other
// prepared geometry.
|
[
"Within",
"computes",
"whether",
"the",
"prepared",
"geometry",
"is",
"within",
"the",
"other",
"prepared",
"geometry",
"."
] |
21f81b2ea5af44d3f6029cc3e5bbbd26b2425236
|
https://github.com/paulsmith/gogeos/blob/21f81b2ea5af44d3f6029cc3e5bbbd26b2425236/geos/prepared.go#L90-L92
|
17,199 |
hoisie/redis
|
redis.go
|
Zadd
|
func (client *Client) Zadd(key string, value []byte, score float64) (bool, error) {
res, err := client.sendCommand("ZADD", key, strconv.FormatFloat(score, 'f', -1, 64), string(value))
if err != nil {
return false, err
}
return res.(int64) == 1, nil
}
|
go
|
func (client *Client) Zadd(key string, value []byte, score float64) (bool, error) {
res, err := client.sendCommand("ZADD", key, strconv.FormatFloat(score, 'f', -1, 64), string(value))
if err != nil {
return false, err
}
return res.(int64) == 1, nil
}
|
[
"func",
"(",
"client",
"*",
"Client",
")",
"Zadd",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"byte",
",",
"score",
"float64",
")",
"(",
"bool",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"client",
".",
"sendCommand",
"(",
"\"",
"\"",
",",
"key",
",",
"strconv",
".",
"FormatFloat",
"(",
"score",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
",",
"string",
"(",
"value",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"res",
".",
"(",
"int64",
")",
"==",
"1",
",",
"nil",
"\n",
"}"
] |
// sorted set commands
|
[
"sorted",
"set",
"commands"
] |
b5c6e81454e0395c280f220d82a6854fd0fcf42e
|
https://github.com/hoisie/redis/blob/b5c6e81454e0395c280f220d82a6854fd0fcf42e/redis.go#L914-L921
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.