summaryrefslogtreecommitdiff
path: root/vendor/github.com/getlantern/context
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/github.com/getlantern/context')
-rw-r--r--vendor/github.com/getlantern/context/LICENSE202
-rw-r--r--vendor/github.com/getlantern/context/README.md6
-rw-r--r--vendor/github.com/getlantern/context/context.go309
-rw-r--r--vendor/github.com/getlantern/context/context_test.go160
-rw-r--r--vendor/github.com/getlantern/context/gotrack.go130
5 files changed, 807 insertions, 0 deletions
diff --git a/vendor/github.com/getlantern/context/LICENSE b/vendor/github.com/getlantern/context/LICENSE
new file mode 100644
index 0000000..5dc6c26
--- /dev/null
+++ b/vendor/github.com/getlantern/context/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2016 Brave New Software Project, Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/getlantern/context/README.md b/vendor/github.com/getlantern/context/README.md
new file mode 100644
index 0000000..978c9e0
--- /dev/null
+++ b/vendor/github.com/getlantern/context/README.md
@@ -0,0 +1,6 @@
+# context [![Travis CI Status](https://travis-ci.org/getlantern/context.svg?branch=master)](https://travis-ci.org/getlantern/context) [![Coverage Status](https://coveralls.io/repos/getlantern/context/badge.png?branch=master)](https://coveralls.io/r/getlantern/context)
+
+Provides goroutine-based context state inspired by https://github.com/tylerb/gls
+and https://github.com/jtolds/gls. It uses the same basic hack as tylerb's
+library, but adds a stack abstraction that allows nested contexts similar to
+jtolds' library, but using `Enter()` and `Exit()` instead of callback functions.
diff --git a/vendor/github.com/getlantern/context/context.go b/vendor/github.com/getlantern/context/context.go
new file mode 100644
index 0000000..c77f129
--- /dev/null
+++ b/vendor/github.com/getlantern/context/context.go
@@ -0,0 +1,309 @@
+// Package context provides a mechanism for transparently tracking contextual
+// state associated to the current goroutine and even across goroutines.
+package context
+
+import (
+ "sync"
+)
+
+// Manager provides the ability to create and access Contexts.
+type Manager interface {
+ // Enter enters a new level on the current Context stack, creating a new Context
+ // if necessary.
+ Enter() Context
+
+ // Go starts the given function on a new goroutine but sharing the context of
+ // the current goroutine (if it has one).
+ Go(func())
+
+ // PutGlobal puts the given key->value pair into the global context.
+ PutGlobal(key string, value interface{})
+
+ // PutGlobalDynamic puts a key->value pair into the global context where the
+ // value is generated by a function that gets evaluated at every Read. If the
+ // value is a map[string]interface{}, we will unpack the map and set each
+ // contained key->value pair independently.
+ PutGlobalDynamic(key string, valueFN func() interface{})
+
+ // AsMap returns a map containing all values from the supplied obj if it is a
+ // Contextual, plus any addition values from along the stack, plus globals if so
+ // specified.
+ AsMap(obj interface{}, includeGlobals bool) Map
+}
+
+type manager struct {
+ contexts map[uint64]*context
+ mxContexts sync.RWMutex
+ global Map
+ mxGlobal sync.RWMutex
+}
+
+// NewManager creates a new Manager
+func NewManager() Manager {
+ return &manager{
+ contexts: make(map[uint64]*context),
+ global: make(Map),
+ }
+}
+
+// Contextual is an interface for anything that maintains its own context.
+type Contextual interface {
+ // Fill fills the given Map with all of this Contextual's context
+ Fill(m Map)
+}
+
+// Map is a map of key->value pairs.
+type Map map[string]interface{}
+
+// Fill implements the method from the Contextual interface.
+func (_m Map) Fill(m Map) {
+ for key, value := range _m {
+ m[key] = value
+ }
+}
+
+// Context is a context containing key->value pairs
+type Context interface {
+ // Enter enters a new level on this Context stack.
+ Enter() Context
+
+ // Go starts the given function on a new goroutine.
+ Go(fn func())
+
+ // Exit exits the current level on this Context stack.
+ Exit()
+
+ // Put puts a key->value pair into the current level of the context stack.
+ Put(key string, value interface{}) Context
+
+ // PutIfAbsent puts the given key->value pair into the current level of the
+ // context stack if and only if that key is defined nowhere within the context
+ // stack (including parent contexts).
+ PutIfAbsent(key string, value interface{}) Context
+
+ // PutDynamic puts a key->value pair into the current level of the context
+ // stack where the value is generated by a function that gets evaluated at
+ // every Read. If the value is a map[string]interface{}, we will unpack the
+ // map and set each contained key->value pair independently.
+ PutDynamic(key string, valueFN func() interface{}) Context
+
+ // Fill fills the given map with data from this Context
+ Fill(m Map)
+
+ // AsMap returns a map containing all values from the supplied obj if it is a
+ // Contextual, plus any addition values from along the stack, plus globals if
+ // so specified.
+ AsMap(obj interface{}, includeGlobals bool) Map
+}
+
+type context struct {
+ cm *manager
+ id uint64
+ parent *context
+ branchedFrom *context
+ data Map
+ mx sync.RWMutex
+}
+
+type dynval struct {
+ fn func() interface{}
+}
+
+func (cm *manager) Enter() Context {
+ return cm.enter(curGoroutineID())
+}
+
+func (cm *manager) enter(id uint64) *context {
+ cm.mxContexts.Lock()
+ parentOrNil := cm.contexts[id]
+ c := cm.makeContext(id, parentOrNil, nil)
+ cm.contexts[id] = c
+ cm.mxContexts.Unlock()
+ return c
+}
+
+func (cm *manager) exit(id uint64, parent *context) {
+ cm.mxContexts.Lock()
+ if parent == nil {
+ delete(cm.contexts, id)
+ } else {
+ cm.contexts[id] = parent
+ }
+ cm.mxContexts.Unlock()
+}
+
+func (cm *manager) branch(id uint64, from *context) {
+ next := cm.makeContext(id, nil, from)
+ cm.mxContexts.Lock()
+ cm.contexts[id] = next
+ cm.mxContexts.Unlock()
+}
+
+func (cm *manager) merge(id uint64) {
+ cm.mxContexts.Lock()
+ delete(cm.contexts, id)
+ cm.mxContexts.Unlock()
+}
+
+func (c *context) Enter() Context {
+ c.mx.RLock()
+ id := c.id
+ c.mx.RUnlock()
+ return c.cm.enter(id)
+}
+
+func (c *context) Go(fn func()) {
+ go func() {
+ id := curGoroutineID()
+ c.cm.branch(id, c)
+ fn()
+ c.cm.merge(id)
+ }()
+}
+
+func (cm *manager) Go(fn func()) {
+ c := cm.currentContext()
+ if c != nil {
+ c.Go(fn)
+ } else {
+ go fn()
+ }
+}
+
+func (cm *manager) makeContext(id uint64, parent *context, branchedFrom *context) *context {
+ return &context{
+ cm: cm,
+ id: id,
+ parent: parent,
+ branchedFrom: branchedFrom,
+ data: make(Map),
+ }
+}
+
+func (c *context) Exit() {
+ c.mx.RLock()
+ id := c.id
+ parent := c.parent
+ c.mx.RUnlock()
+ c.cm.exit(id, parent)
+}
+
+func (c *context) Put(key string, value interface{}) Context {
+ c.mx.Lock()
+ c.data[key] = value
+ c.mx.Unlock()
+ return c
+}
+
+func (c *context) PutIfAbsent(key string, value interface{}) Context {
+ for ctx := c; ctx != nil; {
+ ctx.mx.RLock()
+ _, exists := ctx.data[key]
+ next := ctx.parent
+ if next == nil {
+ next = ctx.branchedFrom
+ }
+ ctx.mx.RUnlock()
+ if exists {
+ return c
+ }
+ ctx = next
+ }
+
+ // Value not set, set it
+ return c.Put(key, value)
+}
+
+func (c *context) PutDynamic(key string, valueFN func() interface{}) Context {
+ value := &dynval{valueFN}
+ c.mx.Lock()
+ c.data[key] = value
+ c.mx.Unlock()
+ return c
+}
+
+func (cm *manager) PutGlobal(key string, value interface{}) {
+ cm.mxGlobal.Lock()
+ cm.global[key] = value
+ cm.mxGlobal.Unlock()
+}
+
+func (cm *manager) PutGlobalDynamic(key string, valueFN func() interface{}) {
+ value := &dynval{valueFN}
+ cm.mxGlobal.Lock()
+ cm.global[key] = value
+ cm.mxGlobal.Unlock()
+}
+
+func (c *context) Fill(m Map) {
+ for ctx := c; ctx != nil; {
+ ctx.mx.RLock()
+ fill(m, ctx.data)
+ next := ctx.parent
+ if next == nil {
+ next = ctx.branchedFrom
+ }
+ ctx.mx.RUnlock()
+ ctx = next
+ }
+}
+
+func (cm *manager) AsMap(obj interface{}, includeGlobals bool) Map {
+ return cm.currentContext().asMap(cm, obj, includeGlobals)
+}
+
+func (c *context) AsMap(obj interface{}, includeGlobals bool) Map {
+ return c.asMap(c.cm, obj, includeGlobals)
+}
+
+func (c *context) asMap(cm *manager, obj interface{}, includeGlobals bool) Map {
+ result := make(Map, 0)
+ cl, ok := obj.(Contextual)
+ if ok {
+ cl.Fill(result)
+ }
+ if c != nil {
+ c.Fill(result)
+ }
+ if includeGlobals {
+ cm.mxGlobal.RLock()
+ fill(result, cm.global)
+ cm.mxGlobal.RUnlock()
+ }
+ return result
+}
+
+func fill(m Map, from Map) {
+ if m != nil {
+ doFill := func(key string, _value interface{}) {
+ switch value := _value.(type) {
+ case map[string]interface{}:
+ for k, v := range value {
+ m[k] = v
+ }
+ default:
+ m[key] = value
+ }
+ }
+
+ for key, value := range from {
+ _, alreadyRead := m[key]
+ if !alreadyRead {
+ switch v := value.(type) {
+ case *dynval:
+ doFill(key, v.fn())
+ default:
+ doFill(key, v)
+ }
+ }
+ }
+ }
+}
+
+func (cm *manager) currentContext() *context {
+ id := curGoroutineID()
+ cm.mxContexts.RLock()
+ c := cm.contexts[id]
+ cm.mxContexts.RUnlock()
+ return c
+}
diff --git a/vendor/github.com/getlantern/context/context_test.go b/vendor/github.com/getlantern/context/context_test.go
new file mode 100644
index 0000000..9fb86f3
--- /dev/null
+++ b/vendor/github.com/getlantern/context/context_test.go
@@ -0,0 +1,160 @@
+package context
+
+import (
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestStack(t *testing.T) {
+ cm := NewManager()
+ _cm := cm.(*manager)
+ // Put globals first
+ cm.PutGlobal("a", -1) // This will get overriden in specific contexts
+ cm.PutGlobal("ga", "i")
+ cm.PutGlobalDynamic("gb", func() interface{} { return "ii" })
+ cm.PutGlobalDynamic("gm", func() interface{} { return map[string]interface{}{"gm3": "iii", "gm4": "iv"} })
+
+ // Use a Map as a Contextual
+ var contextual = Map{
+ "a": 0, // This will override whatever is in specific contexts
+ "contextual": "special",
+ }
+
+ c := cm.Enter()
+ c.Put("a", 1)
+ penultimate := cm.Enter().
+ Put("b", 2)
+ c = cm.Enter().
+ PutDynamic("c", func() interface{} { return 4 }).
+ PutIfAbsent("d", 5).
+ PutIfAbsent("a", 11)
+
+ // Put something in the penultimate context and make sure it doesn't override
+ // what's set in the ultimate context
+ penultimate.Put("c", 3)
+
+ var assertMutex sync.Mutex
+ doAssertContents := func(expected Map, actual Map, scope string) {
+ assertMutex.Lock()
+ assert.Equal(t, expected, actual, scope)
+ assertMutex.Unlock()
+ }
+
+ assertContents := func(expected Map) {
+ doAssertContents(expected, cm.AsMap(nil, false), "AsMapwith(nil, false)")
+ expected["ga"] = "i"
+ expected["gb"] = "ii"
+ expected["gm3"] = "iii"
+ expected["gm4"] = "iv"
+ _, exists := expected["a"]
+ if !exists {
+ expected["a"] = -1
+ }
+ doAssertContents(expected, cm.AsMap(nil, true), "AsMap(nil, true)")
+ expected["a"] = 0
+ expected["contextual"] = "special"
+ doAssertContents(expected, cm.AsMap(contextual, true), "AsMapWith(contextual, true)")
+ delete(expected, "ga")
+ delete(expected, "gb")
+ delete(expected, "gm3")
+ delete(expected, "gm4")
+ doAssertContents(expected, cm.AsMap(contextual, false), "AsMapWith(contextual, false)")
+ }
+
+ assertContents(Map{
+ "a": 1,
+ "b": 2,
+ "c": 4,
+ "d": 5,
+ })
+
+ var wg sync.WaitGroup
+ wg.Add(1)
+ cm.Go(func() {
+ defer cm.Enter().Put("e", 6).Exit()
+ assertContents(Map{
+ "a": 1,
+ "b": 2,
+ "c": 4,
+ "d": 5,
+ "e": 6,
+ })
+ wg.Done()
+ })
+ wg.Wait()
+
+ wg.Add(1)
+ cm.Go(func() {
+ // This goroutine doesn't Exit. Still, we shouldn't leak anything.
+ wg.Done()
+ })
+ wg.Wait()
+
+ assertContents(Map{
+ "a": 1,
+ "b": 2,
+ "c": 4,
+ "d": 5,
+ })
+
+ c.Exit()
+ c = _cm.currentContext()
+ assert.NotNil(t, c)
+ assertContents(Map{
+ "a": 1,
+ "b": 2,
+ "c": 3,
+ })
+
+ c.Exit()
+ c = _cm.currentContext()
+ assert.NotNil(t, c)
+ assertContents(Map{
+ "a": 1,
+ })
+
+ // Last exit
+ c.Exit()
+ assert.Nil(t, _cm.currentContext())
+ assertContents(Map{})
+
+ // Exit again, just for good measure
+ c.Exit()
+ assert.Nil(t, _cm.currentContext())
+ assertContents(Map{})
+
+ // Spawn a goroutine with no existing contexts
+ wg.Add(1)
+ cm.Go(func() {
+ defer cm.Enter().Put("f", 7).Exit()
+ assertContents(Map{
+ "f": 7,
+ })
+ wg.Done()
+ })
+ wg.Wait()
+
+ _cm.mxContexts.Lock()
+ assert.Empty(t, _cm.contexts, "No contexts should be left")
+ _cm.mxContexts.Unlock()
+}
+
+func BenchmarkPut(b *testing.B) {
+ cm := NewManager()
+ c := cm.Enter()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ c.Put("key", "value")
+ }
+}
+
+func BenchmarkAsMap(b *testing.B) {
+ cm := NewManager()
+ cm.Enter().Put("a", 1).Put("b", 2)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ cm.AsMap(nil, true)
+ }
+}
diff --git a/vendor/github.com/getlantern/context/gotrack.go b/vendor/github.com/getlantern/context/gotrack.go
new file mode 100644
index 0000000..7f92346
--- /dev/null
+++ b/vendor/github.com/getlantern/context/gotrack.go
@@ -0,0 +1,130 @@
+package context
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "runtime"
+ "strconv"
+ "sync"
+)
+
+// Sourced https://github.com/bradfitz/http2/blob/dc0c5c000ec33e263612939744d51a3b68b9cece/gotrack.go
+var goroutineSpace = []byte("goroutine ")
+var littleBuf = sync.Pool{
+ New: func() interface{} {
+ buf := make([]byte, 64)
+ return &buf
+ },
+}
+
+func curGoroutineID() uint64 {
+ bp := littleBuf.Get().(*[]byte)
+ defer littleBuf.Put(bp)
+ b := *bp
+ b = b[:runtime.Stack(b, false)]
+ // Parse the 4707 out of "goroutine 4707 ["
+ b = bytes.TrimPrefix(b, goroutineSpace)
+ i := bytes.IndexByte(b, ' ')
+ if i < 0 {
+ panic(fmt.Sprintf("No space found in %q", b))
+ }
+ b = b[:i]
+ n, err := parseUintBytes(b, 10, 64)
+ if err != nil {
+ panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
+ }
+ return n
+}
+
+// parseUintBytes is like strconv.ParseUint, but using a []byte.
+func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) {
+ var cutoff, maxVal uint64
+
+ if bitSize == 0 {
+ bitSize = int(strconv.IntSize)
+ }
+
+ s0 := s
+ switch {
+ case len(s) < 1:
+ err = strconv.ErrSyntax
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+
+ case 2 <= base && base <= 36:
+ // valid base; nothing to do
+
+ case base == 0:
+ // Look for octal, hex prefix.
+ switch {
+ case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'):
+ base = 16
+ s = s[2:]
+ if len(s) < 1 {
+ err = strconv.ErrSyntax
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+ case s[0] == '0':
+ base = 8
+ default:
+ base = 10
+ }
+
+ default:
+ err = errors.New("invalid base " + strconv.Itoa(base))
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+
+ n = 0
+ cutoff = cutoff64(base)
+ maxVal = 1<<uint(bitSize) - 1
+
+ for i := 0; i < len(s); i++ {
+ var v byte
+ d := s[i]
+ switch {
+ case '0' <= d && d <= '9':
+ v = d - '0'
+ case 'a' <= d && d <= 'z':
+ v = d - 'a' + 10
+ case 'A' <= d && d <= 'Z':
+ v = d - 'A' + 10
+ default:
+ n = 0
+ err = strconv.ErrSyntax
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+ if int(v) >= base {
+ n = 0
+ err = strconv.ErrSyntax
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+
+ if n >= cutoff {
+ // n*base overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+ n *= uint64(base)
+
+ n1 := n + uint64(v)
+ if n1 < n || n1 > maxVal {
+ // n+v overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+ }
+ n = n1
+ }
+
+ return n, nil
+}
+
+// Return the first number n such that n*base >= 1<<64.
+func cutoff64(base int) uint64 {
+ if base < 2 {
+ return 0
+ }
+ return (1<<64-1)/uint64(base) + 1
+}