├── LICENSE ├── README.md ├── cmd └── stress │ └── stress.go ├── const.go ├── corruption_test.go ├── cursor.go ├── cursor_test.go ├── diff_tree.go ├── diff_tree_test.go ├── doc.go ├── examples ├── data_corruption_showcase │ └── data_corruption_showcase.go ├── key_value_example │ └── keyvalue_example.go └── snapshot_example │ └── snapshot_example.go ├── extra.go ├── go.mod ├── graph.go ├── hash.go ├── images └── GRAVITON.png ├── node.go ├── node_inner.go ├── node_inner_test.go ├── node_leaf.go ├── node_leaf_test.go ├── node_test.go ├── proof.go ├── proof_test.go ├── snapshot.go ├── snapshot_test.go ├── special.go ├── store.go ├── store_test.go ├── tree.go ├── tree_test.go └── vendor ├── github.com └── stretchr │ └── testify │ ├── .gitignore │ ├── .travis.gofmt.sh │ ├── .travis.gogenerate.sh │ ├── .travis.govet.sh │ ├── .travis.yml │ ├── Gopkg.lock │ ├── Gopkg.toml │ ├── LICENSE │ ├── README.md │ ├── _codegen │ └── main.go │ ├── assert │ ├── assertion_format.go │ ├── assertion_format.go.tmpl │ ├── assertion_forward.go │ ├── assertion_forward.go.tmpl │ ├── assertion_order.go │ ├── assertion_order_test.go │ ├── assertions.go │ ├── assertions_test.go │ ├── doc.go │ ├── errors.go │ ├── forward_assertions.go │ ├── forward_assertions_test.go │ ├── http_assertions.go │ └── http_assertions_test.go │ ├── doc.go │ ├── go.mod │ ├── go.sum │ ├── http │ ├── doc.go │ ├── test_response_writer.go │ └── test_round_tripper.go │ ├── mock │ ├── doc.go │ ├── mock.go │ └── mock_test.go │ ├── package_test.go │ ├── require │ ├── doc.go │ ├── forward_requirements.go │ ├── forward_requirements_test.go │ ├── require.go │ ├── require.go.tmpl │ ├── require_forward.go │ ├── require_forward.go.tmpl │ ├── requirements.go │ └── requirements_test.go │ ├── suite │ ├── doc.go │ ├── interfaces.go │ ├── suite.go │ └── suite_test.go │ └── vendor │ └── github.com │ ├── davecgh │ └── go-spew │ │ ├── LICENSE │ │ └── spew │ │ ├── bypass.go │ │ ├── bypasssafe.go │ │ ├── common.go │ │ ├── config.go │ │ ├── doc.go │ │ ├── dump.go │ │ ├── format.go │ │ └── spew.go │ ├── pmezard │ └── go-difflib │ │ ├── LICENSE │ │ └── difflib │ │ └── difflib.go │ └── stretchr │ └── objx │ ├── LICENSE │ ├── accessors.go │ ├── constants.go │ ├── conversions.go │ ├── doc.go │ ├── map.go │ ├── mutations.go │ ├── security.go │ ├── tests.go │ ├── type_specific_codegen.go │ └── value.go ├── golang.org └── x │ ├── crypto │ └── blake2s │ │ ├── blake2s.go │ │ ├── blake2s_386.go │ │ ├── blake2s_386.s │ │ ├── blake2s_amd64.go │ │ ├── blake2s_amd64.s │ │ ├── blake2s_generic.go │ │ ├── blake2s_ref.go │ │ ├── blake2s_test.go │ │ ├── blake2x.go │ │ └── register.go │ ├── sys │ └── cpu │ │ ├── asm_aix_ppc64.s │ │ ├── byteorder.go │ │ ├── cpu.go │ │ ├── cpu_aix.go │ │ ├── cpu_arm.go │ │ ├── cpu_arm64.go │ │ ├── cpu_arm64.s │ │ ├── cpu_gc_arm64.go │ │ ├── cpu_gc_s390x.go │ │ ├── cpu_gc_x86.go │ │ ├── cpu_gccgo_arm64.go │ │ ├── cpu_gccgo_s390x.go │ │ ├── cpu_gccgo_x86.c │ │ ├── cpu_gccgo_x86.go │ │ ├── cpu_linux.go │ │ ├── cpu_linux_arm.go │ │ ├── cpu_linux_arm64.go │ │ ├── cpu_linux_mips64x.go │ │ ├── cpu_linux_noinit.go │ │ ├── cpu_linux_ppc64x.go │ │ ├── cpu_linux_s390x.go │ │ ├── cpu_mips64x.go │ │ ├── cpu_mipsx.go │ │ ├── cpu_other_arm.go │ │ ├── cpu_other_arm64.go │ │ ├── cpu_ppc64x.go │ │ ├── cpu_riscv64.go │ │ ├── cpu_s390x.go │ │ ├── cpu_s390x.s │ │ ├── cpu_test.go │ │ ├── cpu_wasm.go │ │ ├── cpu_x86.go │ │ ├── cpu_x86.s │ │ ├── hwcap_linux.go │ │ ├── syscall_aix_gccgo.go │ │ └── syscall_aix_ppc64_gc.go │ └── xerrors │ ├── LICENSE │ ├── PATENTS │ ├── README │ ├── adaptor.go │ ├── codereview.cfg │ ├── doc.go │ ├── errors.go │ ├── errors_test.go │ ├── example_As_test.go │ ├── example_FormatError_test.go │ ├── example_test.go │ ├── fmt.go │ ├── fmt_test.go │ ├── fmt_unexported_test.go │ ├── format.go │ ├── frame.go │ ├── go.mod │ ├── internal │ └── internal.go │ ├── stack_test.go │ ├── wrap.go │ ├── wrap_113_test.go │ └── wrap_test.go └── gopkg.in └── yaml.v2 ├── .travis.yml ├── LICENSE ├── LICENSE.libyaml ├── NOTICE ├── README.md ├── apic.go ├── decode.go ├── decode_test.go ├── emitterc.go ├── encode.go ├── encode_test.go ├── example_embedded_test.go ├── go.mod ├── limit_test.go ├── parserc.go ├── readerc.go ├── resolve.go ├── scannerc.go ├── sorter.go ├── suite_test.go ├── writerc.go ├── yaml.go ├── yamlh.go └── yamlprivateh.go /cmd/stress/stress.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "flag" 4 | import "os" 5 | import "log" 6 | import "math" 7 | import "encoding/binary" 8 | import "crypto/rc4" 9 | import "path/filepath" 10 | import "bytes" 11 | import "runtime/pprof" 12 | import "github.com/deroproject/graviton" 13 | 14 | var rt = filepath.Join 15 | 16 | const keysize uint64 = 64 // in bytes 17 | const valuesize uint64 = 512 // in bytes 18 | var stepsize = flag.Uint64("stepsize", 10, "Every commit will include this much data in MB") 19 | var totalsize = flag.Uint64("totalsize", 500, "Total this much data will be written in MB ( use 0 for infinite )") 20 | var db_directory = flag.String("db_directory", "/tmp", "DB will be created in this path, will be cleared on exit") 21 | var memory = flag.Bool("memory", true, "DB will by default use memory backend (use -memory=false for disk based tests)") 22 | var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") 23 | 24 | 25 | var step uint64 26 | var keys_written uint64 27 | 28 | func main() { 29 | log.Printf("Graviton DB stress tester") 30 | log.Printf("NOTE: Do not use rotational media") 31 | 32 | flag.Parse() 33 | if *cpuprofile != "" { 34 | f, err := os.Create(*cpuprofile) 35 | if err != nil { 36 | log.Fatal("could not create CPU profile: ", err) 37 | } 38 | defer f.Close() // error handling omitted for example 39 | if err := pprof.StartCPUProfile(f); err != nil { 40 | log.Fatal("could not start CPU profile: ", err) 41 | } 42 | defer pprof.StopCPUProfile() 43 | } 44 | 45 | if *stepsize < 1 { 46 | *stepsize = 1 47 | } 48 | 49 | if *totalsize == 0 { 50 | *totalsize = math.MaxUint64 51 | } 52 | if *stepsize > 512 { 53 | *stepsize = 512 54 | } 55 | if *stepsize > *totalsize { 56 | *stepsize = *totalsize 57 | } 58 | 59 | log.Printf("Total Size (to be written): %d MB", *totalsize) 60 | log.Printf("Commit size: %d MB", *stepsize) 61 | 62 | var store *graviton.Store 63 | var err error 64 | if *memory { 65 | store, err = graviton.NewMemStore() // create a new DB in RAM 66 | log.Printf("Using memory backend\n") 67 | } else { 68 | store, err = graviton.NewDiskStore(filepath.Join(*db_directory, "graviton_stress_db")) // create a new testdb in "/tmp/testdb" 69 | log.Printf("Using disk backend, db_directory: %s\n", filepath.Join(*db_directory, "graviton_stress_db")) 70 | } 71 | 72 | if err != nil { 73 | log.Fatalf("stress db creation err %s", err) 74 | } 75 | 76 | gv, err := store.LoadSnapshot(0) 77 | if err != nil { 78 | log.Fatalf("stress db LoadSnapshot err %s", err) 79 | } 80 | 81 | write_tree, err := gv.GetTree("stress_testing") 82 | if err != nil { 83 | log.Fatalf("stress db GetTree err %s", err) 84 | } 85 | 86 | for i := uint64(0); i < *totalsize / *stepsize; i++ { 87 | log.Printf("Running step %d %f completed total keys %d", i, float64(i*100)/float64(*totalsize / *stepsize), keys_written) 88 | RunStep(store,write_tree) 89 | } 90 | log.Printf("Completed step %d %f completed total keys %d", (*totalsize / *stepsize), float32(100), keys_written) 91 | 92 | } 93 | 94 | // each step consists of generating pseudorandom data, which is first committed and then verified after each step 95 | func RunStep(store *graviton.Store, write_tree *graviton.Tree) { 96 | var read_tree *graviton.Tree 97 | values_count := (*stepsize * 1024 * 1024 / valuesize) + 1 98 | 99 | key_buf := make([]byte, values_count*keysize, values_count*keysize) 100 | value_buf := make([]byte, values_count*valuesize, values_count*valuesize) 101 | 102 | var cryptokey, cryptovalue [9]byte 103 | 104 | cryptokey[0] = 1 105 | binary.LittleEndian.PutUint64(cryptokey[1:], step) 106 | binary.LittleEndian.PutUint64(cryptovalue[1:], step) 107 | 108 | keycipher, _ := rc4.NewCipher(cryptokey[:]) 109 | valuecipher, _ := rc4.NewCipher(cryptovalue[:]) 110 | 111 | keycipher.XORKeyStream(key_buf[:], key_buf[:]) 112 | valuecipher.XORKeyStream(value_buf[:], value_buf[:]) 113 | 114 | 115 | 116 | for i := uint64(0); i < values_count; i++ { 117 | write_tree.Put(key_buf[i*keysize:(i+1)*keysize], value_buf[i*valuesize:(i+1)*valuesize]) 118 | keys_written++ 119 | } 120 | write_tree.Commit() // 121 | 122 | read_tree = write_tree // use same tree to read write 123 | /* 124 | // now we will load another tree from storage without cache and read everything back and verify 125 | gv_read, err := store.LoadSnapshot(0) 126 | if err != nil { 127 | log.Fatalf("stress db LoadSnapshot err %s", err) 128 | } 129 | 130 | read_tree, err := gv_read.GetTree("stress_testing") 131 | if err != nil { 132 | log.Fatalf("stress db GetTree err %s", err) 133 | } 134 | */ 135 | for i := uint64(0); i < values_count; i++ { 136 | if value, err := read_tree.Get(key_buf[i*keysize : (i+1)*keysize]); err == nil { 137 | 138 | if bytes.Compare(value, value_buf[i*valuesize:(i+1)*valuesize]) == 0 { 139 | // value macthed nothing to do 140 | 141 | } else { // value error 142 | log.Fatalf("value mismatched") 143 | } 144 | 145 | } else { // key not existent or other err, stop testing 146 | log.Fatalf("err occured while verifying tree err %s", err) 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /const.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import "errors" 4 | 5 | const ( 6 | HASHSIZE_BYTES = 32 // we currently are using blake hash which is 256 bits or 32 bytes 7 | HASHSIZE = HASHSIZE_BYTES 8 | HASHSIZE_BITS = HASHSIZE_BYTES * 8 // hash size in bits 9 | MINBLOCK = 512 // max block size excluding value 10 | MAX_KEYSIZE = MINBLOCK - 64 // 64 bytes are reserved, keys are limited to 448 bytes 11 | MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 // 2GB since we use split files to store data chunks 12 | MAX_VALUE_SIZE = 100 * 1024 * 1024 // values are limited to this size 13 | TREE_NAME_LIMIT = 127 // TREE name cannot be larger than this in bytes ( not in utf8 chars) 14 | ) 15 | 16 | const internal_MAX_VERSIONS_TO_KEEP = 20 // this many recent versions will be kept 17 | const internal_VERSION_RECORD_SIZE = 24 // three uint64 18 | 19 | var ( 20 | ErrNotFound = errors.New("leaf not found") 21 | ErrVersionNotStored = errors.New("no such version") 22 | ErrCorruption = errors.New("Data Corruption") 23 | ErrNoMoreKeys = errors.New("No more keys exist") 24 | ) 25 | -------------------------------------------------------------------------------- /corruption_test.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import ( 4 | "bytes" 5 | "io/ioutil" 6 | "os" 7 | "path/filepath" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | // this creates a persistant store in tmp dir 14 | // then commits and does a number of tests 15 | // the closes the store and reopens and does all the tests again 16 | func TestCorruptionStore_basic(t *testing.T) { 17 | 18 | key := []byte("key1key1key1key1key1key1key1key1key1key1key1key1key1key1") 19 | value := []byte("This value is good") // an 100 KB value, which will be corrupted later on disk to showcase detection 20 | value_corrupted := []byte("Corrupted value !!") 21 | 22 | dir, err := ioutil.TempDir("", "graviton_showcase_") 23 | require.NoError(t, err) 24 | 25 | defer os.RemoveAll(dir) // clean up 26 | 27 | store, err := NewDiskStore(dir) 28 | require.NoError(t, err) 29 | 30 | gv, err := store.LoadSnapshot(0) 31 | require.NoError(t, err) 32 | tree, err := gv.GetTree("treename") 33 | require.NoError(t, err) 34 | 35 | err = tree.Put(key, value) 36 | require.NoError(t, err) 37 | 38 | _, err = Commit(tree) 39 | require.NoError(t, err) 40 | 41 | gv, err = store.LoadSnapshot(0) 42 | require.NoError(t, err) 43 | tree, err = gv.GetTree("treename") 44 | require.NoError(t, err) 45 | value, err = tree.Get(key) 46 | 47 | //fmt.Printf("Reading value before corruption \"%s\" err %s\n", string(value), err) 48 | 49 | // now the key has been persisted and verified now we will corrupt the value 50 | file, err := os.OpenFile(filepath.Join(dir, "0", "0", "0", "0.dfs"), os.O_RDWR, 0644) 51 | require.NoError(t, err) 52 | 53 | file_contents, err := ioutil.ReadFile(filepath.Join(dir, "0", "0", "0", "0.dfs")) 54 | require.NoError(t, err) 55 | 56 | index := bytes.Index(file_contents, value) 57 | if index < 0 { 58 | panic("err could not find value in DB") 59 | } 60 | 61 | //fmt.Printf("contain count %d\n", bytes.Count(file_contents,value)) 62 | 63 | file.WriteAt(value_corrupted, int64(index)) 64 | file.Close() 65 | 66 | gv, err = store.LoadSnapshot(0) 67 | require.NoError(t, err) 68 | tree1, err := gv.GetTree("treename") 69 | require.NoError(t, err) 70 | _, err = tree1.Get(key) 71 | require.Error(t, err) 72 | 73 | dummytree, err := gv.GetTree("dummytree") 74 | require.NoError(t, err) 75 | require.Error(t, Diff(tree1, dummytree, nil, nil, nil)) 76 | 77 | } 78 | 79 | func TestCorruptionStore_Left(t *testing.T) { 80 | 81 | key := []byte("key1key1key1key1key1key1key1key1key1key1key1key1key1key1") 82 | value := []byte("This value is good") // an 100 KB value, which will be corrupted later on disk to showcase detection 83 | value_corrupted := []byte("Corrupted value !!") 84 | 85 | dir, err := ioutil.TempDir("", "graviton_showcase1_") 86 | require.NoError(t, err) 87 | 88 | defer os.RemoveAll(dir) // clean up 89 | 90 | store, err := NewDiskStore(dir) 91 | require.NoError(t, err) 92 | 93 | gv, err := store.LoadSnapshot(0) 94 | require.NoError(t, err) 95 | tree, err := gv.GetTree("treename") 96 | require.NoError(t, err) 97 | 98 | for i := 0; i < 8; i++ { 99 | key1 := randStr(60) 100 | value1 := randStr(512) 101 | tree.Put([]byte(key1), []byte(value1)) 102 | } 103 | err = tree.Put(key, value) 104 | require.NoError(t, err) 105 | tree.Commit() // commit the tree 106 | 107 | gv, err = store.LoadSnapshot(0) 108 | require.NoError(t, err) 109 | tree, err = gv.GetTree("treename") 110 | require.NoError(t, err) 111 | value, err = tree.Get(key) 112 | 113 | //fmt.Printf("Reading value before corruption \"%s\" err %s\n", string(value), err) 114 | 115 | // now the key has been persisted and verified now we will corrupt the value 116 | file, err := os.OpenFile(filepath.Join(dir, "0", "0", "0", "0.dfs"), os.O_RDWR, 0644) 117 | require.NoError(t, err) 118 | 119 | file_contents, err := ioutil.ReadFile(filepath.Join(dir, "0", "0", "0", "0.dfs")) 120 | require.NoError(t, err) 121 | 122 | index := bytes.Index(file_contents, value) 123 | if index < 0 { 124 | panic("err could not find value in DB") 125 | } 126 | 127 | //fmt.Printf("contain count %d\n", bytes.Count(file_contents,value)) 128 | 129 | file.WriteAt(value_corrupted, int64(index)) 130 | file.Close() 131 | 132 | gv, err = store.LoadSnapshot(0) 133 | require.NoError(t, err) 134 | tree1, err := gv.GetTree("treename") 135 | require.NoError(t, err) 136 | _, err = tree1.Get(key) 137 | require.Error(t, err) 138 | 139 | dummytree, err := gv.GetTree("dummytree") 140 | require.NoError(t, err) 141 | require.Error(t, Diff(tree1, dummytree, nil, nil, nil)) 142 | 143 | } 144 | -------------------------------------------------------------------------------- /cursor.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import "fmt" 4 | 5 | //Cursor represents an iterator that can traverse over all key/value pairs in a tree in hash sorted order. 6 | //Cursors can be obtained from a tree and are valid as long as the tree is valid. 7 | //Keys and values returned from the cursor are only valid for the life of the transaction. 8 | //Changing tree (before committing) while traversing with a cursor may cause it to be invalidated and return unexpected keys and/or values. You must reposition your cursor after mutating data. 9 | type Cursor struct { 10 | tree *Tree 11 | 12 | node_path []*inner 13 | left []bool // it basically represents the path as bools 14 | 15 | } 16 | 17 | // get Cursor which is used as an iterator that can traverse over all key/value pairs in a tree in hash sorted order. 18 | func (t *Tree) Cursor() Cursor { 19 | return Cursor{tree: t} 20 | } 21 | 22 | // First moves the cursor to the first item in the tree and returns its key and value. If the tree is empty then an error is returned. The returned key and value are only valid for the life of the tree. 23 | func (c *Cursor) First() (k, v []byte, err error) { 24 | // the function is iterative and not recursive 25 | return c.next_internal(node(c.tree.root), false) 26 | } 27 | 28 | // Last moves the cursor to the last item in the tree and returns its key and value. If the tree is empty then an error is returned. The returned key and value are only valid for the life of the tree. 29 | func (c *Cursor) Last() (k, v []byte, err error) { 30 | // the function is iterative and not recursive 31 | return c.next_internal(node(c.tree.root), true) 32 | } 33 | 34 | // this function will descend and reach the next or previous value 35 | func (c *Cursor) next_internal(loop_node node, reverse bool) (k, v []byte, err error) { 36 | for { 37 | switch node := loop_node.(type) { 38 | case *inner: 39 | if node.loaded_partial { // if node is loaded partially, load it fully now 40 | if err = node.loadinnerfromstore(c.tree.store); err != nil { 41 | return 42 | } 43 | } 44 | 45 | left, right := node.left, node.right 46 | if reverse { 47 | left, right = right, left 48 | } 49 | 50 | if left != nil { 51 | c.node_path = append(c.node_path, node) 52 | c.left = append(c.left, true == !reverse) 53 | loop_node = left 54 | continue // we must descend further 55 | } 56 | 57 | if right != nil { 58 | c.node_path = append(c.node_path, node) 59 | c.left = append(c.left, false == !reverse) 60 | loop_node = right 61 | continue // we must descend further 62 | } 63 | 64 | // we can only reach here if a tree has both left,right nil, ie an empty tree 65 | err = ErrNoMoreKeys 66 | return 67 | break 68 | 69 | case *leaf: 70 | if node.loaded_partial { // if leaf is loaded partially, load it fully now 71 | if err = node.loadfullleaffromstore(c.tree.store); err != nil { 72 | return 73 | } 74 | } 75 | return node.key, node.value, nil 76 | default: 77 | return k, v, fmt.Errorf("unknown node type, corruption") 78 | } 79 | } 80 | } 81 | 82 | // Next moves the cursor to the next item in the tree and returns its key and value.If the tree is empty then an error is returned.If the cursor is at the end of the tree, then an error is returned. The returned key and value are only valid for the life of the tree. 83 | func (c *Cursor) Next() (k, v []byte, err error) { 84 | 85 | try_again: 86 | if len(c.node_path) == 0 { 87 | err = ErrNoMoreKeys 88 | return 89 | } 90 | cur_node_index := len(c.node_path) - 1 91 | 92 | if !c.left[cur_node_index] || c.node_path[cur_node_index].right == nil { // since we are a right node, we must back track one node 93 | c.node_path = c.node_path[:cur_node_index] 94 | c.left = c.left[:cur_node_index] 95 | goto try_again 96 | } 97 | // we are here means we are on a left node, lets check the right node 98 | c.left[cur_node_index] = false 99 | 100 | if err = c.node_path[cur_node_index].right.load_partial(c.tree.store); err != nil { 101 | return 102 | } 103 | switch node := c.node_path[cur_node_index].right.(type) { 104 | case *inner: 105 | return c.next_internal(node, false) 106 | case *leaf: 107 | return node.key, node.value, nil 108 | 109 | default: 110 | return k, v, fmt.Errorf("unknown node type, corruption") 111 | } 112 | } 113 | 114 | // Prev moves the cursor to the prev item in the tree and returns its key and value.If the tree is empty then an error is returned.If the cursor is at the end of the tree, then an error is returned. The returned key and value are only valid for the life of the tree. 115 | func (c *Cursor) Prev() (k, v []byte, err error) { 116 | try_again: 117 | if len(c.node_path) == 0 { 118 | err = ErrNoMoreKeys 119 | return 120 | } 121 | cur_node_index := len(c.node_path) - 1 122 | if c.left[cur_node_index] || c.node_path[cur_node_index].left == nil { // since we are a right node, we must back track one node 123 | c.node_path = c.node_path[:cur_node_index] 124 | c.left = c.left[:cur_node_index] 125 | goto try_again 126 | } 127 | // we are here means we are on a right node, lets check the left node 128 | c.left[cur_node_index] = true 129 | 130 | if err = c.node_path[cur_node_index].left.load_partial(c.tree.store); err != nil { 131 | return 132 | } 133 | switch node := c.node_path[cur_node_index].left.(type) { 134 | case *inner: 135 | return c.next_internal(node, true) 136 | case *leaf: 137 | return node.key, node.value, nil 138 | 139 | default: 140 | 141 | return k, v, fmt.Errorf("unknown node type, corruption") 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright dero developers 2 | 3 | /* 4 | GravitonDB in short is "ZFS for key-value stores". 5 | 6 | GravitonDB is a pure Go key/value store having features unmatched by other software (such as Boltdb, berkeleydb, mysql, postgresql etc). The goal of the project is to provide a simple, fast, reliable, versioned, authenticated database for projects which require such features. 7 | 8 | Since GravitonDB is meant to be used as such a low-level piece of functionality, simplicity is key. The API will be small and only focus on getting values and setting values. That's it. 9 | 10 | GravitonDB is a key value store having 11 | 1) cryptographically authenticated ( a single hash verifies complete data store) 12 | 2) append only 13 | 3) versioning 14 | 4) Writable snapshots 15 | 5) exabyte storage capable, (tested upto Terabytes, if you can help with testing petabyte capability please discuss with authors) 16 | 6) cryptographic proof capability to prove existence/non-existence of any arbitrary key 17 | 7) ability to diff 2 trees in linear time 18 | 8) designed and developed for DERO blockchain 19 | 20 | 21 | Features 22 | 23 | * Authenticated data store ( all keys, values are backed by blake 256 bit checksum) 24 | * Append only data store 25 | * Support of 2^64 trees ( Theoretically ) within a single data store. trees can be named and thus used as buckets 26 | * Versioning support ( all committed changes are versioned with ability to visit them at any point in time ) 27 | * Snapshots ( multi tree commits in a single version causing multi tree sync, each snapshot can be visited, appended and further modified, keys deleted, values modified etc, new keys, values stored ) 28 | * Ability to iterate over all key-value pairs in a tree 29 | * Ability to diff between 2 trees in linear time and report all changes (insertions,deletions,modifications) 30 | * Minimal, small, simplified API 31 | * Theoretically support Exabyte data store, multi Terabyte tested internally 32 | * Decoupled storage layer, allowing use of object stores such as Ceph, AWS etc 33 | * Ability to generate cryptographic proofs which can prove key existance or non-existance ( proofs are around 1 KB ) 34 | * Superfast proof generation time of around 1000 proofs per second per core 35 | * Support for disk based filesystem based persistant stores. 36 | * Support for memory based non-persistant stores 37 | * 100% code coverage 38 | * this is alpha software, we are still evaluating a number of ideas 39 | 40 | 41 | Eg. Minimal code, to write and read back a value (error checking is skipped) 42 | store, _ := NewDiskStore("/tmp/testdb") // create a new testdb in "/tmp/testdb" 43 | ss, _ := store.LoadSnapshot(0) // load most recent snapshot 44 | tree, _ := ss.GetTree("root") // use or create tree named "root" 45 | tree.Put([]byte("key"), []byte("value")) // insert a value 46 | Commit(tree) // commit the tree 47 | value, _ = tree.Get([]byte("key")) 48 | 49 | 50 | 51 | Eg, Snapshots, see github.com/deroproject/gravitondb/examples/snapshot_example//snapshot_example.go 52 | 53 | 54 | 55 | The design enables infinite trees with infinite snapshots. The design enables designs such as dedeuplicating backups, blockchains which 56 | enable proving their data ( both state and content) to users etc 57 | 58 | */ 59 | package graviton 60 | -------------------------------------------------------------------------------- /examples/data_corruption_showcase/data_corruption_showcase.go: -------------------------------------------------------------------------------- 1 | /* 2 | Graviton showcase data corruption example. 3 | */ 4 | 5 | package main 6 | 7 | import "os" 8 | import "fmt" 9 | import "log" 10 | import "bytes" 11 | import "io/ioutil" 12 | import "path/filepath" 13 | import "github.com/deroproject/graviton" 14 | 15 | 16 | func handle_error(err error, msg string){ 17 | if err != nil { 18 | log.Fatalf("%s err:\n",msg, err) 19 | } 20 | } 21 | 22 | func main() { 23 | 24 | 25 | 26 | key := []byte("key1key1key1key1key1key1key1key1key1key1key1key1key1key1") 27 | value := []byte("This value is good") // an value, which will be corrupted later on disk to showcase detection 28 | value_corrupted := []byte("Corrupted value !!") 29 | 30 | dir, err := ioutil.TempDir("", "graviton_showcase_") 31 | handle_error(err,"err opening database") 32 | 33 | defer os.RemoveAll(dir) // clean up 34 | 35 | store, err := graviton.NewDiskStore(dir) 36 | handle_error(err,"err opening diskstore") 37 | 38 | gv, err := store.LoadSnapshot(0) 39 | handle_error(err,"err opening snapshot") 40 | tree, err := gv.GetTree("treename") 41 | handle_error(err,"err opening tree") 42 | 43 | err = tree.Put(key, value); 44 | handle_error(err,"err writing value to diskstore") 45 | 46 | _, err = graviton.Commit(tree); 47 | handle_error(err,"err committing tree to diskstore") 48 | 49 | gv, err = store.LoadSnapshot(0) 50 | handle_error(err,"err opening snapshot") 51 | tree, err = gv.GetTree("treename") 52 | handle_error(err,"err opening tree") 53 | value,err = tree.Get(key) 54 | 55 | fmt.Printf("Reading value before corruption \"%s\" err %s\n", string(value), err) 56 | 57 | 58 | // now the key has been persisted and verified now we will corrupt the value 59 | file, err := os.OpenFile(filepath.Join(dir,"0","0","0","0.dfs"), os.O_RDWR, 0644) 60 | handle_error(err,"err opening db file in raw mode for corruption") 61 | 62 | file_contents,err := ioutil.ReadFile( filepath.Join(dir,"0","0","0","0.dfs")) 63 | handle_error(err,"err read db file in raw mode for corruption") 64 | 65 | index := bytes.Index(file_contents,value) 66 | if index < 0 { 67 | handle_error(err,"err could not find value in DB") 68 | } 69 | 70 | //fmt.Printf("contain count %d\n", bytes.Count(file_contents,value)) 71 | 72 | file.WriteAt(value_corrupted, int64(index)) 73 | file.Close() 74 | 75 | gv, err = store.LoadSnapshot(0) 76 | handle_error(err,"err opening snapshot") 77 | tree1, err := gv.GetTree("treename") 78 | handle_error(err,"err opening tree") 79 | value_back,err := tree1.Get(key) 80 | 81 | if err != nil { 82 | fmt.Printf("Value Corruption detected %s\n",err) 83 | return 84 | }else{ 85 | 86 | fmt.Printf("Reading value after corruption \"%s\" err %s\n", string(value_back), err) 87 | } 88 | 89 | 90 | } 91 | -------------------------------------------------------------------------------- /examples/key_value_example/keyvalue_example.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "github.com/deroproject/graviton" 5 | 6 | func main() { 7 | //store, _ := graviton.NewDiskStore("/tmp/testdb") // create a new testdb in "/tmp/testdb" 8 | store, _ := graviton.NewMemStore() // create a new DB in RAM 9 | ss, _ := store.LoadSnapshot(0) // load most recent snapshot 10 | tree, _ := ss.GetTree("root") // use or create tree named "root" 11 | tree.Put([]byte("key"), []byte("value")) // insert a value 12 | _, _ = graviton.Commit(tree) // commit the tree 13 | value, _ := tree.Get([]byte("key")) 14 | 15 | fmt.Printf("value retrived from DB \"%s\"\n", string(value)) 16 | 17 | } 18 | -------------------------------------------------------------------------------- /examples/snapshot_example/snapshot_example.go: -------------------------------------------------------------------------------- 1 | /* 2 | Graviton snapshot example. 3 | */ 4 | 5 | package main 6 | 7 | import "fmt" 8 | import "github.com/deroproject/graviton" 9 | 10 | func main() { 11 | 12 | key := []byte("key1") 13 | store, _ := graviton.NewDiskStore("/tmp/testdb") // create a new testdb in "/tmp/testdb" 14 | //store, _ := graviton.NewMemStore() // create a new DB in RAM 15 | ss, _ := store.LoadSnapshot(0) // load most recent snapshot 16 | tree, _ := ss.GetTree("root") // use or create tree named "root" 17 | tree.Put(key, []byte("commit_value1")) // insert a value 18 | commit1, _ := graviton.Commit(tree) // commit the tree 19 | tree.Put(key, []byte("commit_value2")) // overwrite existing value 20 | commit2, _ := graviton.Commit(tree) // commit the tree again 21 | 22 | // at this point, you have done 2 commits 23 | // at first commit, "root" tree contains "key : commit_value1" 24 | // at second commit, "root" tree contains "key : commit_value2" 25 | 26 | // we will traverse now commit1 snapshot 27 | ss, _ = store.LoadSnapshot(commit1) 28 | tree, _ = ss.GetTree("root") 29 | value, err := tree.Get(key) 30 | fmt.Printf(" snapshot%d key %s value %s err %s\n", ss.GetVersion(), string(key), string(value), err) 31 | 32 | // we will traverse now commit2 snapshot 33 | ss, _ = store.LoadSnapshot(commit2) 34 | tree, _ = ss.GetTree("root") 35 | value, err = tree.Get(key) 36 | fmt.Printf(" snapshot%d key %s value %s err %s\n", ss.GetVersion(), string(key), string(value), err) 37 | } 38 | -------------------------------------------------------------------------------- /extra.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import "fmt" 4 | import "math" 5 | import "crypto/rand" 6 | 7 | 8 | func (t *Tree) GetName() (string) { 9 | return t.treename 10 | } 11 | // Random returns a random key,value from the tree, provided a tree has keys 12 | // the following are limitations 13 | // a tree containing 0 key, value pairs will return err 14 | // randomness depends on number of keys, if tree contains only 1 value, it will be ported etc 15 | func (t *Tree) Random() (k, v []byte, err error) { 16 | return t.random(t.root) 17 | } 18 | func (t *Tree) random(cnode node) (k, v []byte, err error) { 19 | switch node := cnode.(type) { 20 | case *inner: 21 | if node.loaded_partial { // if node is loaded partially, load it fully now 22 | if err = node.loadinnerfromstore(t.store); err != nil { 23 | return 24 | } 25 | } 26 | left, right := node.left, node.right 27 | if left != nil && right != nil { // we have an option to choose from left or right randomly 28 | var rbyte [1]byte 29 | if _, err = rand.Read(rbyte[:]); err != nil { 30 | return 31 | } 32 | if rbyte[0]&1 == 1 { 33 | return t.random(right) // descend further 34 | } 35 | return t.random(left) // descend further 36 | } 37 | 38 | if right != nil { 39 | return t.random(right) // descend further without any option 40 | } 41 | 42 | if left != nil { 43 | return t.random(left) // descend further without any option 44 | } 45 | 46 | // we can only reach here if a tree has both left,right nil, ie an empty tree 47 | err = ErrNoMoreKeys 48 | return 49 | case *leaf: 50 | if node.loaded_partial { // if leaf is loaded partially, load it fully now 51 | if err = node.loadfullleaffromstore(t.store); err != nil { 52 | return 53 | } 54 | } 55 | return node.key, node.value, nil 56 | default: 57 | return k, v, fmt.Errorf("unknown node type, corruption") 58 | } 59 | } 60 | 61 | // estimate number of keys that exist in the tree 62 | // very crude but only used for use display 63 | func (t *Tree) KeyCountEstimate() (count int64) { 64 | c := t.Cursor() 65 | 66 | var depth_array []int 67 | var floatsum float64 68 | for _, _, err := c.First(); err == nil; _, _, err = c.Next() { 69 | floatsum += float64(len(c.node_path)) 70 | depth_array = append(depth_array, len(c.node_path)) 71 | if len(depth_array) >= 20 { 72 | break 73 | } 74 | } 75 | if len(depth_array) <= 4 { 76 | return int64(count) 77 | } 78 | avg := floatsum / float64(len(depth_array)+1) 79 | return int64(math.Exp2(avg)) 80 | } 81 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/deroproject/graviton 2 | 3 | go 1.14 4 | -------------------------------------------------------------------------------- /graph.go: -------------------------------------------------------------------------------- 1 | //+build ignore 2 | 3 | package graviton 4 | 5 | import "os" 6 | import "fmt" 7 | import "bufio" 8 | 9 | // this function will export the tree to a dor graph file to understand any issues 10 | func (t *Tree) Graph(fname string) (err error) { 11 | 12 | f, err := os.Create(fname) 13 | if err != nil { 14 | return 15 | } 16 | defer f.Close() 17 | 18 | w := bufio.NewWriter(f) 19 | defer w.Flush() 20 | 21 | w.WriteString("digraph graviton_graph { \n") 22 | defer w.WriteString(" \n}\n") 23 | 24 | t.graph(t.root, w) 25 | return nil 26 | } 27 | func (t *Tree) graph(cnode node, w *bufio.Writer) { 28 | var err error 29 | switch node := cnode.(type) { 30 | case *inner: 31 | if node.loaded_partial { // if node is loaded partially, load it fully now 32 | if err = node.loadinnerfromstore(t.store); err != nil { 33 | return 34 | } 35 | } 36 | 37 | w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) 38 | hash, _ := node.Hash(t.store) 39 | w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x\" ];\n", hash, "red", hash)) 40 | w.WriteString(fmt.Sprintf("}\n")) 41 | 42 | left, right := node.left, node.right 43 | 44 | if right != nil { 45 | rhash, _ := right.Hash(t.store) 46 | w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, rhash)) 47 | t.graph(right, w) // descend further without any option 48 | } 49 | 50 | if left != nil { 51 | lhash, _ := left.Hash(t.store) 52 | w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, lhash)) 53 | t.graph(left, w) // descend further without any option 54 | } 55 | 56 | return 57 | case *leaf: 58 | if node.loaded_partial { // if leaf is loaded partially, load it fully now 59 | if err = node.loadfullleaffromstore(t.store); err != nil { 60 | return 61 | } 62 | } 63 | w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) 64 | hash, _ := node.Hash(t.store) 65 | keyhash := sum(node.key) 66 | w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x %x\" ];\n", hash, "green", hash, keyhash)) 67 | w.WriteString(fmt.Sprintf("}\n")) 68 | //return node.key, node.value, nil 69 | default: 70 | panic("unknown node type, corruption") 71 | return 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /hash.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import "hash" 4 | 5 | //import "crypto/sha256" 6 | import "golang.org/x/crypto/blake2s" 7 | 8 | const lastBit = HASHSIZE*8 - 1 9 | 10 | var zerosHash, zeros [HASHSIZE]byte // all empty nodes have this hash 11 | 12 | func hasher() hash.Hash { 13 | //return sha256.New() 14 | h, _ := blake2s.New256(nil) 15 | return h 16 | } 17 | 18 | func sum(key []byte) (keyhash [HASHSIZE]byte) { 19 | return blake2s.Sum256(key) 20 | } 21 | 22 | func init() { 23 | h := hasher() 24 | h.Write([]byte{leafNODE}) 25 | h.Write(zeros[:]) 26 | tmp := zerosHash[:0] 27 | h.Sum(tmp) 28 | } 29 | -------------------------------------------------------------------------------- /images/GRAVITON.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deroproject/graviton/2c248a53b2e1529172cb4f99f8e89b1821075130/images/GRAVITON.png -------------------------------------------------------------------------------- /node.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | const ( 4 | nullNODE byte = iota 5 | innerNODE 6 | leafNODE 7 | ) 8 | 9 | // we can get away with runtime type detection 10 | func getNodeType(n node) byte { 11 | switch n.(type) { 12 | case nil: 13 | return nullNODE 14 | case *inner: 15 | return innerNODE 16 | case *leaf: 17 | return leafNODE 18 | default: 19 | panic("unknown type") 20 | } 21 | } 22 | 23 | // TODO simplify node 24 | type node interface { 25 | isDirty() bool 26 | load_partial(*Store) error 27 | Hash(*Store) ([]byte, error) 28 | Get(*Store, [HASHSIZE]byte) ([]byte, error) 29 | Delete(*Store, [HASHSIZE]byte) (bool, bool, error) 30 | Position() (uint32, uint32) 31 | Prove(*Store, [HASHSIZE]byte, *Proof) error 32 | } 33 | 34 | // these will enable processing of all bits collective from MSB to LSB 35 | func setBit(keyhash []byte, index uint) { 36 | pos, bit := index/8, index%8 37 | keyhash[pos] = (keyhash[pos] | (1 << (8 - (bit + 1)))) 38 | } 39 | 40 | func isBitSet(keyhash []byte, index uint) bool { 41 | pos, bit := index/8, index%8 42 | return (keyhash[pos] & (1 << (8 - (bit + 1)))) > 0 43 | } 44 | -------------------------------------------------------------------------------- /node_inner_test.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import ( 4 | "github.com/stretchr/testify/require" 5 | "testing" 6 | ) 7 | 8 | func TestInnerUnMarshal(t *testing.T) { 9 | var buffs = [][]byte{ 10 | []byte{0, 0}, // small buf error 11 | []byte{24, innerNODE, 0, 0, 0, 0, 0x88, 0x88, 0x88, 0x88, 0x88, 0x8}, // more than 4 billion findex left node 12 | []byte{24, innerNODE, 0, 0, 0, 0, 0x10, 0x88, 0x88, 0x88, 0x88, 0x88, 0x8}, // more than 4 billion fpos left node 13 | []byte{24, innerNODE, 0, 0, 0, 0, 0x10, 0x10, 0x11, 0x11}, // buffer doesn't contain hash size, left 14 | 15 | []byte{24, 0, leafNODE, 0, 0, 0, 0x88, 0x88, 0x88, 0x88, 0x88, 0x8}, // more than 4 billion findex left node 16 | []byte{24, 0, leafNODE, 0, 0, 0, 0x10, 0x88, 0x88, 0x88, 0x88, 0x88, 0x8}, // more than 4 billion fpos left node 17 | []byte{24, 0, leafNODE, 0, 0, 0, 0x10, 0x10, 0x11, 0x11}, // buffer doesn't contain hash size 18 | []byte{24, 0, 3, 0, 0, 0, 0x10, 0x10, 0x11, 0x11}, // unknown node type 19 | 20 | } 21 | var in inner 22 | for _, buf := range buffs { 23 | err := in.Unmarshal(buf) 24 | require.Error(t, err) 25 | } 26 | } 27 | 28 | func TestIsOnlyChildleafPanic(t *testing.T) { 29 | defer func() { 30 | if r := recover(); r == nil { 31 | t.Errorf("The code did not panic") 32 | } 33 | }() 34 | 35 | if n, ok := isOnlyChildleaf(nil); n != nil || ok != false { // result should be nil, false 36 | t.Errorf("isOnlyChildleaf failed for nil") 37 | } 38 | 39 | if n, ok := isOnlyChildleaf(&leaf{}); n != nil || ok != false { // result should be nil, false 40 | t.Errorf("isOnlyChildleaf failed for leaf") 41 | } 42 | 43 | isOnlyChildleaf(&dummynode{}) // it will panic and thus successfully complete the test 44 | } 45 | 46 | func TestLoadinnerfromstore(t *testing.T) { 47 | store, err := NewMemStore() 48 | //store,err := NewDiskStore("/tmp/test") 49 | require.NoError(t, err) 50 | 51 | var in inner 52 | require.Error(t, in.loadinnerfromstore(store)) 53 | 54 | //in.fpos = 10000 55 | //require.Error(t, in.loadinnerfromstore(store)) // invalid position 56 | 57 | in.findex = 1000000 58 | require.Error(t, in.loadinnerfromstore(store)) // invalid findex 59 | 60 | in.loaded_partial = true 61 | if hash, _ := in.Hash(store); hash != nil { // invalid findex for hash 62 | t.Fatalf("Hash inner node loading failed") 63 | } 64 | 65 | _, err = in.Get(store, sum([]byte("dummykey"))) // trigger load error for Get 66 | require.Error(t, err) 67 | 68 | var l leaf 69 | err = in.Insert(store, &l) // trigger load error for Insert 70 | require.Error(t, err) 71 | 72 | //var p Proof 73 | //err = in.Prove(store, sum([]byte("dummykey")), &p) // trigger load error for Prove 74 | //require.Error(t, err) 75 | 76 | _, _, err = in.Delete(store, sum([]byte("dummykey"))) // trigger load error for Delete 77 | require.Error(t, err) 78 | 79 | { // n level deep Delete errors are simulated here 80 | var in, inlevel1 inner 81 | in.loaded_partial = false 82 | inlevel1.loaded_partial = true 83 | in.left = &inlevel1 84 | in.findex = 0 85 | _, _, err = in.Delete(store, [HASHSIZE]byte{0}) // trigger load error for Delete 86 | require.Error(t, err) 87 | 88 | in.right = &inlevel1 89 | _, _, err = in.Delete(store, [HASHSIZE]byte{0x80}) // trigger load error for Delete 90 | require.Error(t, err) 91 | } 92 | 93 | { // n level deep insert errors are simulated here 94 | var in inner 95 | l := &leaf{loaded_partial: true, keyhash: [HASHSIZE]byte{0x00, 1, 3}} 96 | l2 := &leaf{loaded_partial: true, keyhash: [HASHSIZE]byte{0x00, 1, 3, 4}} 97 | 98 | r := &leaf{loaded_partial: true, keyhash: [HASHSIZE]byte{0x80, 1, 3}} 99 | r2 := &leaf{loaded_partial: true, keyhash: [HASHSIZE]byte{0x80, 1, 3, 4}} 100 | 101 | in.left = l 102 | err = in.Insert(store, l2) // trigger load error for Insert 103 | require.Error(t, err) 104 | 105 | in.right = r 106 | err = in.Insert(store, r2) // trigger load error for right Insert 107 | require.Error(t, err) 108 | 109 | } 110 | 111 | } 112 | 113 | func TestInnerCoverage(t *testing.T) { 114 | _, tree := setupDeterministicTree(t, 0) 115 | value := []byte("testdeadend") 116 | 117 | order := []byte{ 118 | 0x0, //00000000, 119 | 0xc0, //11000000, 120 | 0xd0, //11010000, 121 | 0x8, //10000000, 122 | } 123 | for i := range order { 124 | key := [HASHSIZE]byte{} 125 | key[0] = order[i] 126 | require.NoError(t, tree.putRaw(key, nil, value)) 127 | } 128 | 129 | require.Error(t, tree.Commit()) // actually an error should be reported due to corruption 130 | 131 | } 132 | -------------------------------------------------------------------------------- /node_leaf_test.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import ( 4 | "github.com/stretchr/testify/require" 5 | "testing" 6 | ) 7 | 8 | func TestHashPanic(t *testing.T) { 9 | store, err := NewMemStore() 10 | //store,err := NewDiskStore("/tmp/test") 11 | require.NoError(t, err) 12 | 13 | var l leaf 14 | l.loaded_partial = true 15 | 16 | _, err = l.Hash(store) // it will panic and thus successfully complete the test 17 | require.Error(t, err) 18 | } 19 | 20 | func TestLoadfullleaffromstore(t *testing.T) { 21 | store, err := NewMemStore() 22 | //store,err := NewDiskStore("/tmp/test") 23 | require.NoError(t, err) 24 | 25 | var l leaf 26 | l.loaded_partial = true 27 | 28 | _, err = l.Get(store, sum([]byte("dummykey"))) // trigger load error for Get 29 | require.Error(t, err) 30 | 31 | _, _, err = l.Delete(store, sum([]byte("dummykey"))) // trigger load error for Delete 32 | require.Error(t, err) 33 | 34 | var p Proof 35 | err = l.Prove(store, sum([]byte("dummykey")), &p) // trigger load error for Prove 36 | require.Error(t, err) 37 | 38 | err = l.Put(store, sum([]byte("dummykey")), []byte("dummyvalue")) // trigger load error for Get 39 | require.Error(t, err) 40 | 41 | l.findex = 100000 42 | err = l.loadfullleaffromstore(store) 43 | require.Error(t, err) 44 | 45 | keysizeerror := []byte{0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88} // more than 2^64 46 | l.findex, l.fpos, err = store.write(keysizeerror) 47 | require.NoError(t, err) 48 | err = l.loadfullleaffromstore(store) // loading it will give keysize error 49 | require.Error(t, err) 50 | 51 | valuesizeerror := []byte{0x1, 0x0, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88} // more than 2^64 52 | l.findex, l.fpos, err = store.write(valuesizeerror) 53 | require.NoError(t, err) 54 | err = l.loadfullleaffromstore(store) // loading it will give value size error 55 | require.Error(t, err) 56 | 57 | } 58 | -------------------------------------------------------------------------------- /node_test.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | ) 7 | 8 | // used to test certain code paths, which though can be avoid now but may arise when code is maintained, developed, rewritten over a period of time 9 | type dummynode struct { 10 | dirty bool 11 | } 12 | 13 | func (d *dummynode) Hash(store *Store) ([]byte, error) { 14 | var h [HASHSIZE_BYTES]byte 15 | return h[:], nil 16 | } 17 | 18 | func (d *dummynode) isDirty() bool { 19 | return d.dirty 20 | } 21 | 22 | func (d *dummynode) load_partial(store *Store) error { 23 | return nil 24 | } 25 | 26 | func (d *dummynode) Position() (uint32, uint32) { 27 | return 0, 0 28 | } 29 | 30 | func (d *dummynode) Put(store *Store, keyhash [HASHSIZE]byte, value []byte) error { 31 | return errors.New("not implemented") 32 | } 33 | 34 | func (d *dummynode) Get(store *Store, keyhash [HASHSIZE]byte) ([]byte, error) { 35 | return nil, errors.New("not implemented") 36 | } 37 | 38 | func (d *dummynode) Delete(store *Store, keyhash [HASHSIZE]byte) (bool, bool, error) { 39 | return false, false, errors.New("not implemented") 40 | } 41 | 42 | func (d *dummynode) Prove(store *Store, keyhash [HASHSIZE]byte, proof *Proof) error { 43 | return errors.New("not implemented") 44 | } 45 | 46 | func TestUnknownNodePanic(t *testing.T) { 47 | defer func() { 48 | if r := recover(); r == nil { 49 | t.Errorf("The code did not panic") 50 | } 51 | }() 52 | 53 | var d dummynode 54 | 55 | // The following is the code under test 56 | getNodeType(&d) 57 | } 58 | -------------------------------------------------------------------------------- /proof_test.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | import ( 4 | "math/rand" 5 | "testing" 6 | "time" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestTreeProve(t *testing.T) { 12 | rand.Seed(100) 13 | _, tree := setupDeterministicTree(t, 10) 14 | 15 | key := make([]byte, 20) 16 | value := make([]byte, 10) 17 | rand.Read(key) 18 | rand.Read(value) 19 | require.NoError(t, tree.Put(key, value)) 20 | 21 | proof, err := tree.GenerateProof(key) 22 | require.NoError(t, err) 23 | require.True(t, proof.VerifyMembership(tree.hashSkipError(), key)) 24 | 25 | mproof := proof.Marshal() 26 | var decoded Proof 27 | 28 | decoded.Unmarshal(mproof) 29 | 30 | require.True(t, decoded.VerifyMembership(tree.hashSkipError(), key)) 31 | require.False(t, decoded.VerifyNonMembership(tree.hashSkipError(), key)) 32 | 33 | // value is last 11 bytes 34 | 35 | copy(mproof[len(mproof)-11:], []byte{0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}) 36 | require.Error(t, decoded.Unmarshal(mproof)) 37 | 38 | // test malformed proofs, small buffer give array indexing array 39 | wrong_proof := []byte{1, collision, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88} 40 | require.Error(t, decoded.Unmarshal(wrong_proof)) 41 | 42 | } 43 | 44 | func TestTreeProvePersistent(t *testing.T) { 45 | _, tree := setupDeterministicTree(t, 4) 46 | 47 | var key = make([]byte, 10) 48 | rand.Read(key) 49 | require.NoError(t, tree.Put(key, key)) 50 | 51 | root := tree.hashSkipError() 52 | require.NoError(t, tree.Commit()) 53 | 54 | proof, err := tree.GenerateProof(key) 55 | require.NoError(t, err) 56 | require.True(t, proof.VerifyMembership(tree.hashSkipError(), key)) 57 | 58 | require.Equal(t, key, proof.Value()) 59 | require.True(t, proof.VerifyMembership(root, key)) 60 | 61 | proof.Reset() 62 | 63 | if len(proof.Value()) != 0 { 64 | t.Fatalf("Proof not successfully reset.") 65 | } 66 | } 67 | 68 | // these cannot be generated using exported api 69 | func TestProveCollision(t *testing.T) { 70 | _, tree := setupDeterministicTree(t, 0) 71 | value := []byte("testcollision") 72 | 73 | for i := 0; i < 8; i++ { 74 | key := [HASHSIZE]byte{} 75 | key[0] = 1 << uint(i) 76 | require.NoError(t, tree.putRaw(key, nil, value)) 77 | } 78 | 79 | key := [HASHSIZE]byte{} 80 | key[0] = 0xf0 // this needs to be flipped if if bit prrocessing is switched 81 | require.NoError(t, tree.putRaw(key, nil, value)) 82 | root := tree.hashSkipError() 83 | 84 | //require.NoError(t, tree.Commit()) 85 | 86 | ckey := [HASHSIZE]byte{} 87 | ckey[0] = 0xf8 // this needs to be flipped if if bit prrocessing is switched 88 | proof := NewProof() 89 | require.NoError(t, tree.generateProofRaw(ckey, proof)) 90 | 91 | require.False(t, proof.verifyMembershipRaw(root, key)) 92 | 93 | require.True(t, proof.verifyNonMembershipRaw(root, key)) 94 | 95 | } 96 | 97 | func TestProveDeadend(t *testing.T) { 98 | _, tree := setupDeterministicTree(t, 0) 99 | value := []byte("testdeadend") 100 | 101 | gET_CHECKED = false // disable error checking of values 102 | 103 | defer func() { 104 | gET_CHECKED = true 105 | }() 106 | 107 | order := []byte{ 108 | 0x0, //00000000, 109 | 0xc0, //11000000, 110 | 0xd0, //11010000, 111 | 0x8, //10000000, 112 | } 113 | for i := range order { 114 | key := [HASHSIZE]byte{} 115 | key[0] = order[i] 116 | require.NoError(t, tree.putRaw(key, nil, value)) 117 | } 118 | 119 | key := [HASHSIZE]byte{} 120 | key[0] = 0xE0 //11100000 121 | root := tree.hashSkipError() 122 | 123 | require.NoError(t, tree.Commit()) 124 | 125 | proof := NewProof() 126 | require.NoError(t, tree.generateProofRaw(key, proof)) 127 | 128 | require.False(t, proof.verifyMembershipRaw(root, key)) 129 | require.True(t, proof.verifyNonMembershipRaw(root, key)) 130 | 131 | { 132 | order := []byte{ 133 | 0x0, //00000000, 134 | 0x20, //11000000, 135 | 0xd0, //11010000, 136 | 0x8, //10000000, 137 | } 138 | for i := range order { 139 | key := [HASHSIZE]byte{} 140 | key[0] = order[i] 141 | require.NoError(t, tree.putRaw(key, nil, value)) 142 | } 143 | 144 | key := [HASHSIZE]byte{} 145 | key[0] = 0xE0 //11100000 146 | //root := tree.Hash() 147 | 148 | require.NoError(t, tree.Commit()) 149 | 150 | } 151 | 152 | } 153 | 154 | func TestProofMarshal(t *testing.T) { 155 | _, tree := setupDeterministicTree(t, 1000) 156 | root := tree.hashSkipError() 157 | 158 | key := make([]byte, 20) 159 | for i := 0; i < 10; i++ { 160 | rand.Read(key) 161 | proof, err := tree.GenerateProof(key[:]) 162 | require.NoError(t, err) 163 | 164 | member := proof.VerifyMembership(root, key) 165 | non := proof.VerifyNonMembership(root, key) 166 | 167 | buf := proof.Marshal() 168 | 169 | marshalled := NewProof() 170 | marshalled.Unmarshal(buf) 171 | 172 | require.Equal(t, proof, marshalled) 173 | 174 | require.Equal(t, member, marshalled.VerifyMembership(root, key)) 175 | require.Equal(t, non, marshalled.VerifyNonMembership(root, key)) 176 | 177 | proof.Reset() 178 | } 179 | } 180 | 181 | func TestProveAfterDelete(t *testing.T) { 182 | rand.Seed(time.Now().UnixNano()) 183 | _, tree := setupDeterministicTree(t, 0) 184 | proof := NewProof() 185 | 186 | key1 := make([]byte, 20) 187 | rand.Read(key1) 188 | 189 | require.NoError(t, tree.Put(key1, key1)) 190 | keys := [][]byte{} 191 | for i := 0; i < 7; i++ { 192 | key2 := make([]byte, 20) 193 | rand.Read(key2) 194 | require.NoError(t, tree.Put(key2, key2)) 195 | keys = append(keys, key2) 196 | } 197 | 198 | proof, err := tree.GenerateProof(key1[:]) 199 | require.NoError(t, err) 200 | require.True(t, proof.VerifyMembership(tree.hashSkipError(), key1)) 201 | 202 | for _, key := range keys { 203 | require.NoError(t, tree.Delete(key)) 204 | } 205 | proof.Reset() 206 | proof, err = tree.GenerateProof(key1[:]) 207 | require.NoError(t, err) 208 | require.True(t, proof.VerifyMembership(tree.hashSkipError(), key1)) 209 | } 210 | -------------------------------------------------------------------------------- /special.go: -------------------------------------------------------------------------------- 1 | package graviton 2 | 3 | //import "io" 4 | //import "math" 5 | 6 | import "fmt" 7 | import "bytes" 8 | import "golang.org/x/xerrors" 9 | 10 | // this file contains some functions ( to extend read-only api). these apis are used in the dero blockchain. 11 | 12 | func Sum(key []byte) [HASHSIZE]byte { 13 | return sum(key) 14 | } 15 | 16 | // we have a key and need to get both the key,value 17 | func (t *Tree) GetKeyValueFromKey(key []byte) (int, []byte, []byte, error) { 18 | return t.root.GetKeyValue(t.store, sum(key), 256, 0) 19 | } 20 | 21 | // we only have a keyhash and need to get both the key,value 22 | func (t *Tree) GetKeyValueFromHash(keyhashc []byte) (int, []byte, []byte, error) { 23 | var keyhash [HASHSIZE]byte 24 | if len(keyhashc) <= 0 || len(keyhashc) > HASHSIZE { 25 | return 0, nil, nil, fmt.Errorf("keyhashc must be atleast 1 byte and less than 33 bytes, len=%d", len(keyhashc)) 26 | } 27 | copy(keyhash[:], keyhashc) 28 | 29 | return t.root.GetKeyValue(t.store, keyhash, len(keyhashc)*8, 0) 30 | } 31 | 32 | func (in *inner) GetKeyValue(store *Store, keyhash [HASHSIZE]byte, valid_bit_count, used_bit_count int) (int, []byte, []byte, error) { 33 | if err := in.load_partial(store); err != nil { // if inner node is loaded partially, load it fully now 34 | return used_bit_count, nil, nil, err 35 | } 36 | 37 | if used_bit_count > valid_bit_count || valid_bit_count <= 0 { 38 | return used_bit_count, nil, nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) 39 | } 40 | 41 | if isBitSet(keyhash[:], uint(in.bit)) { 42 | if in.right == nil { 43 | return used_bit_count, nil, nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) 44 | } 45 | switch in.right.(type) { // draw left branch 46 | case *inner: 47 | return in.right.(*inner).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) 48 | case *leaf: 49 | return in.right.(*leaf).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) 50 | default: 51 | panic("unknown node type") 52 | } 53 | 54 | } 55 | if in.left == nil { 56 | return used_bit_count, nil, nil, xerrors.Errorf("%w: left dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) 57 | } 58 | switch in.left.(type) { // draw left branch 59 | case *inner: 60 | return in.left.(*inner).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) 61 | case *leaf: 62 | return in.left.(*leaf).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) 63 | default: 64 | panic("unknown node type") 65 | } 66 | } 67 | 68 | // should we return a copy 69 | func (l *leaf) GetKeyValue(store *Store, keyhash [HASHSIZE]byte, valid_bit_count, used_bit_count int) (int, []byte, []byte, error) { 70 | if l.loaded_partial { // if leaf is loaded partially, load it fully now 71 | if err := l.loadfullleaffromstore(store); err != nil { 72 | return used_bit_count, nil, nil, err 73 | } 74 | } 75 | 76 | if bytes.Compare(l.keyhash[:valid_bit_count/8], keyhash[:valid_bit_count/8]) == 0 { 77 | return used_bit_count, l.key, l.value, nil 78 | } 79 | 80 | return used_bit_count, nil, nil, xerrors.Errorf("%w: collision, keyhash %x not found, inram hash %x, used_bit_count %d", ErrNotFound, keyhash,l.keyhash,used_bit_count) 81 | } 82 | 83 | // sets a root for the cursor, so the cursor visits only a specific prefix keys 84 | func (c *Cursor) SpecialFirst(section []byte, validbits uint) (k, v []byte, err error) { 85 | loop_node := node(c.tree.root) // we always start at root node 86 | 87 | donebits := uint(0) 88 | 89 | if validbits >= 256 { 90 | err = fmt.Errorf("invalid valid bits %d", validbits) 91 | return 92 | } 93 | 94 | if validbits == 0 { 95 | return c.First() 96 | } 97 | 98 | // the function is iterative and not recursive 99 | for { 100 | switch node := loop_node.(type) { 101 | case *inner: 102 | if node.loaded_partial { // if node is loaded partially, load it fully now 103 | if err = node.loadinnerfromstore(c.tree.store); err != nil { 104 | return 105 | } 106 | } 107 | 108 | left, right := node.left, node.right 109 | if isBitSet(section, donebits) { // 1 is right 110 | if right == nil { 111 | err = ErrNoMoreKeys 112 | return 113 | } 114 | loop_node = right 115 | } else { //0 is left 116 | if left == nil { 117 | err = ErrNoMoreKeys 118 | return 119 | } 120 | loop_node = left 121 | } 122 | donebits++ 123 | 124 | if donebits < validbits { 125 | continue 126 | } else if donebits == validbits { 127 | return c.next_internal(loop_node, false) 128 | } 129 | 130 | // we can only reach here if a tree has both left,right nil, ie an empty tree 131 | err = ErrNoMoreKeys 132 | return 133 | 134 | case *leaf: 135 | err = ErrNoMoreKeys 136 | return 137 | default: 138 | return k, v, fmt.Errorf("unknown node type, corruption") 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | .DS_Store 25 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/.travis.gofmt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -n "$(gofmt -l .)" ]; then 4 | echo "Go code is not formatted:" 5 | gofmt -d . 6 | exit 1 7 | fi 8 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/.travis.gogenerate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ "$TRAVIS_GO_VERSION" =~ ^1\.[45](\..*)?$ ]]; then 4 | exit 0 5 | fi 6 | 7 | go get github.com/ernesto-jimenez/gogen/imports 8 | go generate ./... 9 | if [ -n "$(git diff)" ]; then 10 | echo "Go generate had not been run" 11 | git diff 12 | exit 1 13 | fi 14 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/.travis.govet.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd "$(dirname $0)" 4 | DIRS=". assert require mock _codegen" 5 | set -e 6 | for subdir in $DIRS; do 7 | pushd $subdir 8 | go vet 9 | popd 10 | done 11 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | sudo: false 4 | 5 | matrix: 6 | include: 7 | - go: "1.8.x" 8 | - go: "1.9.x" 9 | - go: "1.10.x" 10 | - go: "1.11.x" 11 | env: GO111MODULE=off 12 | - go: "1.11.x" 13 | env: GO111MODULE=on 14 | - go: tip 15 | script: 16 | - ./.travis.gogenerate.sh 17 | - ./.travis.gofmt.sh 18 | - ./.travis.govet.sh 19 | - go test -v -race $(go list ./... | grep -v vendor) 20 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/davecgh/go-spew" 6 | packages = ["spew"] 7 | revision = "346938d642f2ec3594ed81d874461961cd0faa76" 8 | version = "v1.1.0" 9 | 10 | [[projects]] 11 | name = "github.com/pmezard/go-difflib" 12 | packages = ["difflib"] 13 | revision = "792786c7400a136282c1664665ae0a8db921c6c2" 14 | version = "v1.0.0" 15 | 16 | [[projects]] 17 | name = "github.com/stretchr/objx" 18 | packages = ["."] 19 | revision = "facf9a85c22f48d2f52f2380e4efce1768749a89" 20 | version = "v0.1" 21 | 22 | [solve-meta] 23 | analyzer-name = "dep" 24 | analyzer-version = 1 25 | inputs-digest = "448ddae4702c6aded2555faafd390c537789bb1c483f70b0431e6634f73f2090" 26 | solver-name = "gps-cdcl" 27 | solver-version = 1 28 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/Gopkg.toml: -------------------------------------------------------------------------------- 1 | [prune] 2 | unused-packages = true 3 | non-go = true 4 | go-tests = true 5 | 6 | [[constraint]] 7 | name = "github.com/davecgh/go-spew" 8 | version = "~1.1.0" 9 | 10 | [[constraint]] 11 | name = "github.com/pmezard/go-difflib" 12 | version = "~1.0.0" 13 | 14 | [[constraint]] 15 | name = "github.com/stretchr/objx" 16 | version = "~0.1.0" 17 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2012-2018 Mat Ryer and Tyler Bunnell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl: -------------------------------------------------------------------------------- 1 | {{.CommentFormat}} 2 | func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { 3 | if h, ok := t.(tHelper); ok { h.Helper() } 4 | return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) 5 | } 6 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl: -------------------------------------------------------------------------------- 1 | {{.CommentWithoutT "a"}} 2 | func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { 3 | if h, ok := a.t.(tHelper); ok { h.Helper() } 4 | return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) 5 | } 6 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/assertion_order_test.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestCompare(t *testing.T) { 9 | for _, currCase := range []struct { 10 | less interface{} 11 | greater interface{} 12 | cType string 13 | }{ 14 | {less: "a", greater: "b", cType: "string"}, 15 | {less: int(1), greater: int(2), cType: "int"}, 16 | {less: int8(1), greater: int8(2), cType: "int8"}, 17 | {less: int16(1), greater: int16(2), cType: "int16"}, 18 | {less: int32(1), greater: int32(2), cType: "int32"}, 19 | {less: int64(1), greater: int64(2), cType: "int64"}, 20 | {less: uint8(1), greater: uint8(2), cType: "uint8"}, 21 | {less: uint16(1), greater: uint16(2), cType: "uint16"}, 22 | {less: uint32(1), greater: uint32(2), cType: "uint32"}, 23 | {less: uint64(1), greater: uint64(2), cType: "uint64"}, 24 | {less: float32(1), greater: float32(2), cType: "float32"}, 25 | {less: float64(1), greater: float64(2), cType: "float64"}, 26 | } { 27 | resLess, isComparable := compare(currCase.less, currCase.greater, reflect.ValueOf(currCase.less).Kind()) 28 | if !isComparable { 29 | t.Error("object should be comparable for type " + currCase.cType) 30 | } 31 | 32 | if resLess != 1 { 33 | t.Errorf("object less should be less than greater for type " + currCase.cType) 34 | } 35 | 36 | resGreater, isComparable := compare(currCase.greater, currCase.less, reflect.ValueOf(currCase.less).Kind()) 37 | if !isComparable { 38 | t.Error("object are comparable for type " + currCase.cType) 39 | } 40 | 41 | if resGreater != -1 { 42 | t.Errorf("object greater should be greater than less for type " + currCase.cType) 43 | } 44 | 45 | resEqual, isComparable := compare(currCase.less, currCase.less, reflect.ValueOf(currCase.less).Kind()) 46 | if !isComparable { 47 | t.Error("object are comparable for type " + currCase.cType) 48 | } 49 | 50 | if resEqual != 0 { 51 | t.Errorf("objects should be equal for type " + currCase.cType) 52 | } 53 | } 54 | } 55 | 56 | func TestGreater(t *testing.T) { 57 | mockT := new(testing.T) 58 | 59 | if !Greater(mockT, 2, 1) { 60 | t.Error("Greater should return true") 61 | } 62 | 63 | if Greater(mockT, 1, 1) { 64 | t.Error("Greater should return false") 65 | } 66 | 67 | if Greater(mockT, 1, 2) { 68 | t.Error("Greater should return false") 69 | } 70 | } 71 | 72 | func TestGreaterOrEqual(t *testing.T) { 73 | mockT := new(testing.T) 74 | 75 | if !GreaterOrEqual(mockT, 2, 1) { 76 | t.Error("Greater should return true") 77 | } 78 | 79 | if !GreaterOrEqual(mockT, 1, 1) { 80 | t.Error("Greater should return true") 81 | } 82 | 83 | if GreaterOrEqual(mockT, 1, 2) { 84 | t.Error("Greater should return false") 85 | } 86 | } 87 | 88 | func TestLess(t *testing.T) { 89 | mockT := new(testing.T) 90 | 91 | if !Less(mockT, 1, 2) { 92 | t.Error("Less should return true") 93 | } 94 | 95 | if Less(mockT, 1, 1) { 96 | t.Error("Less should return false") 97 | } 98 | 99 | if Less(mockT, 2, 1) { 100 | t.Error("Less should return false") 101 | } 102 | } 103 | 104 | func TestLessOrEqual(t *testing.T) { 105 | mockT := new(testing.T) 106 | 107 | if !LessOrEqual(mockT, 1, 2) { 108 | t.Error("Greater should return true") 109 | } 110 | 111 | if !LessOrEqual(mockT, 1, 1) { 112 | t.Error("Greater should return true") 113 | } 114 | 115 | if LessOrEqual(mockT, 2, 1) { 116 | t.Error("Greater should return false") 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/doc.go: -------------------------------------------------------------------------------- 1 | // Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. 2 | // 3 | // Example Usage 4 | // 5 | // The following is a complete example using assert in a standard test function: 6 | // import ( 7 | // "testing" 8 | // "github.com/stretchr/testify/assert" 9 | // ) 10 | // 11 | // func TestSomething(t *testing.T) { 12 | // 13 | // var a string = "Hello" 14 | // var b string = "Hello" 15 | // 16 | // assert.Equal(t, a, b, "The two words should be the same.") 17 | // 18 | // } 19 | // 20 | // if you assert many times, use the format below: 21 | // 22 | // import ( 23 | // "testing" 24 | // "github.com/stretchr/testify/assert" 25 | // ) 26 | // 27 | // func TestSomething(t *testing.T) { 28 | // assert := assert.New(t) 29 | // 30 | // var a string = "Hello" 31 | // var b string = "Hello" 32 | // 33 | // assert.Equal(a, b, "The two words should be the same.") 34 | // } 35 | // 36 | // Assertions 37 | // 38 | // Assertions allow you to easily write test code, and are global funcs in the `assert` package. 39 | // All assertion functions take, as the first argument, the `*testing.T` object provided by the 40 | // testing framework. This allows the assertion funcs to write the failings and other details to 41 | // the correct place. 42 | // 43 | // Every assertion function also takes an optional string message as the final argument, 44 | // allowing custom error messages to be appended to the message the assertion method outputs. 45 | package assert 46 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/errors.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // AnError is an error instance useful for testing. If the code does not care 8 | // about error specifics, and only needs to return the error for example, this 9 | // error should be used to make the test code more readable. 10 | var AnError = errors.New("assert.AnError general error for testing") 11 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/forward_assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | // Assertions provides assertion methods around the 4 | // TestingT interface. 5 | type Assertions struct { 6 | t TestingT 7 | } 8 | 9 | // New makes a new Assertions object for the specified TestingT. 10 | func New(t TestingT) *Assertions { 11 | return &Assertions{ 12 | t: t, 13 | } 14 | } 15 | 16 | //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs 17 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/http_assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httptest" 7 | "net/url" 8 | "strings" 9 | ) 10 | 11 | // httpCode is a helper that returns HTTP code of the response. It returns -1 and 12 | // an error if building a new request fails. 13 | func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { 14 | w := httptest.NewRecorder() 15 | req, err := http.NewRequest(method, url, nil) 16 | if err != nil { 17 | return -1, err 18 | } 19 | req.URL.RawQuery = values.Encode() 20 | handler(w, req) 21 | return w.Code, nil 22 | } 23 | 24 | // HTTPSuccess asserts that a specified handler returns a success status code. 25 | // 26 | // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) 27 | // 28 | // Returns whether the assertion was successful (true) or not (false). 29 | func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { 30 | if h, ok := t.(tHelper); ok { 31 | h.Helper() 32 | } 33 | code, err := httpCode(handler, method, url, values) 34 | if err != nil { 35 | Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) 36 | return false 37 | } 38 | 39 | isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent 40 | if !isSuccessCode { 41 | Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) 42 | } 43 | 44 | return isSuccessCode 45 | } 46 | 47 | // HTTPRedirect asserts that a specified handler returns a redirect status code. 48 | // 49 | // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} 50 | // 51 | // Returns whether the assertion was successful (true) or not (false). 52 | func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { 53 | if h, ok := t.(tHelper); ok { 54 | h.Helper() 55 | } 56 | code, err := httpCode(handler, method, url, values) 57 | if err != nil { 58 | Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) 59 | return false 60 | } 61 | 62 | isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect 63 | if !isRedirectCode { 64 | Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) 65 | } 66 | 67 | return isRedirectCode 68 | } 69 | 70 | // HTTPError asserts that a specified handler returns an error status code. 71 | // 72 | // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} 73 | // 74 | // Returns whether the assertion was successful (true) or not (false). 75 | func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { 76 | if h, ok := t.(tHelper); ok { 77 | h.Helper() 78 | } 79 | code, err := httpCode(handler, method, url, values) 80 | if err != nil { 81 | Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) 82 | return false 83 | } 84 | 85 | isErrorCode := code >= http.StatusBadRequest 86 | if !isErrorCode { 87 | Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) 88 | } 89 | 90 | return isErrorCode 91 | } 92 | 93 | // HTTPBody is a helper that returns HTTP body of the response. It returns 94 | // empty string if building a new request fails. 95 | func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { 96 | w := httptest.NewRecorder() 97 | req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) 98 | if err != nil { 99 | return "" 100 | } 101 | handler(w, req) 102 | return w.Body.String() 103 | } 104 | 105 | // HTTPBodyContains asserts that a specified handler returns a 106 | // body that contains a string. 107 | // 108 | // assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") 109 | // 110 | // Returns whether the assertion was successful (true) or not (false). 111 | func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { 112 | if h, ok := t.(tHelper); ok { 113 | h.Helper() 114 | } 115 | body := HTTPBody(handler, method, url, values) 116 | 117 | contains := strings.Contains(body, fmt.Sprint(str)) 118 | if !contains { 119 | Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) 120 | } 121 | 122 | return contains 123 | } 124 | 125 | // HTTPBodyNotContains asserts that a specified handler returns a 126 | // body that does not contain a string. 127 | // 128 | // assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") 129 | // 130 | // Returns whether the assertion was successful (true) or not (false). 131 | func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { 132 | if h, ok := t.(tHelper); ok { 133 | h.Helper() 134 | } 135 | body := HTTPBody(handler, method, url, values) 136 | 137 | contains := strings.Contains(body, fmt.Sprint(str)) 138 | if contains { 139 | Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) 140 | } 141 | 142 | return !contains 143 | } 144 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/assert/http_assertions_test.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "testing" 8 | ) 9 | 10 | func httpOK(w http.ResponseWriter, r *http.Request) { 11 | w.WriteHeader(http.StatusOK) 12 | } 13 | 14 | func httpRedirect(w http.ResponseWriter, r *http.Request) { 15 | w.WriteHeader(http.StatusTemporaryRedirect) 16 | } 17 | 18 | func httpError(w http.ResponseWriter, r *http.Request) { 19 | w.WriteHeader(http.StatusInternalServerError) 20 | } 21 | 22 | func TestHTTPSuccess(t *testing.T) { 23 | assert := New(t) 24 | 25 | mockT1 := new(testing.T) 26 | assert.Equal(HTTPSuccess(mockT1, httpOK, "GET", "/", nil), true) 27 | assert.False(mockT1.Failed()) 28 | 29 | mockT2 := new(testing.T) 30 | assert.Equal(HTTPSuccess(mockT2, httpRedirect, "GET", "/", nil), false) 31 | assert.True(mockT2.Failed()) 32 | 33 | mockT3 := new(testing.T) 34 | assert.Equal(HTTPSuccess(mockT3, httpError, "GET", "/", nil), false) 35 | assert.True(mockT3.Failed()) 36 | } 37 | 38 | func TestHTTPRedirect(t *testing.T) { 39 | assert := New(t) 40 | 41 | mockT1 := new(testing.T) 42 | assert.Equal(HTTPRedirect(mockT1, httpOK, "GET", "/", nil), false) 43 | assert.True(mockT1.Failed()) 44 | 45 | mockT2 := new(testing.T) 46 | assert.Equal(HTTPRedirect(mockT2, httpRedirect, "GET", "/", nil), true) 47 | assert.False(mockT2.Failed()) 48 | 49 | mockT3 := new(testing.T) 50 | assert.Equal(HTTPRedirect(mockT3, httpError, "GET", "/", nil), false) 51 | assert.True(mockT3.Failed()) 52 | } 53 | 54 | func TestHTTPError(t *testing.T) { 55 | assert := New(t) 56 | 57 | mockT1 := new(testing.T) 58 | assert.Equal(HTTPError(mockT1, httpOK, "GET", "/", nil), false) 59 | assert.True(mockT1.Failed()) 60 | 61 | mockT2 := new(testing.T) 62 | assert.Equal(HTTPError(mockT2, httpRedirect, "GET", "/", nil), false) 63 | assert.True(mockT2.Failed()) 64 | 65 | mockT3 := new(testing.T) 66 | assert.Equal(HTTPError(mockT3, httpError, "GET", "/", nil), true) 67 | assert.False(mockT3.Failed()) 68 | } 69 | 70 | func TestHTTPStatusesWrapper(t *testing.T) { 71 | assert := New(t) 72 | mockAssert := New(new(testing.T)) 73 | 74 | assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) 75 | assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) 76 | assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) 77 | 78 | assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) 79 | assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) 80 | assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) 81 | 82 | assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) 83 | assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) 84 | assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) 85 | } 86 | 87 | func httpHelloName(w http.ResponseWriter, r *http.Request) { 88 | name := r.FormValue("name") 89 | w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) 90 | } 91 | 92 | func TestHTTPRequestWithNoParams(t *testing.T) { 93 | var got *http.Request 94 | handler := func(w http.ResponseWriter, r *http.Request) { 95 | got = r 96 | w.WriteHeader(http.StatusOK) 97 | } 98 | 99 | True(t, HTTPSuccess(t, handler, "GET", "/url", nil)) 100 | 101 | Empty(t, got.URL.Query()) 102 | Equal(t, "/url", got.URL.RequestURI()) 103 | } 104 | 105 | func TestHTTPRequestWithParams(t *testing.T) { 106 | var got *http.Request 107 | handler := func(w http.ResponseWriter, r *http.Request) { 108 | got = r 109 | w.WriteHeader(http.StatusOK) 110 | } 111 | params := url.Values{} 112 | params.Add("id", "12345") 113 | 114 | True(t, HTTPSuccess(t, handler, "GET", "/url", params)) 115 | 116 | Equal(t, url.Values{"id": []string{"12345"}}, got.URL.Query()) 117 | Equal(t, "/url?id=12345", got.URL.String()) 118 | Equal(t, "/url?id=12345", got.URL.RequestURI()) 119 | } 120 | 121 | func TestHttpBody(t *testing.T) { 122 | assert := New(t) 123 | mockT := new(testing.T) 124 | 125 | assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 126 | assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 127 | assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 128 | 129 | assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 130 | assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 131 | assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 132 | } 133 | 134 | func TestHttpBodyWrappers(t *testing.T) { 135 | assert := New(t) 136 | mockAssert := New(new(testing.T)) 137 | 138 | assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 139 | assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 140 | assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 141 | 142 | assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 143 | assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 144 | assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 145 | 146 | } 147 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/doc.go: -------------------------------------------------------------------------------- 1 | // Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. 2 | // 3 | // testify contains the following packages: 4 | // 5 | // The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. 6 | // 7 | // The http package contains tools to make it easier to test http activity using the Go testing system. 8 | // 9 | // The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. 10 | // 11 | // The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces. 12 | package testify 13 | 14 | // blank imports help docs. 15 | import ( 16 | // assert package 17 | _ "github.com/stretchr/testify/assert" 18 | // http package 19 | _ "github.com/stretchr/testify/http" 20 | // mock package 21 | _ "github.com/stretchr/testify/mock" 22 | ) 23 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/stretchr/testify 2 | 3 | require ( 4 | github.com/davecgh/go-spew v1.1.0 5 | github.com/pmezard/go-difflib v1.0.0 6 | github.com/stretchr/objx v0.1.0 7 | gopkg.in/yaml.v2 v2.2.2 8 | ) 9 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= 6 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 8 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 9 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 10 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/http/doc.go: -------------------------------------------------------------------------------- 1 | // Package http DEPRECATED USE net/http/httptest 2 | package http 3 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/http/test_response_writer.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | // TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. 8 | type TestResponseWriter struct { 9 | 10 | // StatusCode is the last int written by the call to WriteHeader(int) 11 | StatusCode int 12 | 13 | // Output is a string containing the written bytes using the Write([]byte) func. 14 | Output string 15 | 16 | // header is the internal storage of the http.Header object 17 | header http.Header 18 | } 19 | 20 | // Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. 21 | func (rw *TestResponseWriter) Header() http.Header { 22 | 23 | if rw.header == nil { 24 | rw.header = make(http.Header) 25 | } 26 | 27 | return rw.header 28 | } 29 | 30 | // Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. 31 | func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { 32 | 33 | // assume 200 success if no header has been set 34 | if rw.StatusCode == 0 { 35 | rw.WriteHeader(200) 36 | } 37 | 38 | // add these bytes to the output string 39 | rw.Output = rw.Output + string(bytes) 40 | 41 | // return normal values 42 | return 0, nil 43 | 44 | } 45 | 46 | // WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. 47 | func (rw *TestResponseWriter) WriteHeader(i int) { 48 | rw.StatusCode = i 49 | } 50 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/http/test_round_tripper.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | "github.com/stretchr/testify/mock" 5 | "net/http" 6 | ) 7 | 8 | // TestRoundTripper DEPRECATED USE net/http/httptest 9 | type TestRoundTripper struct { 10 | mock.Mock 11 | } 12 | 13 | // RoundTrip DEPRECATED USE net/http/httptest 14 | func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 15 | args := t.Called(req) 16 | return args.Get(0).(*http.Response), args.Error(1) 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/mock/doc.go: -------------------------------------------------------------------------------- 1 | // Package mock provides a system by which it is possible to mock your objects 2 | // and verify calls are happening as expected. 3 | // 4 | // Example Usage 5 | // 6 | // The mock package provides an object, Mock, that tracks activity on another object. It is usually 7 | // embedded into a test object as shown below: 8 | // 9 | // type MyTestObject struct { 10 | // // add a Mock object instance 11 | // mock.Mock 12 | // 13 | // // other fields go here as normal 14 | // } 15 | // 16 | // When implementing the methods of an interface, you wire your functions up 17 | // to call the Mock.Called(args...) method, and return the appropriate values. 18 | // 19 | // For example, to mock a method that saves the name and age of a person and returns 20 | // the year of their birth or an error, you might write this: 21 | // 22 | // func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { 23 | // args := o.Called(firstname, lastname, age) 24 | // return args.Int(0), args.Error(1) 25 | // } 26 | // 27 | // The Int, Error and Bool methods are examples of strongly typed getters that take the argument 28 | // index position. Given this argument list: 29 | // 30 | // (12, true, "Something") 31 | // 32 | // You could read them out strongly typed like this: 33 | // 34 | // args.Int(0) 35 | // args.Bool(1) 36 | // args.String(2) 37 | // 38 | // For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: 39 | // 40 | // return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) 41 | // 42 | // This may cause a panic if the object you are getting is nil (the type assertion will fail), in those 43 | // cases you should check for nil first. 44 | package mock 45 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/package_test.go: -------------------------------------------------------------------------------- 1 | package testify 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestImports(t *testing.T) { 9 | if assert.Equal(t, 1, 1) != true { 10 | t.Error("Something is wrong.") 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/require/doc.go: -------------------------------------------------------------------------------- 1 | // Package require implements the same assertions as the `assert` package but 2 | // stops test execution when a test fails. 3 | // 4 | // Example Usage 5 | // 6 | // The following is a complete example using require in a standard test function: 7 | // import ( 8 | // "testing" 9 | // "github.com/stretchr/testify/require" 10 | // ) 11 | // 12 | // func TestSomething(t *testing.T) { 13 | // 14 | // var a string = "Hello" 15 | // var b string = "Hello" 16 | // 17 | // require.Equal(t, a, b, "The two words should be the same.") 18 | // 19 | // } 20 | // 21 | // Assertions 22 | // 23 | // The `require` package have same global functions as in the `assert` package, 24 | // but instead of returning a boolean result they call `t.FailNow()`. 25 | // 26 | // Every assertion function also takes an optional string message as the final argument, 27 | // allowing custom error messages to be appended to the message the assertion method outputs. 28 | package require 29 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/require/forward_requirements.go: -------------------------------------------------------------------------------- 1 | package require 2 | 3 | // Assertions provides assertion methods around the 4 | // TestingT interface. 5 | type Assertions struct { 6 | t TestingT 7 | } 8 | 9 | // New makes a new Assertions object for the specified TestingT. 10 | func New(t TestingT) *Assertions { 11 | return &Assertions{ 12 | t: t, 13 | } 14 | } 15 | 16 | //go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs 17 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/require/require.go.tmpl: -------------------------------------------------------------------------------- 1 | {{.Comment}} 2 | func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { 3 | if h, ok := t.(tHelper); ok { h.Helper() } 4 | if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return } 5 | t.FailNow() 6 | } 7 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/require/require_forward.go.tmpl: -------------------------------------------------------------------------------- 1 | {{.CommentWithoutT "a"}} 2 | func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { 3 | if h, ok := a.t.(tHelper); ok { h.Helper() } 4 | {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) 5 | } 6 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/require/requirements.go: -------------------------------------------------------------------------------- 1 | package require 2 | 3 | // TestingT is an interface wrapper around *testing.T 4 | type TestingT interface { 5 | Errorf(format string, args ...interface{}) 6 | FailNow() 7 | } 8 | 9 | type tHelper interface { 10 | Helper() 11 | } 12 | 13 | // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful 14 | // for table driven tests. 15 | type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) 16 | 17 | // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful 18 | // for table driven tests. 19 | type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) 20 | 21 | // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful 22 | // for table driven tests. 23 | type BoolAssertionFunc func(TestingT, bool, ...interface{}) 24 | 25 | // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful 26 | // for table driven tests. 27 | type ErrorAssertionFunc func(TestingT, error, ...interface{}) 28 | 29 | //go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs 30 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/suite/doc.go: -------------------------------------------------------------------------------- 1 | // Package suite contains logic for creating testing suite structs 2 | // and running the methods on those structs as tests. The most useful 3 | // piece of this package is that you can create setup/teardown methods 4 | // on your testing suites, which will run before/after the whole suite 5 | // or individual tests (depending on which interface(s) you 6 | // implement). 7 | // 8 | // A testing suite is usually built by first extending the built-in 9 | // suite functionality from suite.Suite in testify. Alternatively, 10 | // you could reproduce that logic on your own if you wanted (you 11 | // just need to implement the TestingSuite interface from 12 | // suite/interfaces.go). 13 | // 14 | // After that, you can implement any of the interfaces in 15 | // suite/interfaces.go to add setup/teardown functionality to your 16 | // suite, and add any methods that start with "Test" to add tests. 17 | // Methods that do not match any suite interfaces and do not begin 18 | // with "Test" will not be run by testify, and can safely be used as 19 | // helper methods. 20 | // 21 | // Once you've built your testing suite, you need to run the suite 22 | // (using suite.Run from testify) inside any function that matches the 23 | // identity that "go test" is already looking for (i.e. 24 | // func(*testing.T)). 25 | // 26 | // Regular expression to select test suites specified command-line 27 | // argument "-run". Regular expression to select the methods 28 | // of test suites specified command-line argument "-m". 29 | // Suite object has assertion methods. 30 | // 31 | // A crude example: 32 | // // Basic imports 33 | // import ( 34 | // "testing" 35 | // "github.com/stretchr/testify/assert" 36 | // "github.com/stretchr/testify/suite" 37 | // ) 38 | // 39 | // // Define the suite, and absorb the built-in basic suite 40 | // // functionality from testify - including a T() method which 41 | // // returns the current testing context 42 | // type ExampleTestSuite struct { 43 | // suite.Suite 44 | // VariableThatShouldStartAtFive int 45 | // } 46 | // 47 | // // Make sure that VariableThatShouldStartAtFive is set to five 48 | // // before each test 49 | // func (suite *ExampleTestSuite) SetupTest() { 50 | // suite.VariableThatShouldStartAtFive = 5 51 | // } 52 | // 53 | // // All methods that begin with "Test" are run as tests within a 54 | // // suite. 55 | // func (suite *ExampleTestSuite) TestExample() { 56 | // assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) 57 | // suite.Equal(5, suite.VariableThatShouldStartAtFive) 58 | // } 59 | // 60 | // // In order for 'go test' to run this suite, we need to create 61 | // // a normal test function and pass our suite to suite.Run 62 | // func TestExampleTestSuite(t *testing.T) { 63 | // suite.Run(t, new(ExampleTestSuite)) 64 | // } 65 | package suite 66 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/suite/interfaces.go: -------------------------------------------------------------------------------- 1 | package suite 2 | 3 | import "testing" 4 | 5 | // TestingSuite can store and return the current *testing.T context 6 | // generated by 'go test'. 7 | type TestingSuite interface { 8 | T() *testing.T 9 | SetT(*testing.T) 10 | } 11 | 12 | // SetupAllSuite has a SetupSuite method, which will run before the 13 | // tests in the suite are run. 14 | type SetupAllSuite interface { 15 | SetupSuite() 16 | } 17 | 18 | // SetupTestSuite has a SetupTest method, which will run before each 19 | // test in the suite. 20 | type SetupTestSuite interface { 21 | SetupTest() 22 | } 23 | 24 | // TearDownAllSuite has a TearDownSuite method, which will run after 25 | // all the tests in the suite have been run. 26 | type TearDownAllSuite interface { 27 | TearDownSuite() 28 | } 29 | 30 | // TearDownTestSuite has a TearDownTest method, which will run after 31 | // each test in the suite. 32 | type TearDownTestSuite interface { 33 | TearDownTest() 34 | } 35 | 36 | // BeforeTest has a function to be executed right before the test 37 | // starts and receives the suite and test names as input 38 | type BeforeTest interface { 39 | BeforeTest(suiteName, testName string) 40 | } 41 | 42 | // AfterTest has a function to be executed right after the test 43 | // finishes and receives the suite and test names as input 44 | type AfterTest interface { 45 | AfterTest(suiteName, testName string) 46 | } 47 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/suite/suite.go: -------------------------------------------------------------------------------- 1 | package suite 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "reflect" 8 | "regexp" 9 | "runtime/debug" 10 | "testing" 11 | 12 | "github.com/stretchr/testify/assert" 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } 17 | var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") 18 | 19 | // Suite is a basic testing suite with methods for storing and 20 | // retrieving the current *testing.T context. 21 | type Suite struct { 22 | *assert.Assertions 23 | require *require.Assertions 24 | t *testing.T 25 | } 26 | 27 | // T retrieves the current *testing.T context. 28 | func (suite *Suite) T() *testing.T { 29 | return suite.t 30 | } 31 | 32 | // SetT sets the current *testing.T context. 33 | func (suite *Suite) SetT(t *testing.T) { 34 | suite.t = t 35 | suite.Assertions = assert.New(t) 36 | suite.require = require.New(t) 37 | } 38 | 39 | // Require returns a require context for suite. 40 | func (suite *Suite) Require() *require.Assertions { 41 | if suite.require == nil { 42 | suite.require = require.New(suite.T()) 43 | } 44 | return suite.require 45 | } 46 | 47 | // Assert returns an assert context for suite. Normally, you can call 48 | // `suite.NoError(expected, actual)`, but for situations where the embedded 49 | // methods are overridden (for example, you might want to override 50 | // assert.Assertions with require.Assertions), this method is provided so you 51 | // can call `suite.Assert().NoError()`. 52 | func (suite *Suite) Assert() *assert.Assertions { 53 | if suite.Assertions == nil { 54 | suite.Assertions = assert.New(suite.T()) 55 | } 56 | return suite.Assertions 57 | } 58 | 59 | func failOnPanic(t *testing.T) { 60 | r := recover() 61 | if r != nil { 62 | t.Errorf("test panicked: %v\n%s", r, debug.Stack()) 63 | t.FailNow() 64 | } 65 | } 66 | 67 | // Run provides suite functionality around golang subtests. It should be 68 | // called in place of t.Run(name, func(t *testing.T)) in test suite code. 69 | // The passed-in func will be executed as a subtest with a fresh instance of t. 70 | // Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. 71 | func (suite *Suite) Run(name string, subtest func()) bool { 72 | oldT := suite.T() 73 | defer suite.SetT(oldT) 74 | return oldT.Run(name, func(t *testing.T) { 75 | suite.SetT(t) 76 | subtest() 77 | }) 78 | } 79 | 80 | // Run takes a testing suite and runs all of the tests attached 81 | // to it. 82 | func Run(t *testing.T, suite TestingSuite) { 83 | suite.SetT(t) 84 | defer failOnPanic(t) 85 | 86 | suiteSetupDone := false 87 | 88 | methodFinder := reflect.TypeOf(suite) 89 | tests := []testing.InternalTest{} 90 | for index := 0; index < methodFinder.NumMethod(); index++ { 91 | method := methodFinder.Method(index) 92 | ok, err := methodFilter(method.Name) 93 | if err != nil { 94 | fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) 95 | os.Exit(1) 96 | } 97 | if !ok { 98 | continue 99 | } 100 | if !suiteSetupDone { 101 | if setupAllSuite, ok := suite.(SetupAllSuite); ok { 102 | setupAllSuite.SetupSuite() 103 | } 104 | defer func() { 105 | if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { 106 | tearDownAllSuite.TearDownSuite() 107 | } 108 | }() 109 | suiteSetupDone = true 110 | } 111 | test := testing.InternalTest{ 112 | Name: method.Name, 113 | F: func(t *testing.T) { 114 | parentT := suite.T() 115 | suite.SetT(t) 116 | defer failOnPanic(t) 117 | 118 | if setupTestSuite, ok := suite.(SetupTestSuite); ok { 119 | setupTestSuite.SetupTest() 120 | } 121 | if beforeTestSuite, ok := suite.(BeforeTest); ok { 122 | beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) 123 | } 124 | defer func() { 125 | if afterTestSuite, ok := suite.(AfterTest); ok { 126 | afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) 127 | } 128 | if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { 129 | tearDownTestSuite.TearDownTest() 130 | } 131 | suite.SetT(parentT) 132 | }() 133 | method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) 134 | }, 135 | } 136 | tests = append(tests, test) 137 | } 138 | runTests(t, tests) 139 | } 140 | 141 | func runTests(t testing.TB, tests []testing.InternalTest) { 142 | r, ok := t.(runner) 143 | if !ok { // backwards compatibility with Go 1.6 and below 144 | if !testing.RunTests(allTestsFilter, tests) { 145 | t.Fail() 146 | } 147 | return 148 | } 149 | 150 | for _, test := range tests { 151 | r.Run(test.Name, test.F) 152 | } 153 | } 154 | 155 | // Filtering method according to set regular expression 156 | // specified command-line argument -m 157 | func methodFilter(name string) (bool, error) { 158 | if ok, _ := regexp.MatchString("^Test", name); !ok { 159 | return false, nil 160 | } 161 | return regexp.MatchString(*matchMethod, name) 162 | } 163 | 164 | type runner interface { 165 | Run(name string, f func(t *testing.T)) bool 166 | } 167 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2012-2016 Dave Collins 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 Dave Collins 2 | // 3 | // Permission to use, copy, modify, and distribute this software for any 4 | // purpose with or without fee is hereby granted, provided that the above 5 | // copyright notice and this permission notice appear in all copies. 6 | // 7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 | 15 | // NOTE: Due to the following build constraints, this file will only be compiled 16 | // when the code is running on Google App Engine, compiled by GopherJS, or 17 | // "-tags safe" is added to the go build command line. The "disableunsafe" 18 | // tag is deprecated and thus should not be used. 19 | // +build js appengine safe disableunsafe 20 | 21 | package spew 22 | 23 | import "reflect" 24 | 25 | const ( 26 | // UnsafeDisabled is a build-time constant which specifies whether or 27 | // not access to the unsafe package is available. 28 | UnsafeDisabled = true 29 | ) 30 | 31 | // unsafeReflectValue typically converts the passed reflect.Value into a one 32 | // that bypasses the typical safety restrictions preventing access to 33 | // unaddressable and unexported data. However, doing this relies on access to 34 | // the unsafe package. This is a stub version which simply returns the passed 35 | // reflect.Value when the unsafe package is not available. 36 | func unsafeReflectValue(v reflect.Value) reflect.Value { 37 | return v 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, Patrick Mezard 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | The names of its contributors may not be used to endorse or promote 14 | products derived from this software without specific prior written 15 | permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 18 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 19 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 20 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 23 | TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 24 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 25 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 26 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2014 Stretchr, Inc. 4 | Copyright (c) 2017-2018 objx contributors 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // arrayAccesRegexString is the regex used to extract the array number 11 | // from the access path 12 | const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` 13 | 14 | // arrayAccesRegex is the compiled arrayAccesRegexString 15 | var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) 16 | 17 | // Get gets the value using the specified selector and 18 | // returns it inside a new Obj object. 19 | // 20 | // If it cannot find the value, Get will return a nil 21 | // value inside an instance of Obj. 22 | // 23 | // Get can only operate directly on map[string]interface{} and []interface. 24 | // 25 | // Example 26 | // 27 | // To access the title of the third chapter of the second book, do: 28 | // 29 | // o.Get("books[1].chapters[2].title") 30 | func (m Map) Get(selector string) *Value { 31 | rawObj := access(m, selector, nil, false, false) 32 | return &Value{data: rawObj} 33 | } 34 | 35 | // Set sets the value using the specified selector and 36 | // returns the object on which Set was called. 37 | // 38 | // Set can only operate directly on map[string]interface{} and []interface 39 | // 40 | // Example 41 | // 42 | // To set the title of the third chapter of the second book, do: 43 | // 44 | // o.Set("books[1].chapters[2].title","Time to Go") 45 | func (m Map) Set(selector string, value interface{}) Map { 46 | access(m, selector, value, true, false) 47 | return m 48 | } 49 | 50 | // access accesses the object using the selector and performs the 51 | // appropriate action. 52 | func access(current, selector, value interface{}, isSet, panics bool) interface{} { 53 | 54 | switch selector.(type) { 55 | case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: 56 | 57 | if array, ok := current.([]interface{}); ok { 58 | index := intFromInterface(selector) 59 | 60 | if index >= len(array) { 61 | if panics { 62 | panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) 63 | } 64 | return nil 65 | } 66 | 67 | return array[index] 68 | } 69 | 70 | return nil 71 | 72 | case string: 73 | 74 | selStr := selector.(string) 75 | selSegs := strings.SplitN(selStr, PathSeparator, 2) 76 | thisSel := selSegs[0] 77 | index := -1 78 | var err error 79 | 80 | if strings.Contains(thisSel, "[") { 81 | arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) 82 | 83 | if len(arrayMatches) > 0 { 84 | // Get the key into the map 85 | thisSel = arrayMatches[1] 86 | 87 | // Get the index into the array at the key 88 | index, err = strconv.Atoi(arrayMatches[2]) 89 | 90 | if err != nil { 91 | // This should never happen. If it does, something has gone 92 | // seriously wrong. Panic. 93 | panic("objx: Array index is not an integer. Must use array[int].") 94 | } 95 | } 96 | } 97 | 98 | if curMap, ok := current.(Map); ok { 99 | current = map[string]interface{}(curMap) 100 | } 101 | 102 | // get the object in question 103 | switch current.(type) { 104 | case map[string]interface{}: 105 | curMSI := current.(map[string]interface{}) 106 | if len(selSegs) <= 1 && isSet { 107 | curMSI[thisSel] = value 108 | return nil 109 | } 110 | current = curMSI[thisSel] 111 | default: 112 | current = nil 113 | } 114 | 115 | if current == nil && panics { 116 | panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) 117 | } 118 | 119 | // do we need to access the item of an array? 120 | if index > -1 { 121 | if array, ok := current.([]interface{}); ok { 122 | if index < len(array) { 123 | current = array[index] 124 | } else { 125 | if panics { 126 | panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) 127 | } 128 | current = nil 129 | } 130 | } 131 | } 132 | 133 | if len(selSegs) > 1 { 134 | current = access(current, selSegs[1], value, isSet, panics) 135 | } 136 | 137 | } 138 | return current 139 | } 140 | 141 | // intFromInterface converts an interface object to the largest 142 | // representation of an unsigned integer using a type switch and 143 | // assertions 144 | func intFromInterface(selector interface{}) int { 145 | var value int 146 | switch selector.(type) { 147 | case int: 148 | value = selector.(int) 149 | case int8: 150 | value = int(selector.(int8)) 151 | case int16: 152 | value = int(selector.(int16)) 153 | case int32: 154 | value = int(selector.(int32)) 155 | case int64: 156 | value = int(selector.(int64)) 157 | case uint: 158 | value = int(selector.(uint)) 159 | case uint8: 160 | value = int(selector.(uint8)) 161 | case uint16: 162 | value = int(selector.(uint16)) 163 | case uint32: 164 | value = int(selector.(uint32)) 165 | case uint64: 166 | value = int(selector.(uint64)) 167 | default: 168 | panic("objx: array access argument is not an integer type (this should never happen)") 169 | } 170 | return value 171 | } 172 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | const ( 4 | // PathSeparator is the character used to separate the elements 5 | // of the keypath. 6 | // 7 | // For example, `location.address.city` 8 | PathSeparator string = "." 9 | 10 | // SignatureSeparator is the character that is used to 11 | // separate the Base64 string from the security signature. 12 | SignatureSeparator = "_" 13 | ) 14 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "net/url" 10 | ) 11 | 12 | // JSON converts the contained object to a JSON string 13 | // representation 14 | func (m Map) JSON() (string, error) { 15 | result, err := json.Marshal(m) 16 | if err != nil { 17 | err = errors.New("objx: JSON encode failed with: " + err.Error()) 18 | } 19 | return string(result), err 20 | } 21 | 22 | // MustJSON converts the contained object to a JSON string 23 | // representation and panics if there is an error 24 | func (m Map) MustJSON() string { 25 | result, err := m.JSON() 26 | if err != nil { 27 | panic(err.Error()) 28 | } 29 | return result 30 | } 31 | 32 | // Base64 converts the contained object to a Base64 string 33 | // representation of the JSON string representation 34 | func (m Map) Base64() (string, error) { 35 | var buf bytes.Buffer 36 | 37 | jsonData, err := m.JSON() 38 | if err != nil { 39 | return "", err 40 | } 41 | 42 | encoder := base64.NewEncoder(base64.StdEncoding, &buf) 43 | _, err = encoder.Write([]byte(jsonData)) 44 | if err != nil { 45 | return "", err 46 | } 47 | _ = encoder.Close() 48 | 49 | return buf.String(), nil 50 | } 51 | 52 | // MustBase64 converts the contained object to a Base64 string 53 | // representation of the JSON string representation and panics 54 | // if there is an error 55 | func (m Map) MustBase64() string { 56 | result, err := m.Base64() 57 | if err != nil { 58 | panic(err.Error()) 59 | } 60 | return result 61 | } 62 | 63 | // SignedBase64 converts the contained object to a Base64 string 64 | // representation of the JSON string representation and signs it 65 | // using the provided key. 66 | func (m Map) SignedBase64(key string) (string, error) { 67 | base64, err := m.Base64() 68 | if err != nil { 69 | return "", err 70 | } 71 | 72 | sig := HashWithKey(base64, key) 73 | return base64 + SignatureSeparator + sig, nil 74 | } 75 | 76 | // MustSignedBase64 converts the contained object to a Base64 string 77 | // representation of the JSON string representation and signs it 78 | // using the provided key and panics if there is an error 79 | func (m Map) MustSignedBase64(key string) string { 80 | result, err := m.SignedBase64(key) 81 | if err != nil { 82 | panic(err.Error()) 83 | } 84 | return result 85 | } 86 | 87 | /* 88 | URL Query 89 | ------------------------------------------------ 90 | */ 91 | 92 | // URLValues creates a url.Values object from an Obj. This 93 | // function requires that the wrapped object be a map[string]interface{} 94 | func (m Map) URLValues() url.Values { 95 | vals := make(url.Values) 96 | for k, v := range m { 97 | //TODO: can this be done without sprintf? 98 | vals.Set(k, fmt.Sprintf("%v", v)) 99 | } 100 | return vals 101 | } 102 | 103 | // URLQuery gets an encoded URL query representing the given 104 | // Obj. This function requires that the wrapped object be a 105 | // map[string]interface{} 106 | func (m Map) URLQuery() (string, error) { 107 | return m.URLValues().Encode(), nil 108 | } 109 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Objx - Go package for dealing with maps, slices, JSON and other data. 3 | 4 | Overview 5 | 6 | Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes 7 | a powerful `Get` method (among others) that allows you to easily and quickly get 8 | access to data within the map, without having to worry too much about type assertions, 9 | missing data, default values etc. 10 | 11 | Pattern 12 | 13 | Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. 14 | Call one of the `objx.` functions to create your `objx.Map` to get going: 15 | 16 | m, err := objx.FromJSON(json) 17 | 18 | NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, 19 | the rest will be optimistic and try to figure things out without panicking. 20 | 21 | Use `Get` to access the value you're interested in. You can use dot and array 22 | notation too: 23 | 24 | m.Get("places[0].latlng") 25 | 26 | Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. 27 | 28 | if m.Get("code").IsStr() { // Your code... } 29 | 30 | Or you can just assume the type, and use one of the strong type methods to extract the real value: 31 | 32 | m.Get("code").Int() 33 | 34 | If there's no value there (or if it's the wrong type) then a default value will be returned, 35 | or you can be explicit about the default value. 36 | 37 | Get("code").Int(-1) 38 | 39 | If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, 40 | manipulating and selecting that data. You can find out more by exploring the index below. 41 | 42 | Reading data 43 | 44 | A simple example of how to use Objx: 45 | 46 | // Use MustFromJSON to make an objx.Map from some JSON 47 | m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) 48 | 49 | // Get the details 50 | name := m.Get("name").Str() 51 | age := m.Get("age").Int() 52 | 53 | // Get their nickname (or use their name if they don't have one) 54 | nickname := m.Get("nickname").Str(name) 55 | 56 | Ranging 57 | 58 | Since `objx.Map` is a `map[string]interface{}` you can treat it as such. 59 | For example, to `range` the data, do what you would expect: 60 | 61 | m := objx.MustFromJSON(json) 62 | for key, value := range m { 63 | // Your code... 64 | } 65 | */ 66 | package objx 67 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | // Exclude returns a new Map with the keys in the specified []string 4 | // excluded. 5 | func (m Map) Exclude(exclude []string) Map { 6 | excluded := make(Map) 7 | for k, v := range m { 8 | var shouldInclude = true 9 | for _, toExclude := range exclude { 10 | if k == toExclude { 11 | shouldInclude = false 12 | break 13 | } 14 | } 15 | if shouldInclude { 16 | excluded[k] = v 17 | } 18 | } 19 | return excluded 20 | } 21 | 22 | // Copy creates a shallow copy of the Obj. 23 | func (m Map) Copy() Map { 24 | copied := make(map[string]interface{}) 25 | for k, v := range m { 26 | copied[k] = v 27 | } 28 | return New(copied) 29 | } 30 | 31 | // Merge blends the specified map with a copy of this map and returns the result. 32 | // 33 | // Keys that appear in both will be selected from the specified map. 34 | // This method requires that the wrapped object be a map[string]interface{} 35 | func (m Map) Merge(merge Map) Map { 36 | return m.Copy().MergeHere(merge) 37 | } 38 | 39 | // MergeHere blends the specified map with this map and returns the current map. 40 | // 41 | // Keys that appear in both will be selected from the specified map. The original map 42 | // will be modified. This method requires that 43 | // the wrapped object be a map[string]interface{} 44 | func (m Map) MergeHere(merge Map) Map { 45 | for k, v := range merge { 46 | m[k] = v 47 | } 48 | return m 49 | } 50 | 51 | // Transform builds a new Obj giving the transformer a chance 52 | // to change the keys and values as it goes. This method requires that 53 | // the wrapped object be a map[string]interface{} 54 | func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { 55 | newMap := make(map[string]interface{}) 56 | for k, v := range m { 57 | modifiedKey, modifiedVal := transformer(k, v) 58 | newMap[modifiedKey] = modifiedVal 59 | } 60 | return New(newMap) 61 | } 62 | 63 | // TransformKeys builds a new map using the specified key mapping. 64 | // 65 | // Unspecified keys will be unaltered. 66 | // This method requires that the wrapped object be a map[string]interface{} 67 | func (m Map) TransformKeys(mapping map[string]string) Map { 68 | return m.Transform(func(key string, value interface{}) (string, interface{}) { 69 | if newKey, ok := mapping[key]; ok { 70 | return newKey, value 71 | } 72 | return key, value 73 | }) 74 | } 75 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "crypto/sha1" 5 | "encoding/hex" 6 | ) 7 | 8 | // HashWithKey hashes the specified string using the security 9 | // key. 10 | func HashWithKey(data, key string) string { 11 | hash := sha1.New() 12 | _, err := hash.Write([]byte(data + ":" + key)) 13 | if err != nil { 14 | return "" 15 | } 16 | return hex.EncodeToString(hash.Sum(nil)) 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | // Has gets whether there is something at the specified selector 4 | // or not. 5 | // 6 | // If m is nil, Has will always return false. 7 | func (m Map) Has(selector string) bool { 8 | if m == nil { 9 | return false 10 | } 11 | return !m.Get(selector).IsNil() 12 | } 13 | 14 | // IsNil gets whether the data is nil or not. 15 | func (v *Value) IsNil() bool { 16 | return v == nil || v.data == nil 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | // Value provides methods for extracting interface{} data in various 9 | // types. 10 | type Value struct { 11 | // data contains the raw data being managed by this Value 12 | data interface{} 13 | } 14 | 15 | // Data returns the raw data contained by this Value 16 | func (v *Value) Data() interface{} { 17 | return v.data 18 | } 19 | 20 | // String returns the value always as a string 21 | func (v *Value) String() string { 22 | switch { 23 | case v.IsStr(): 24 | return v.Str() 25 | case v.IsBool(): 26 | return strconv.FormatBool(v.Bool()) 27 | case v.IsFloat32(): 28 | return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32) 29 | case v.IsFloat64(): 30 | return strconv.FormatFloat(v.Float64(), 'f', -1, 64) 31 | case v.IsInt(): 32 | return strconv.FormatInt(int64(v.Int()), 10) 33 | case v.IsInt(): 34 | return strconv.FormatInt(int64(v.Int()), 10) 35 | case v.IsInt8(): 36 | return strconv.FormatInt(int64(v.Int8()), 10) 37 | case v.IsInt16(): 38 | return strconv.FormatInt(int64(v.Int16()), 10) 39 | case v.IsInt32(): 40 | return strconv.FormatInt(int64(v.Int32()), 10) 41 | case v.IsInt64(): 42 | return strconv.FormatInt(v.Int64(), 10) 43 | case v.IsUint(): 44 | return strconv.FormatUint(uint64(v.Uint()), 10) 45 | case v.IsUint8(): 46 | return strconv.FormatUint(uint64(v.Uint8()), 10) 47 | case v.IsUint16(): 48 | return strconv.FormatUint(uint64(v.Uint16()), 10) 49 | case v.IsUint32(): 50 | return strconv.FormatUint(uint64(v.Uint32()), 10) 51 | case v.IsUint64(): 52 | return strconv.FormatUint(v.Uint64(), 10) 53 | } 54 | 55 | return fmt.Sprintf("%#v", v.Data()) 56 | } 57 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/blake2s_386.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386,!gccgo,!appengine 6 | 7 | package blake2s 8 | 9 | import "golang.org/x/sys/cpu" 10 | 11 | var ( 12 | useSSE4 = false 13 | useSSSE3 = cpu.X86.HasSSSE3 14 | useSSE2 = cpu.X86.HasSSE2 15 | ) 16 | 17 | //go:noescape 18 | func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 19 | 20 | //go:noescape 21 | func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 22 | 23 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 24 | switch { 25 | case useSSSE3: 26 | hashBlocksSSSE3(h, c, flag, blocks) 27 | case useSSE2: 28 | hashBlocksSSE2(h, c, flag, blocks) 29 | default: 30 | hashBlocksGeneric(h, c, flag, blocks) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/blake2s_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!gccgo,!appengine 6 | 7 | package blake2s 8 | 9 | import "golang.org/x/sys/cpu" 10 | 11 | var ( 12 | useSSE4 = cpu.X86.HasSSE41 13 | useSSSE3 = cpu.X86.HasSSSE3 14 | useSSE2 = cpu.X86.HasSSE2 15 | ) 16 | 17 | //go:noescape 18 | func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 19 | 20 | //go:noescape 21 | func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 22 | 23 | //go:noescape 24 | func hashBlocksSSE4(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 25 | 26 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 27 | switch { 28 | case useSSE4: 29 | hashBlocksSSE4(h, c, flag, blocks) 30 | case useSSSE3: 31 | hashBlocksSSSE3(h, c, flag, blocks) 32 | case useSSE2: 33 | hashBlocksSSE2(h, c, flag, blocks) 34 | default: 35 | hashBlocksGeneric(h, c, flag, blocks) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/blake2s_generic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package blake2s 6 | 7 | import ( 8 | "math/bits" 9 | ) 10 | 11 | // the precomputed values for BLAKE2s 12 | // there are 10 16-byte arrays - one for each round 13 | // the entries are calculated from the sigma constants. 14 | var precomputed = [10][16]byte{ 15 | {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, 16 | {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, 17 | {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, 18 | {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, 19 | {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, 20 | {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, 21 | {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, 22 | {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, 23 | {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, 24 | {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, 25 | } 26 | 27 | func hashBlocksGeneric(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 28 | var m [16]uint32 29 | c0, c1 := c[0], c[1] 30 | 31 | for i := 0; i < len(blocks); { 32 | c0 += BlockSize 33 | if c0 < BlockSize { 34 | c1++ 35 | } 36 | 37 | v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] 38 | v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] 39 | v12 ^= c0 40 | v13 ^= c1 41 | v14 ^= flag 42 | 43 | for j := range m { 44 | m[j] = uint32(blocks[i]) | uint32(blocks[i+1])<<8 | uint32(blocks[i+2])<<16 | uint32(blocks[i+3])<<24 45 | i += 4 46 | } 47 | 48 | for k := range precomputed { 49 | s := &(precomputed[k]) 50 | 51 | v0 += m[s[0]] 52 | v0 += v4 53 | v12 ^= v0 54 | v12 = bits.RotateLeft32(v12, -16) 55 | v8 += v12 56 | v4 ^= v8 57 | v4 = bits.RotateLeft32(v4, -12) 58 | v1 += m[s[1]] 59 | v1 += v5 60 | v13 ^= v1 61 | v13 = bits.RotateLeft32(v13, -16) 62 | v9 += v13 63 | v5 ^= v9 64 | v5 = bits.RotateLeft32(v5, -12) 65 | v2 += m[s[2]] 66 | v2 += v6 67 | v14 ^= v2 68 | v14 = bits.RotateLeft32(v14, -16) 69 | v10 += v14 70 | v6 ^= v10 71 | v6 = bits.RotateLeft32(v6, -12) 72 | v3 += m[s[3]] 73 | v3 += v7 74 | v15 ^= v3 75 | v15 = bits.RotateLeft32(v15, -16) 76 | v11 += v15 77 | v7 ^= v11 78 | v7 = bits.RotateLeft32(v7, -12) 79 | 80 | v0 += m[s[4]] 81 | v0 += v4 82 | v12 ^= v0 83 | v12 = bits.RotateLeft32(v12, -8) 84 | v8 += v12 85 | v4 ^= v8 86 | v4 = bits.RotateLeft32(v4, -7) 87 | v1 += m[s[5]] 88 | v1 += v5 89 | v13 ^= v1 90 | v13 = bits.RotateLeft32(v13, -8) 91 | v9 += v13 92 | v5 ^= v9 93 | v5 = bits.RotateLeft32(v5, -7) 94 | v2 += m[s[6]] 95 | v2 += v6 96 | v14 ^= v2 97 | v14 = bits.RotateLeft32(v14, -8) 98 | v10 += v14 99 | v6 ^= v10 100 | v6 = bits.RotateLeft32(v6, -7) 101 | v3 += m[s[7]] 102 | v3 += v7 103 | v15 ^= v3 104 | v15 = bits.RotateLeft32(v15, -8) 105 | v11 += v15 106 | v7 ^= v11 107 | v7 = bits.RotateLeft32(v7, -7) 108 | 109 | v0 += m[s[8]] 110 | v0 += v5 111 | v15 ^= v0 112 | v15 = bits.RotateLeft32(v15, -16) 113 | v10 += v15 114 | v5 ^= v10 115 | v5 = bits.RotateLeft32(v5, -12) 116 | v1 += m[s[9]] 117 | v1 += v6 118 | v12 ^= v1 119 | v12 = bits.RotateLeft32(v12, -16) 120 | v11 += v12 121 | v6 ^= v11 122 | v6 = bits.RotateLeft32(v6, -12) 123 | v2 += m[s[10]] 124 | v2 += v7 125 | v13 ^= v2 126 | v13 = bits.RotateLeft32(v13, -16) 127 | v8 += v13 128 | v7 ^= v8 129 | v7 = bits.RotateLeft32(v7, -12) 130 | v3 += m[s[11]] 131 | v3 += v4 132 | v14 ^= v3 133 | v14 = bits.RotateLeft32(v14, -16) 134 | v9 += v14 135 | v4 ^= v9 136 | v4 = bits.RotateLeft32(v4, -12) 137 | 138 | v0 += m[s[12]] 139 | v0 += v5 140 | v15 ^= v0 141 | v15 = bits.RotateLeft32(v15, -8) 142 | v10 += v15 143 | v5 ^= v10 144 | v5 = bits.RotateLeft32(v5, -7) 145 | v1 += m[s[13]] 146 | v1 += v6 147 | v12 ^= v1 148 | v12 = bits.RotateLeft32(v12, -8) 149 | v11 += v12 150 | v6 ^= v11 151 | v6 = bits.RotateLeft32(v6, -7) 152 | v2 += m[s[14]] 153 | v2 += v7 154 | v13 ^= v2 155 | v13 = bits.RotateLeft32(v13, -8) 156 | v8 += v13 157 | v7 ^= v8 158 | v7 = bits.RotateLeft32(v7, -7) 159 | v3 += m[s[15]] 160 | v3 += v4 161 | v14 ^= v3 162 | v14 = bits.RotateLeft32(v14, -8) 163 | v9 += v14 164 | v4 ^= v9 165 | v4 = bits.RotateLeft32(v4, -7) 166 | } 167 | 168 | h[0] ^= v0 ^ v8 169 | h[1] ^= v1 ^ v9 170 | h[2] ^= v2 ^ v10 171 | h[3] ^= v3 ^ v11 172 | h[4] ^= v4 ^ v12 173 | h[5] ^= v5 ^ v13 174 | h[6] ^= v6 ^ v14 175 | h[7] ^= v7 ^ v15 176 | } 177 | c[0], c[1] = c0, c1 178 | } 179 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/blake2s_ref.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64,!386 gccgo appengine 6 | 7 | package blake2s 8 | 9 | var ( 10 | useSSE4 = false 11 | useSSSE3 = false 12 | useSSE2 = false 13 | ) 14 | 15 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 16 | hashBlocksGeneric(h, c, flag, blocks) 17 | } 18 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/blake2x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package blake2s 6 | 7 | import ( 8 | "encoding/binary" 9 | "errors" 10 | "io" 11 | ) 12 | 13 | // XOF defines the interface to hash functions that 14 | // support arbitrary-length output. 15 | type XOF interface { 16 | // Write absorbs more data into the hash's state. It panics if called 17 | // after Read. 18 | io.Writer 19 | 20 | // Read reads more output from the hash. It returns io.EOF if the limit 21 | // has been reached. 22 | io.Reader 23 | 24 | // Clone returns a copy of the XOF in its current state. 25 | Clone() XOF 26 | 27 | // Reset resets the XOF to its initial state. 28 | Reset() 29 | } 30 | 31 | // OutputLengthUnknown can be used as the size argument to NewXOF to indicate 32 | // the length of the output is not known in advance. 33 | const OutputLengthUnknown = 0 34 | 35 | // magicUnknownOutputLength is a magic value for the output size that indicates 36 | // an unknown number of output bytes. 37 | const magicUnknownOutputLength = 65535 38 | 39 | // maxOutputLength is the absolute maximum number of bytes to produce when the 40 | // number of output bytes is unknown. 41 | const maxOutputLength = (1 << 32) * 32 42 | 43 | // NewXOF creates a new variable-output-length hash. The hash either produce a 44 | // known number of bytes (1 <= size < 65535), or an unknown number of bytes 45 | // (size == OutputLengthUnknown). In the latter case, an absolute limit of 46 | // 128GiB applies. 47 | // 48 | // A non-nil key turns the hash into a MAC. The key must between 49 | // zero and 32 bytes long. 50 | func NewXOF(size uint16, key []byte) (XOF, error) { 51 | if len(key) > Size { 52 | return nil, errKeySize 53 | } 54 | if size == magicUnknownOutputLength { 55 | // 2^16-1 indicates an unknown number of bytes and thus isn't a 56 | // valid length. 57 | return nil, errors.New("blake2s: XOF length too large") 58 | } 59 | if size == OutputLengthUnknown { 60 | size = magicUnknownOutputLength 61 | } 62 | x := &xof{ 63 | d: digest{ 64 | size: Size, 65 | keyLen: len(key), 66 | }, 67 | length: size, 68 | } 69 | copy(x.d.key[:], key) 70 | x.Reset() 71 | return x, nil 72 | } 73 | 74 | type xof struct { 75 | d digest 76 | length uint16 77 | remaining uint64 78 | cfg, root, block [Size]byte 79 | offset int 80 | nodeOffset uint32 81 | readMode bool 82 | } 83 | 84 | func (x *xof) Write(p []byte) (n int, err error) { 85 | if x.readMode { 86 | panic("blake2s: write to XOF after read") 87 | } 88 | return x.d.Write(p) 89 | } 90 | 91 | func (x *xof) Clone() XOF { 92 | clone := *x 93 | return &clone 94 | } 95 | 96 | func (x *xof) Reset() { 97 | x.cfg[0] = byte(Size) 98 | binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length 99 | binary.LittleEndian.PutUint16(x.cfg[12:], x.length) // XOF length 100 | x.cfg[15] = byte(Size) // inner hash size 101 | 102 | x.d.Reset() 103 | x.d.h[3] ^= uint32(x.length) 104 | 105 | x.remaining = uint64(x.length) 106 | if x.remaining == magicUnknownOutputLength { 107 | x.remaining = maxOutputLength 108 | } 109 | x.offset, x.nodeOffset = 0, 0 110 | x.readMode = false 111 | } 112 | 113 | func (x *xof) Read(p []byte) (n int, err error) { 114 | if !x.readMode { 115 | x.d.finalize(&x.root) 116 | x.readMode = true 117 | } 118 | 119 | if x.remaining == 0 { 120 | return 0, io.EOF 121 | } 122 | 123 | n = len(p) 124 | if uint64(n) > x.remaining { 125 | n = int(x.remaining) 126 | p = p[:n] 127 | } 128 | 129 | if x.offset > 0 { 130 | blockRemaining := Size - x.offset 131 | if n < blockRemaining { 132 | x.offset += copy(p, x.block[x.offset:]) 133 | x.remaining -= uint64(n) 134 | return 135 | } 136 | copy(p, x.block[x.offset:]) 137 | p = p[blockRemaining:] 138 | x.offset = 0 139 | x.remaining -= uint64(blockRemaining) 140 | } 141 | 142 | for len(p) >= Size { 143 | binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) 144 | x.nodeOffset++ 145 | 146 | x.d.initConfig(&x.cfg) 147 | x.d.Write(x.root[:]) 148 | x.d.finalize(&x.block) 149 | 150 | copy(p, x.block[:]) 151 | p = p[Size:] 152 | x.remaining -= uint64(Size) 153 | } 154 | 155 | if todo := len(p); todo > 0 { 156 | if x.remaining < uint64(Size) { 157 | x.cfg[0] = byte(x.remaining) 158 | } 159 | binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) 160 | x.nodeOffset++ 161 | 162 | x.d.initConfig(&x.cfg) 163 | x.d.Write(x.root[:]) 164 | x.d.finalize(&x.block) 165 | 166 | x.offset = copy(p, x.block[:todo]) 167 | x.remaining -= uint64(todo) 168 | } 169 | 170 | return 171 | } 172 | 173 | func (d *digest) initConfig(cfg *[Size]byte) { 174 | d.offset, d.c[0], d.c[1] = 0, 0, 0 175 | for i := range d.h { 176 | d.h[i] = iv[i] ^ binary.LittleEndian.Uint32(cfg[i*4:]) 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/blake2s/register.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.9 6 | 7 | package blake2s 8 | 9 | import ( 10 | "crypto" 11 | "hash" 12 | ) 13 | 14 | func init() { 15 | newHash256 := func() hash.Hash { 16 | h, _ := New256(nil) 17 | return h 18 | } 19 | 20 | crypto.RegisterHash(crypto.BLAKE2s_256, newHash256) 21 | } 22 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !gccgo 6 | 7 | #include "textflag.h" 8 | 9 | // 10 | // System calls for ppc64, AIX are implemented in runtime/syscall_aix.go 11 | // 12 | 13 | TEXT ·syscall6(SB),NOSPLIT,$0-88 14 | JMP syscall·syscall6(SB) 15 | 16 | TEXT ·rawSyscall6(SB),NOSPLIT,$0-88 17 | JMP syscall·rawSyscall6(SB) 18 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/byteorder.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | import ( 8 | "runtime" 9 | ) 10 | 11 | // byteOrder is a subset of encoding/binary.ByteOrder. 12 | type byteOrder interface { 13 | Uint32([]byte) uint32 14 | Uint64([]byte) uint64 15 | } 16 | 17 | type littleEndian struct{} 18 | type bigEndian struct{} 19 | 20 | func (littleEndian) Uint32(b []byte) uint32 { 21 | _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 22 | return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 23 | } 24 | 25 | func (littleEndian) Uint64(b []byte) uint64 { 26 | _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 27 | return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | 28 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 29 | } 30 | 31 | func (bigEndian) Uint32(b []byte) uint32 { 32 | _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 33 | return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 34 | } 35 | 36 | func (bigEndian) Uint64(b []byte) uint64 { 37 | _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 38 | return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | 39 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 40 | } 41 | 42 | // hostByteOrder returns littleEndian on little-endian machines and 43 | // bigEndian on big-endian machines. 44 | func hostByteOrder() byteOrder { 45 | switch runtime.GOARCH { 46 | case "386", "amd64", "amd64p32", 47 | "alpha", 48 | "arm", "arm64", 49 | "mipsle", "mips64le", "mips64p32le", 50 | "nios2", 51 | "ppc64le", 52 | "riscv", "riscv64", 53 | "sh": 54 | return littleEndian{} 55 | case "armbe", "arm64be", 56 | "m68k", 57 | "mips", "mips64", "mips64p32", 58 | "ppc", "ppc64", 59 | "s390", "s390x", 60 | "shbe", 61 | "sparc", "sparc64": 62 | return bigEndian{} 63 | } 64 | panic("unknown architecture") 65 | } 66 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_aix.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build aix 6 | 7 | package cpu 8 | 9 | const ( 10 | // getsystemcfg constants 11 | _SC_IMPL = 2 12 | _IMPL_POWER8 = 0x10000 13 | _IMPL_POWER9 = 0x20000 14 | ) 15 | 16 | func archInit() { 17 | impl := getsystemcfg(_SC_IMPL) 18 | if impl&_IMPL_POWER8 != 0 { 19 | PPC64.IsPOWER8 = true 20 | } 21 | if impl&_IMPL_POWER9 != 0 { 22 | PPC64.IsPOWER9 = true 23 | } 24 | 25 | Initialized = true 26 | } 27 | 28 | func getsystemcfg(label int) (n uint64) { 29 | r0, _ := callgetsystemcfg(label) 30 | n = uint64(r0) 31 | return 32 | } 33 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_arm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | const cacheLineSize = 32 8 | 9 | // HWCAP/HWCAP2 bits. 10 | // These are specific to Linux. 11 | const ( 12 | hwcap_SWP = 1 << 0 13 | hwcap_HALF = 1 << 1 14 | hwcap_THUMB = 1 << 2 15 | hwcap_26BIT = 1 << 3 16 | hwcap_FAST_MULT = 1 << 4 17 | hwcap_FPA = 1 << 5 18 | hwcap_VFP = 1 << 6 19 | hwcap_EDSP = 1 << 7 20 | hwcap_JAVA = 1 << 8 21 | hwcap_IWMMXT = 1 << 9 22 | hwcap_CRUNCH = 1 << 10 23 | hwcap_THUMBEE = 1 << 11 24 | hwcap_NEON = 1 << 12 25 | hwcap_VFPv3 = 1 << 13 26 | hwcap_VFPv3D16 = 1 << 14 27 | hwcap_TLS = 1 << 15 28 | hwcap_VFPv4 = 1 << 16 29 | hwcap_IDIVA = 1 << 17 30 | hwcap_IDIVT = 1 << 18 31 | hwcap_VFPD32 = 1 << 19 32 | hwcap_LPAE = 1 << 20 33 | hwcap_EVTSTRM = 1 << 21 34 | 35 | hwcap2_AES = 1 << 0 36 | hwcap2_PMULL = 1 << 1 37 | hwcap2_SHA1 = 1 << 2 38 | hwcap2_SHA2 = 1 << 3 39 | hwcap2_CRC32 = 1 << 4 40 | ) 41 | 42 | func initOptions() { 43 | options = []option{ 44 | {Name: "pmull", Feature: &ARM.HasPMULL}, 45 | {Name: "sha1", Feature: &ARM.HasSHA1}, 46 | {Name: "sha2", Feature: &ARM.HasSHA2}, 47 | {Name: "swp", Feature: &ARM.HasSWP}, 48 | {Name: "thumb", Feature: &ARM.HasTHUMB}, 49 | {Name: "thumbee", Feature: &ARM.HasTHUMBEE}, 50 | {Name: "tls", Feature: &ARM.HasTLS}, 51 | {Name: "vfp", Feature: &ARM.HasVFP}, 52 | {Name: "vfpd32", Feature: &ARM.HasVFPD32}, 53 | {Name: "vfpv3", Feature: &ARM.HasVFPv3}, 54 | {Name: "vfpv3d16", Feature: &ARM.HasVFPv3D16}, 55 | {Name: "vfpv4", Feature: &ARM.HasVFPv4}, 56 | {Name: "half", Feature: &ARM.HasHALF}, 57 | {Name: "26bit", Feature: &ARM.Has26BIT}, 58 | {Name: "fastmul", Feature: &ARM.HasFASTMUL}, 59 | {Name: "fpa", Feature: &ARM.HasFPA}, 60 | {Name: "edsp", Feature: &ARM.HasEDSP}, 61 | {Name: "java", Feature: &ARM.HasJAVA}, 62 | {Name: "iwmmxt", Feature: &ARM.HasIWMMXT}, 63 | {Name: "crunch", Feature: &ARM.HasCRUNCH}, 64 | {Name: "neon", Feature: &ARM.HasNEON}, 65 | {Name: "idivt", Feature: &ARM.HasIDIVT}, 66 | {Name: "idiva", Feature: &ARM.HasIDIVA}, 67 | {Name: "lpae", Feature: &ARM.HasLPAE}, 68 | {Name: "evtstrm", Feature: &ARM.HasEVTSTRM}, 69 | {Name: "aes", Feature: &ARM.HasAES}, 70 | {Name: "crc32", Feature: &ARM.HasCRC32}, 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_arm64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | import "runtime" 8 | 9 | const cacheLineSize = 64 10 | 11 | func initOptions() { 12 | options = []option{ 13 | {Name: "fp", Feature: &ARM64.HasFP}, 14 | {Name: "asimd", Feature: &ARM64.HasASIMD}, 15 | {Name: "evstrm", Feature: &ARM64.HasEVTSTRM}, 16 | {Name: "aes", Feature: &ARM64.HasAES}, 17 | {Name: "fphp", Feature: &ARM64.HasFPHP}, 18 | {Name: "jscvt", Feature: &ARM64.HasJSCVT}, 19 | {Name: "lrcpc", Feature: &ARM64.HasLRCPC}, 20 | {Name: "pmull", Feature: &ARM64.HasPMULL}, 21 | {Name: "sha1", Feature: &ARM64.HasSHA1}, 22 | {Name: "sha2", Feature: &ARM64.HasSHA2}, 23 | {Name: "sha3", Feature: &ARM64.HasSHA3}, 24 | {Name: "sha512", Feature: &ARM64.HasSHA512}, 25 | {Name: "sm3", Feature: &ARM64.HasSM3}, 26 | {Name: "sm4", Feature: &ARM64.HasSM4}, 27 | {Name: "sve", Feature: &ARM64.HasSVE}, 28 | {Name: "crc32", Feature: &ARM64.HasCRC32}, 29 | {Name: "atomics", Feature: &ARM64.HasATOMICS}, 30 | {Name: "asimdhp", Feature: &ARM64.HasASIMDHP}, 31 | {Name: "cpuid", Feature: &ARM64.HasCPUID}, 32 | {Name: "asimrdm", Feature: &ARM64.HasASIMDRDM}, 33 | {Name: "fcma", Feature: &ARM64.HasFCMA}, 34 | {Name: "dcpop", Feature: &ARM64.HasDCPOP}, 35 | {Name: "asimddp", Feature: &ARM64.HasASIMDDP}, 36 | {Name: "asimdfhm", Feature: &ARM64.HasASIMDFHM}, 37 | } 38 | } 39 | 40 | func archInit() { 41 | switch runtime.GOOS { 42 | case "android", "darwin", "netbsd": 43 | // Android and iOS don't seem to allow reading these registers. 44 | // 45 | // NetBSD: 46 | // ID_AA64ISAR0_EL1 is a privileged register and cannot be read from EL0. 47 | // It can be read via sysctl(3). Example for future implementers: 48 | // https://nxr.netbsd.org/xref/src/usr.sbin/cpuctl/arch/aarch64.c 49 | // 50 | // Fake the minimal features expected by 51 | // TestARM64minimalFeatures. 52 | ARM64.HasASIMD = true 53 | ARM64.HasFP = true 54 | case "linux": 55 | doinit() 56 | default: 57 | readARM64Registers() 58 | } 59 | } 60 | 61 | func readARM64Registers() { 62 | Initialized = true 63 | 64 | // ID_AA64ISAR0_EL1 65 | isar0 := getisar0() 66 | 67 | switch extractBits(isar0, 4, 7) { 68 | case 1: 69 | ARM64.HasAES = true 70 | case 2: 71 | ARM64.HasAES = true 72 | ARM64.HasPMULL = true 73 | } 74 | 75 | switch extractBits(isar0, 8, 11) { 76 | case 1: 77 | ARM64.HasSHA1 = true 78 | } 79 | 80 | switch extractBits(isar0, 12, 15) { 81 | case 1: 82 | ARM64.HasSHA2 = true 83 | case 2: 84 | ARM64.HasSHA2 = true 85 | ARM64.HasSHA512 = true 86 | } 87 | 88 | switch extractBits(isar0, 16, 19) { 89 | case 1: 90 | ARM64.HasCRC32 = true 91 | } 92 | 93 | switch extractBits(isar0, 20, 23) { 94 | case 2: 95 | ARM64.HasATOMICS = true 96 | } 97 | 98 | switch extractBits(isar0, 28, 31) { 99 | case 1: 100 | ARM64.HasASIMDRDM = true 101 | } 102 | 103 | switch extractBits(isar0, 32, 35) { 104 | case 1: 105 | ARM64.HasSHA3 = true 106 | } 107 | 108 | switch extractBits(isar0, 36, 39) { 109 | case 1: 110 | ARM64.HasSM3 = true 111 | } 112 | 113 | switch extractBits(isar0, 40, 43) { 114 | case 1: 115 | ARM64.HasSM4 = true 116 | } 117 | 118 | switch extractBits(isar0, 44, 47) { 119 | case 1: 120 | ARM64.HasASIMDDP = true 121 | } 122 | 123 | // ID_AA64ISAR1_EL1 124 | isar1 := getisar1() 125 | 126 | switch extractBits(isar1, 0, 3) { 127 | case 1: 128 | ARM64.HasDCPOP = true 129 | } 130 | 131 | switch extractBits(isar1, 12, 15) { 132 | case 1: 133 | ARM64.HasJSCVT = true 134 | } 135 | 136 | switch extractBits(isar1, 16, 19) { 137 | case 1: 138 | ARM64.HasFCMA = true 139 | } 140 | 141 | switch extractBits(isar1, 20, 23) { 142 | case 1: 143 | ARM64.HasLRCPC = true 144 | } 145 | 146 | // ID_AA64PFR0_EL1 147 | pfr0 := getpfr0() 148 | 149 | switch extractBits(pfr0, 16, 19) { 150 | case 0: 151 | ARM64.HasFP = true 152 | case 1: 153 | ARM64.HasFP = true 154 | ARM64.HasFPHP = true 155 | } 156 | 157 | switch extractBits(pfr0, 20, 23) { 158 | case 0: 159 | ARM64.HasASIMD = true 160 | case 1: 161 | ARM64.HasASIMD = true 162 | ARM64.HasASIMDHP = true 163 | } 164 | 165 | switch extractBits(pfr0, 32, 35) { 166 | case 1: 167 | ARM64.HasSVE = true 168 | } 169 | } 170 | 171 | func extractBits(data uint64, start, end uint) uint { 172 | return (uint)(data>>start) & ((1 << (end - start + 1)) - 1) 173 | } 174 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_arm64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !gccgo 6 | 7 | #include "textflag.h" 8 | 9 | // func getisar0() uint64 10 | TEXT ·getisar0(SB),NOSPLIT,$0-8 11 | // get Instruction Set Attributes 0 into x0 12 | // mrs x0, ID_AA64ISAR0_EL1 = d5380600 13 | WORD $0xd5380600 14 | MOVD R0, ret+0(FP) 15 | RET 16 | 17 | // func getisar1() uint64 18 | TEXT ·getisar1(SB),NOSPLIT,$0-8 19 | // get Instruction Set Attributes 1 into x0 20 | // mrs x0, ID_AA64ISAR1_EL1 = d5380620 21 | WORD $0xd5380620 22 | MOVD R0, ret+0(FP) 23 | RET 24 | 25 | // func getpfr0() uint64 26 | TEXT ·getpfr0(SB),NOSPLIT,$0-8 27 | // get Processor Feature Register 0 into x0 28 | // mrs x0, ID_AA64PFR0_EL1 = d5380400 29 | WORD $0xd5380400 30 | MOVD R0, ret+0(FP) 31 | RET 32 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !gccgo 6 | 7 | package cpu 8 | 9 | func getisar0() uint64 10 | func getisar1() uint64 11 | func getpfr0() uint64 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !gccgo 6 | 7 | package cpu 8 | 9 | // haveAsmFunctions reports whether the other functions in this file can 10 | // be safely called. 11 | func haveAsmFunctions() bool { return true } 12 | 13 | // The following feature detection functions are defined in cpu_s390x.s. 14 | // They are likely to be expensive to call so the results should be cached. 15 | func stfle() facilityList 16 | func kmQuery() queryResult 17 | func kmcQuery() queryResult 18 | func kmctrQuery() queryResult 19 | func kmaQuery() queryResult 20 | func kimdQuery() queryResult 21 | func klmdQuery() queryResult 22 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gc_x86.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386 amd64 amd64p32 6 | // +build !gccgo 7 | 8 | package cpu 9 | 10 | // cpuid is implemented in cpu_x86.s for gc compiler 11 | // and in cpu_gccgo.c for gccgo. 12 | func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) 13 | 14 | // xgetbv with ecx = 0 is implemented in cpu_x86.s for gc compiler 15 | // and in cpu_gccgo.c for gccgo. 16 | func xgetbv() (eax, edx uint32) 17 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build gccgo 6 | 7 | package cpu 8 | 9 | func getisar0() uint64 { return 0 } 10 | func getisar1() uint64 { return 0 } 11 | func getpfr0() uint64 { return 0 } 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build gccgo 6 | 7 | package cpu 8 | 9 | // haveAsmFunctions reports whether the other functions in this file can 10 | // be safely called. 11 | func haveAsmFunctions() bool { return false } 12 | 13 | // TODO(mundaym): the following feature detection functions are currently 14 | // stubs. See https://golang.org/cl/162887 for how to fix this. 15 | // They are likely to be expensive to call so the results should be cached. 16 | func stfle() facilityList { panic("not implemented for gccgo") } 17 | func kmQuery() queryResult { panic("not implemented for gccgo") } 18 | func kmcQuery() queryResult { panic("not implemented for gccgo") } 19 | func kmctrQuery() queryResult { panic("not implemented for gccgo") } 20 | func kmaQuery() queryResult { panic("not implemented for gccgo") } 21 | func kimdQuery() queryResult { panic("not implemented for gccgo") } 22 | func klmdQuery() queryResult { panic("not implemented for gccgo") } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386 amd64 amd64p32 6 | // +build gccgo 7 | 8 | #include 9 | #include 10 | 11 | // Need to wrap __get_cpuid_count because it's declared as static. 12 | int 13 | gccgoGetCpuidCount(uint32_t leaf, uint32_t subleaf, 14 | uint32_t *eax, uint32_t *ebx, 15 | uint32_t *ecx, uint32_t *edx) 16 | { 17 | return __get_cpuid_count(leaf, subleaf, eax, ebx, ecx, edx); 18 | } 19 | 20 | // xgetbv reads the contents of an XCR (Extended Control Register) 21 | // specified in the ECX register into registers EDX:EAX. 22 | // Currently, the only supported value for XCR is 0. 23 | // 24 | // TODO: Replace with a better alternative: 25 | // 26 | // #include 27 | // 28 | // #pragma GCC target("xsave") 29 | // 30 | // void gccgoXgetbv(uint32_t *eax, uint32_t *edx) { 31 | // unsigned long long x = _xgetbv(0); 32 | // *eax = x & 0xffffffff; 33 | // *edx = (x >> 32) & 0xffffffff; 34 | // } 35 | // 36 | // Note that _xgetbv is defined starting with GCC 8. 37 | void 38 | gccgoXgetbv(uint32_t *eax, uint32_t *edx) 39 | { 40 | __asm(" xorl %%ecx, %%ecx\n" 41 | " xgetbv" 42 | : "=a"(*eax), "=d"(*edx)); 43 | } 44 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386 amd64 amd64p32 6 | // +build gccgo 7 | 8 | package cpu 9 | 10 | //extern gccgoGetCpuidCount 11 | func gccgoGetCpuidCount(eaxArg, ecxArg uint32, eax, ebx, ecx, edx *uint32) 12 | 13 | func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) { 14 | var a, b, c, d uint32 15 | gccgoGetCpuidCount(eaxArg, ecxArg, &a, &b, &c, &d) 16 | return a, b, c, d 17 | } 18 | 19 | //extern gccgoXgetbv 20 | func gccgoXgetbv(eax, edx *uint32) 21 | 22 | func xgetbv() (eax, edx uint32) { 23 | var a, d uint32 24 | gccgoXgetbv(&a, &d) 25 | return a, d 26 | } 27 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !386,!amd64,!amd64p32,!arm64 6 | 7 | package cpu 8 | 9 | func archInit() { 10 | if err := readHWCAP(); err != nil { 11 | return 12 | } 13 | doinit() 14 | Initialized = true 15 | } 16 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_arm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | func doinit() { 8 | ARM.HasSWP = isSet(hwCap, hwcap_SWP) 9 | ARM.HasHALF = isSet(hwCap, hwcap_HALF) 10 | ARM.HasTHUMB = isSet(hwCap, hwcap_THUMB) 11 | ARM.Has26BIT = isSet(hwCap, hwcap_26BIT) 12 | ARM.HasFASTMUL = isSet(hwCap, hwcap_FAST_MULT) 13 | ARM.HasFPA = isSet(hwCap, hwcap_FPA) 14 | ARM.HasVFP = isSet(hwCap, hwcap_VFP) 15 | ARM.HasEDSP = isSet(hwCap, hwcap_EDSP) 16 | ARM.HasJAVA = isSet(hwCap, hwcap_JAVA) 17 | ARM.HasIWMMXT = isSet(hwCap, hwcap_IWMMXT) 18 | ARM.HasCRUNCH = isSet(hwCap, hwcap_CRUNCH) 19 | ARM.HasTHUMBEE = isSet(hwCap, hwcap_THUMBEE) 20 | ARM.HasNEON = isSet(hwCap, hwcap_NEON) 21 | ARM.HasVFPv3 = isSet(hwCap, hwcap_VFPv3) 22 | ARM.HasVFPv3D16 = isSet(hwCap, hwcap_VFPv3D16) 23 | ARM.HasTLS = isSet(hwCap, hwcap_TLS) 24 | ARM.HasVFPv4 = isSet(hwCap, hwcap_VFPv4) 25 | ARM.HasIDIVA = isSet(hwCap, hwcap_IDIVA) 26 | ARM.HasIDIVT = isSet(hwCap, hwcap_IDIVT) 27 | ARM.HasVFPD32 = isSet(hwCap, hwcap_VFPD32) 28 | ARM.HasLPAE = isSet(hwCap, hwcap_LPAE) 29 | ARM.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) 30 | ARM.HasAES = isSet(hwCap2, hwcap2_AES) 31 | ARM.HasPMULL = isSet(hwCap2, hwcap2_PMULL) 32 | ARM.HasSHA1 = isSet(hwCap2, hwcap2_SHA1) 33 | ARM.HasSHA2 = isSet(hwCap2, hwcap2_SHA2) 34 | ARM.HasCRC32 = isSet(hwCap2, hwcap2_CRC32) 35 | } 36 | 37 | func isSet(hwc uint, value uint) bool { 38 | return hwc&value != 0 39 | } 40 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | // HWCAP/HWCAP2 bits. These are exposed by Linux. 8 | const ( 9 | hwcap_FP = 1 << 0 10 | hwcap_ASIMD = 1 << 1 11 | hwcap_EVTSTRM = 1 << 2 12 | hwcap_AES = 1 << 3 13 | hwcap_PMULL = 1 << 4 14 | hwcap_SHA1 = 1 << 5 15 | hwcap_SHA2 = 1 << 6 16 | hwcap_CRC32 = 1 << 7 17 | hwcap_ATOMICS = 1 << 8 18 | hwcap_FPHP = 1 << 9 19 | hwcap_ASIMDHP = 1 << 10 20 | hwcap_CPUID = 1 << 11 21 | hwcap_ASIMDRDM = 1 << 12 22 | hwcap_JSCVT = 1 << 13 23 | hwcap_FCMA = 1 << 14 24 | hwcap_LRCPC = 1 << 15 25 | hwcap_DCPOP = 1 << 16 26 | hwcap_SHA3 = 1 << 17 27 | hwcap_SM3 = 1 << 18 28 | hwcap_SM4 = 1 << 19 29 | hwcap_ASIMDDP = 1 << 20 30 | hwcap_SHA512 = 1 << 21 31 | hwcap_SVE = 1 << 22 32 | hwcap_ASIMDFHM = 1 << 23 33 | ) 34 | 35 | func doinit() { 36 | if err := readHWCAP(); err != nil { 37 | // failed to read /proc/self/auxv, try reading registers directly 38 | readARM64Registers() 39 | return 40 | } 41 | 42 | // HWCAP feature bits 43 | ARM64.HasFP = isSet(hwCap, hwcap_FP) 44 | ARM64.HasASIMD = isSet(hwCap, hwcap_ASIMD) 45 | ARM64.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) 46 | ARM64.HasAES = isSet(hwCap, hwcap_AES) 47 | ARM64.HasPMULL = isSet(hwCap, hwcap_PMULL) 48 | ARM64.HasSHA1 = isSet(hwCap, hwcap_SHA1) 49 | ARM64.HasSHA2 = isSet(hwCap, hwcap_SHA2) 50 | ARM64.HasCRC32 = isSet(hwCap, hwcap_CRC32) 51 | ARM64.HasATOMICS = isSet(hwCap, hwcap_ATOMICS) 52 | ARM64.HasFPHP = isSet(hwCap, hwcap_FPHP) 53 | ARM64.HasASIMDHP = isSet(hwCap, hwcap_ASIMDHP) 54 | ARM64.HasCPUID = isSet(hwCap, hwcap_CPUID) 55 | ARM64.HasASIMDRDM = isSet(hwCap, hwcap_ASIMDRDM) 56 | ARM64.HasJSCVT = isSet(hwCap, hwcap_JSCVT) 57 | ARM64.HasFCMA = isSet(hwCap, hwcap_FCMA) 58 | ARM64.HasLRCPC = isSet(hwCap, hwcap_LRCPC) 59 | ARM64.HasDCPOP = isSet(hwCap, hwcap_DCPOP) 60 | ARM64.HasSHA3 = isSet(hwCap, hwcap_SHA3) 61 | ARM64.HasSM3 = isSet(hwCap, hwcap_SM3) 62 | ARM64.HasSM4 = isSet(hwCap, hwcap_SM4) 63 | ARM64.HasASIMDDP = isSet(hwCap, hwcap_ASIMDDP) 64 | ARM64.HasSHA512 = isSet(hwCap, hwcap_SHA512) 65 | ARM64.HasSVE = isSet(hwCap, hwcap_SVE) 66 | ARM64.HasASIMDFHM = isSet(hwCap, hwcap_ASIMDFHM) 67 | } 68 | 69 | func isSet(hwc uint, value uint) bool { 70 | return hwc&value != 0 71 | } 72 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build mips64 mips64le 6 | 7 | package cpu 8 | 9 | // HWCAP bits. These are exposed by the Linux kernel 5.4. 10 | const ( 11 | // CPU features 12 | hwcap_MIPS_MSA = 1 << 1 13 | ) 14 | 15 | func doinit() { 16 | // HWCAP feature bits 17 | MIPS64X.HasMSA = isSet(hwCap, hwcap_MIPS_MSA) 18 | } 19 | 20 | func isSet(hwc uint, value uint) bool { 21 | return hwc&value != 0 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build linux,!arm,!arm64,!mips64,!mips64le,!ppc64,!ppc64le,!s390x 6 | 7 | package cpu 8 | 9 | func doinit() {} 10 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build linux 6 | // +build ppc64 ppc64le 7 | 8 | package cpu 9 | 10 | // HWCAP/HWCAP2 bits. These are exposed by the kernel. 11 | const ( 12 | // ISA Level 13 | _PPC_FEATURE2_ARCH_2_07 = 0x80000000 14 | _PPC_FEATURE2_ARCH_3_00 = 0x00800000 15 | 16 | // CPU features 17 | _PPC_FEATURE2_DARN = 0x00200000 18 | _PPC_FEATURE2_SCV = 0x00100000 19 | ) 20 | 21 | func doinit() { 22 | // HWCAP2 feature bits 23 | PPC64.IsPOWER8 = isSet(hwCap2, _PPC_FEATURE2_ARCH_2_07) 24 | PPC64.IsPOWER9 = isSet(hwCap2, _PPC_FEATURE2_ARCH_3_00) 25 | PPC64.HasDARN = isSet(hwCap2, _PPC_FEATURE2_DARN) 26 | PPC64.HasSCV = isSet(hwCap2, _PPC_FEATURE2_SCV) 27 | } 28 | 29 | func isSet(hwc uint, value uint) bool { 30 | return hwc&value != 0 31 | } 32 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | const ( 8 | // bit mask values from /usr/include/bits/hwcap.h 9 | hwcap_ZARCH = 2 10 | hwcap_STFLE = 4 11 | hwcap_MSA = 8 12 | hwcap_LDISP = 16 13 | hwcap_EIMM = 32 14 | hwcap_DFP = 64 15 | hwcap_ETF3EH = 256 16 | hwcap_VX = 2048 17 | hwcap_VXE = 8192 18 | ) 19 | 20 | // bitIsSet reports whether the bit at index is set. The bit index 21 | // is in big endian order, so bit index 0 is the leftmost bit. 22 | func bitIsSet(bits []uint64, index uint) bool { 23 | return bits[index/64]&((1<<63)>>(index%64)) != 0 24 | } 25 | 26 | // function is the code for the named cryptographic function. 27 | type function uint8 28 | 29 | const ( 30 | // KM{,A,C,CTR} function codes 31 | aes128 function = 18 // AES-128 32 | aes192 function = 19 // AES-192 33 | aes256 function = 20 // AES-256 34 | 35 | // K{I,L}MD function codes 36 | sha1 function = 1 // SHA-1 37 | sha256 function = 2 // SHA-256 38 | sha512 function = 3 // SHA-512 39 | sha3_224 function = 32 // SHA3-224 40 | sha3_256 function = 33 // SHA3-256 41 | sha3_384 function = 34 // SHA3-384 42 | sha3_512 function = 35 // SHA3-512 43 | shake128 function = 36 // SHAKE-128 44 | shake256 function = 37 // SHAKE-256 45 | 46 | // KLMD function codes 47 | ghash function = 65 // GHASH 48 | ) 49 | 50 | // queryResult contains the result of a Query function 51 | // call. Bits are numbered in big endian order so the 52 | // leftmost bit (the MSB) is at index 0. 53 | type queryResult struct { 54 | bits [2]uint64 55 | } 56 | 57 | // Has reports whether the given functions are present. 58 | func (q *queryResult) Has(fns ...function) bool { 59 | if len(fns) == 0 { 60 | panic("no function codes provided") 61 | } 62 | for _, f := range fns { 63 | if !bitIsSet(q.bits[:], uint(f)) { 64 | return false 65 | } 66 | } 67 | return true 68 | } 69 | 70 | // facility is a bit index for the named facility. 71 | type facility uint8 72 | 73 | const ( 74 | // cryptography facilities 75 | msa4 facility = 77 // message-security-assist extension 4 76 | msa8 facility = 146 // message-security-assist extension 8 77 | ) 78 | 79 | // facilityList contains the result of an STFLE call. 80 | // Bits are numbered in big endian order so the 81 | // leftmost bit (the MSB) is at index 0. 82 | type facilityList struct { 83 | bits [4]uint64 84 | } 85 | 86 | // Has reports whether the given facilities are present. 87 | func (s *facilityList) Has(fs ...facility) bool { 88 | if len(fs) == 0 { 89 | panic("no facility bits provided") 90 | } 91 | for _, f := range fs { 92 | if !bitIsSet(s.bits[:], uint(f)) { 93 | return false 94 | } 95 | } 96 | return true 97 | } 98 | 99 | func doinit() { 100 | // test HWCAP bit vector 101 | has := func(featureMask uint) bool { 102 | return hwCap&featureMask == featureMask 103 | } 104 | 105 | // mandatory 106 | S390X.HasZARCH = has(hwcap_ZARCH) 107 | 108 | // optional 109 | S390X.HasSTFLE = has(hwcap_STFLE) 110 | S390X.HasLDISP = has(hwcap_LDISP) 111 | S390X.HasEIMM = has(hwcap_EIMM) 112 | S390X.HasETF3EH = has(hwcap_ETF3EH) 113 | S390X.HasDFP = has(hwcap_DFP) 114 | S390X.HasMSA = has(hwcap_MSA) 115 | S390X.HasVX = has(hwcap_VX) 116 | if S390X.HasVX { 117 | S390X.HasVXE = has(hwcap_VXE) 118 | } 119 | 120 | // We need implementations of stfle, km and so on 121 | // to detect cryptographic features. 122 | if !haveAsmFunctions() { 123 | return 124 | } 125 | 126 | // optional cryptographic functions 127 | if S390X.HasMSA { 128 | aes := []function{aes128, aes192, aes256} 129 | 130 | // cipher message 131 | km, kmc := kmQuery(), kmcQuery() 132 | S390X.HasAES = km.Has(aes...) 133 | S390X.HasAESCBC = kmc.Has(aes...) 134 | if S390X.HasSTFLE { 135 | facilities := stfle() 136 | if facilities.Has(msa4) { 137 | kmctr := kmctrQuery() 138 | S390X.HasAESCTR = kmctr.Has(aes...) 139 | } 140 | if facilities.Has(msa8) { 141 | kma := kmaQuery() 142 | S390X.HasAESGCM = kma.Has(aes...) 143 | } 144 | } 145 | 146 | // compute message digest 147 | kimd := kimdQuery() // intermediate (no padding) 148 | klmd := klmdQuery() // last (padding) 149 | S390X.HasSHA1 = kimd.Has(sha1) && klmd.Has(sha1) 150 | S390X.HasSHA256 = kimd.Has(sha256) && klmd.Has(sha256) 151 | S390X.HasSHA512 = kimd.Has(sha512) && klmd.Has(sha512) 152 | S390X.HasGHASH = kimd.Has(ghash) // KLMD-GHASH does not exist 153 | sha3 := []function{ 154 | sha3_224, sha3_256, sha3_384, sha3_512, 155 | shake128, shake256, 156 | } 157 | S390X.HasSHA3 = kimd.Has(sha3...) && klmd.Has(sha3...) 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_mips64x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build mips64 mips64le 6 | 7 | package cpu 8 | 9 | const cacheLineSize = 32 10 | 11 | func initOptions() { 12 | options = []option{ 13 | {Name: "msa", Feature: &MIPS64X.HasMSA}, 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_mipsx.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build mips mipsle 6 | 7 | package cpu 8 | 9 | const cacheLineSize = 32 10 | 11 | func initOptions() {} 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_other_arm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !linux,arm 6 | 7 | package cpu 8 | 9 | func archInit() {} 10 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_other_arm64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !linux,arm64 6 | 7 | package cpu 8 | 9 | func doinit() {} 10 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_ppc64x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build ppc64 ppc64le 6 | 7 | package cpu 8 | 9 | const cacheLineSize = 128 10 | 11 | func initOptions() { 12 | options = []option{ 13 | {Name: "darn", Feature: &PPC64.HasDARN}, 14 | {Name: "scv", Feature: &PPC64.HasSCV}, 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_riscv64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build riscv64 6 | 7 | package cpu 8 | 9 | const cacheLineSize = 32 10 | 11 | func initOptions() {} 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_s390x.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu 6 | 7 | const cacheLineSize = 256 8 | 9 | func initOptions() { 10 | options = []option{ 11 | {Name: "zarch", Feature: &S390X.HasZARCH}, 12 | {Name: "stfle", Feature: &S390X.HasSTFLE}, 13 | {Name: "ldisp", Feature: &S390X.HasLDISP}, 14 | {Name: "eimm", Feature: &S390X.HasEIMM}, 15 | {Name: "dfp", Feature: &S390X.HasDFP}, 16 | {Name: "etf3eh", Feature: &S390X.HasETF3EH}, 17 | {Name: "msa", Feature: &S390X.HasMSA}, 18 | {Name: "aes", Feature: &S390X.HasAES}, 19 | {Name: "aescbc", Feature: &S390X.HasAESCBC}, 20 | {Name: "aesctr", Feature: &S390X.HasAESCTR}, 21 | {Name: "aesgcm", Feature: &S390X.HasAESGCM}, 22 | {Name: "ghash", Feature: &S390X.HasGHASH}, 23 | {Name: "sha1", Feature: &S390X.HasSHA1}, 24 | {Name: "sha256", Feature: &S390X.HasSHA256}, 25 | {Name: "sha3", Feature: &S390X.HasSHA3}, 26 | {Name: "sha512", Feature: &S390X.HasSHA512}, 27 | {Name: "vx", Feature: &S390X.HasVX}, 28 | {Name: "vxe", Feature: &S390X.HasVXE}, 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_s390x.s: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !gccgo 6 | 7 | #include "textflag.h" 8 | 9 | // func stfle() facilityList 10 | TEXT ·stfle(SB), NOSPLIT|NOFRAME, $0-32 11 | MOVD $ret+0(FP), R1 12 | MOVD $3, R0 // last doubleword index to store 13 | XC $32, (R1), (R1) // clear 4 doublewords (32 bytes) 14 | WORD $0xb2b01000 // store facility list extended (STFLE) 15 | RET 16 | 17 | // func kmQuery() queryResult 18 | TEXT ·kmQuery(SB), NOSPLIT|NOFRAME, $0-16 19 | MOVD $0, R0 // set function code to 0 (KM-Query) 20 | MOVD $ret+0(FP), R1 // address of 16-byte return value 21 | WORD $0xB92E0024 // cipher message (KM) 22 | RET 23 | 24 | // func kmcQuery() queryResult 25 | TEXT ·kmcQuery(SB), NOSPLIT|NOFRAME, $0-16 26 | MOVD $0, R0 // set function code to 0 (KMC-Query) 27 | MOVD $ret+0(FP), R1 // address of 16-byte return value 28 | WORD $0xB92F0024 // cipher message with chaining (KMC) 29 | RET 30 | 31 | // func kmctrQuery() queryResult 32 | TEXT ·kmctrQuery(SB), NOSPLIT|NOFRAME, $0-16 33 | MOVD $0, R0 // set function code to 0 (KMCTR-Query) 34 | MOVD $ret+0(FP), R1 // address of 16-byte return value 35 | WORD $0xB92D4024 // cipher message with counter (KMCTR) 36 | RET 37 | 38 | // func kmaQuery() queryResult 39 | TEXT ·kmaQuery(SB), NOSPLIT|NOFRAME, $0-16 40 | MOVD $0, R0 // set function code to 0 (KMA-Query) 41 | MOVD $ret+0(FP), R1 // address of 16-byte return value 42 | WORD $0xb9296024 // cipher message with authentication (KMA) 43 | RET 44 | 45 | // func kimdQuery() queryResult 46 | TEXT ·kimdQuery(SB), NOSPLIT|NOFRAME, $0-16 47 | MOVD $0, R0 // set function code to 0 (KIMD-Query) 48 | MOVD $ret+0(FP), R1 // address of 16-byte return value 49 | WORD $0xB93E0024 // compute intermediate message digest (KIMD) 50 | RET 51 | 52 | // func klmdQuery() queryResult 53 | TEXT ·klmdQuery(SB), NOSPLIT|NOFRAME, $0-16 54 | MOVD $0, R0 // set function code to 0 (KLMD-Query) 55 | MOVD $ret+0(FP), R1 // address of 16-byte return value 56 | WORD $0xB93F0024 // compute last message digest (KLMD) 57 | RET 58 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpu_test 6 | 7 | import ( 8 | "runtime" 9 | "testing" 10 | 11 | "golang.org/x/sys/cpu" 12 | ) 13 | 14 | func TestAMD64minimalFeatures(t *testing.T) { 15 | if runtime.GOARCH == "amd64" { 16 | if !cpu.Initialized { 17 | t.Fatal("Initialized expected true, got false") 18 | } 19 | if !cpu.X86.HasSSE2 { 20 | t.Fatal("HasSSE2 expected true, got false") 21 | } 22 | } 23 | } 24 | 25 | func TestAVX2hasAVX(t *testing.T) { 26 | if runtime.GOARCH == "amd64" { 27 | if cpu.X86.HasAVX2 && !cpu.X86.HasAVX { 28 | t.Fatal("HasAVX expected true, got false") 29 | } 30 | } 31 | } 32 | 33 | func TestARM64minimalFeatures(t *testing.T) { 34 | if runtime.GOARCH != "arm64" || runtime.GOOS == "darwin" { 35 | return 36 | } 37 | if !cpu.ARM64.HasASIMD { 38 | t.Fatal("HasASIMD expected true, got false") 39 | } 40 | if !cpu.ARM64.HasFP { 41 | t.Fatal("HasFP expected true, got false") 42 | } 43 | } 44 | 45 | func TestMIPS64Initialized(t *testing.T) { 46 | if runtime.GOARCH == "mips64" || runtime.GOARCH == "mips64le" { 47 | if !cpu.Initialized { 48 | t.Fatal("Initialized expected true, got false") 49 | } 50 | } 51 | } 52 | 53 | // On ppc64x, the ISA bit for POWER8 should always be set on POWER8 and beyond. 54 | func TestPPC64minimalFeatures(t *testing.T) { 55 | // Do not run this with gccgo on ppc64, as it doesn't have POWER8 as a minimum 56 | // requirement. 57 | if runtime.Compiler == "gccgo" && runtime.GOARCH == "ppc64" { 58 | t.Skip("gccgo does not require POWER8 on ppc64; skipping") 59 | } 60 | if runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" { 61 | if !cpu.PPC64.IsPOWER8 { 62 | t.Fatal("IsPOWER8 expected true, got false") 63 | } 64 | } 65 | } 66 | 67 | func TestS390X(t *testing.T) { 68 | if runtime.GOARCH != "s390x" { 69 | return 70 | } 71 | if testing.Verbose() { 72 | t.Logf("%+v\n", cpu.S390X) 73 | } 74 | // z/Architecture is mandatory 75 | if !cpu.S390X.HasZARCH { 76 | t.Error("HasZARCH expected true, got false") 77 | } 78 | // vector-enhancements require vector facility to be enabled 79 | if cpu.S390X.HasVXE && !cpu.S390X.HasVX { 80 | t.Error("HasVX expected true, got false (VXE is true)") 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_wasm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build wasm 6 | 7 | package cpu 8 | 9 | // We're compiling the cpu package for an unknown (software-abstracted) CPU. 10 | // Make CacheLinePad an empty struct and hope that the usual struct alignment 11 | // rules are good enough. 12 | 13 | const cacheLineSize = 0 14 | 15 | func initOptions() {} 16 | 17 | func archInit() {} 18 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/cpu_x86.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386 amd64 amd64p32 6 | 7 | package cpu 8 | 9 | import "runtime" 10 | 11 | const cacheLineSize = 64 12 | 13 | func initOptions() { 14 | options = []option{ 15 | {Name: "adx", Feature: &X86.HasADX}, 16 | {Name: "aes", Feature: &X86.HasAES}, 17 | {Name: "avx", Feature: &X86.HasAVX}, 18 | {Name: "avx2", Feature: &X86.HasAVX2}, 19 | {Name: "bmi1", Feature: &X86.HasBMI1}, 20 | {Name: "bmi2", Feature: &X86.HasBMI2}, 21 | {Name: "erms", Feature: &X86.HasERMS}, 22 | {Name: "fma", Feature: &X86.HasFMA}, 23 | {Name: "osxsave", Feature: &X86.HasOSXSAVE}, 24 | {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, 25 | {Name: "popcnt", Feature: &X86.HasPOPCNT}, 26 | {Name: "rdrand", Feature: &X86.HasRDRAND}, 27 | {Name: "rdseed", Feature: &X86.HasRDSEED}, 28 | {Name: "sse3", Feature: &X86.HasSSE3}, 29 | {Name: "sse41", Feature: &X86.HasSSE41}, 30 | {Name: "sse42", Feature: &X86.HasSSE42}, 31 | {Name: "ssse3", Feature: &X86.HasSSSE3}, 32 | 33 | // These capabilities should always be enabled on amd64: 34 | {Name: "sse2", Feature: &X86.HasSSE2, Required: runtime.GOARCH == "amd64"}, 35 | } 36 | } 37 | 38 | func archInit() { 39 | 40 | Initialized = true 41 | 42 | maxID, _, _, _ := cpuid(0, 0) 43 | 44 | if maxID < 1 { 45 | return 46 | } 47 | 48 | _, _, ecx1, edx1 := cpuid(1, 0) 49 | X86.HasSSE2 = isSet(26, edx1) 50 | 51 | X86.HasSSE3 = isSet(0, ecx1) 52 | X86.HasPCLMULQDQ = isSet(1, ecx1) 53 | X86.HasSSSE3 = isSet(9, ecx1) 54 | X86.HasFMA = isSet(12, ecx1) 55 | X86.HasSSE41 = isSet(19, ecx1) 56 | X86.HasSSE42 = isSet(20, ecx1) 57 | X86.HasPOPCNT = isSet(23, ecx1) 58 | X86.HasAES = isSet(25, ecx1) 59 | X86.HasOSXSAVE = isSet(27, ecx1) 60 | X86.HasRDRAND = isSet(30, ecx1) 61 | 62 | osSupportsAVX := false 63 | // For XGETBV, OSXSAVE bit is required and sufficient. 64 | if X86.HasOSXSAVE { 65 | eax, _ := xgetbv() 66 | // Check if XMM and YMM registers have OS support. 67 | osSupportsAVX = isSet(1, eax) && isSet(2, eax) 68 | } 69 | 70 | X86.HasAVX = isSet(28, ecx1) && osSupportsAVX 71 | 72 | if maxID < 7 { 73 | return 74 | } 75 | 76 | _, ebx7, _, _ := cpuid(7, 0) 77 | X86.HasBMI1 = isSet(3, ebx7) 78 | X86.HasAVX2 = isSet(5, ebx7) && osSupportsAVX 79 | X86.HasBMI2 = isSet(8, ebx7) 80 | X86.HasERMS = isSet(9, ebx7) 81 | X86.HasRDSEED = isSet(18, ebx7) 82 | X86.HasADX = isSet(19, ebx7) 83 | 84 | } 85 | 86 | func isSet(bitpos uint, value uint32) bool { 87 | return value&(1<> 63)) 18 | ) 19 | 20 | // For those platforms don't have a 'cpuid' equivalent we use HWCAP/HWCAP2 21 | // These are initialized in cpu_$GOARCH.go 22 | // and should not be changed after they are initialized. 23 | var hwCap uint 24 | var hwCap2 uint 25 | 26 | func readHWCAP() error { 27 | buf, err := ioutil.ReadFile(procAuxv) 28 | if err != nil { 29 | // e.g. on android /proc/self/auxv is not accessible, so silently 30 | // ignore the error and leave Initialized = false. On some 31 | // architectures (e.g. arm64) doinit() implements a fallback 32 | // readout and will set Initialized = true again. 33 | return err 34 | } 35 | bo := hostByteOrder() 36 | for len(buf) >= 2*(uintSize/8) { 37 | var tag, val uint 38 | switch uintSize { 39 | case 32: 40 | tag = uint(bo.Uint32(buf[0:])) 41 | val = uint(bo.Uint32(buf[4:])) 42 | buf = buf[8:] 43 | case 64: 44 | tag = uint(bo.Uint64(buf[0:])) 45 | val = uint(bo.Uint64(buf[8:])) 46 | buf = buf[16:] 47 | } 48 | switch tag { 49 | case _AT_HWCAP: 50 | hwCap = val 51 | case _AT_HWCAP2: 52 | hwCap2 = val 53 | } 54 | } 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Recreate a getsystemcfg syscall handler instead of 6 | // using the one provided by x/sys/unix to avoid having 7 | // the dependency between them. (See golang.org/issue/32102) 8 | // Morever, this file will be used during the building of 9 | // gccgo's libgo and thus must not used a CGo method. 10 | 11 | // +build aix 12 | // +build gccgo 13 | 14 | package cpu 15 | 16 | import ( 17 | "syscall" 18 | ) 19 | 20 | //extern getsystemcfg 21 | func gccgoGetsystemcfg(label uint32) (r uint64) 22 | 23 | func callgetsystemcfg(label int) (r1 uintptr, e1 syscall.Errno) { 24 | r1 = uintptr(gccgoGetsystemcfg(uint32(label))) 25 | e1 = syscall.GetErrno() 26 | return 27 | } 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Minimal copy of x/sys/unix so the cpu package can make a 6 | // system call on AIX without depending on x/sys/unix. 7 | // (See golang.org/issue/32102) 8 | 9 | // +build aix,ppc64 10 | // +build !gccgo 11 | 12 | package cpu 13 | 14 | import ( 15 | "syscall" 16 | "unsafe" 17 | ) 18 | 19 | //go:cgo_import_dynamic libc_getsystemcfg getsystemcfg "libc.a/shr_64.o" 20 | 21 | //go:linkname libc_getsystemcfg libc_getsystemcfg 22 | 23 | type syscallFunc uintptr 24 | 25 | var libc_getsystemcfg syscallFunc 26 | 27 | type errno = syscall.Errno 28 | 29 | // Implemented in runtime/syscall_aix.go. 30 | func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) 31 | func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) 32 | 33 | func callgetsystemcfg(label int) (r1 uintptr, e1 errno) { 34 | r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_getsystemcfg)), 1, uintptr(label), 0, 0, 0, 0, 0) 35 | return 36 | } 37 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/README: -------------------------------------------------------------------------------- 1 | This repository holds the transition packages for the new Go 1.13 error values. 2 | See golang.org/design/29934-error-values. 3 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/adaptor.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "io" 11 | "reflect" 12 | "strconv" 13 | ) 14 | 15 | // FormatError calls the FormatError method of f with an errors.Printer 16 | // configured according to s and verb, and writes the result to s. 17 | func FormatError(f Formatter, s fmt.State, verb rune) { 18 | // Assuming this function is only called from the Format method, and given 19 | // that FormatError takes precedence over Format, it cannot be called from 20 | // any package that supports errors.Formatter. It is therefore safe to 21 | // disregard that State may be a specific printer implementation and use one 22 | // of our choice instead. 23 | 24 | // limitations: does not support printing error as Go struct. 25 | 26 | var ( 27 | sep = " " // separator before next error 28 | p = &state{State: s} 29 | direct = true 30 | ) 31 | 32 | var err error = f 33 | 34 | switch verb { 35 | // Note that this switch must match the preference order 36 | // for ordinary string printing (%#v before %+v, and so on). 37 | 38 | case 'v': 39 | if s.Flag('#') { 40 | if stringer, ok := err.(fmt.GoStringer); ok { 41 | io.WriteString(&p.buf, stringer.GoString()) 42 | goto exit 43 | } 44 | // proceed as if it were %v 45 | } else if s.Flag('+') { 46 | p.printDetail = true 47 | sep = "\n - " 48 | } 49 | case 's': 50 | case 'q', 'x', 'X': 51 | // Use an intermediate buffer in the rare cases that precision, 52 | // truncation, or one of the alternative verbs (q, x, and X) are 53 | // specified. 54 | direct = false 55 | 56 | default: 57 | p.buf.WriteString("%!") 58 | p.buf.WriteRune(verb) 59 | p.buf.WriteByte('(') 60 | switch { 61 | case err != nil: 62 | p.buf.WriteString(reflect.TypeOf(f).String()) 63 | default: 64 | p.buf.WriteString("") 65 | } 66 | p.buf.WriteByte(')') 67 | io.Copy(s, &p.buf) 68 | return 69 | } 70 | 71 | loop: 72 | for { 73 | switch v := err.(type) { 74 | case Formatter: 75 | err = v.FormatError((*printer)(p)) 76 | case fmt.Formatter: 77 | v.Format(p, 'v') 78 | break loop 79 | default: 80 | io.WriteString(&p.buf, v.Error()) 81 | break loop 82 | } 83 | if err == nil { 84 | break 85 | } 86 | if p.needColon || !p.printDetail { 87 | p.buf.WriteByte(':') 88 | p.needColon = false 89 | } 90 | p.buf.WriteString(sep) 91 | p.inDetail = false 92 | p.needNewline = false 93 | } 94 | 95 | exit: 96 | width, okW := s.Width() 97 | prec, okP := s.Precision() 98 | 99 | if !direct || (okW && width > 0) || okP { 100 | // Construct format string from State s. 101 | format := []byte{'%'} 102 | if s.Flag('-') { 103 | format = append(format, '-') 104 | } 105 | if s.Flag('+') { 106 | format = append(format, '+') 107 | } 108 | if s.Flag(' ') { 109 | format = append(format, ' ') 110 | } 111 | if okW { 112 | format = strconv.AppendInt(format, int64(width), 10) 113 | } 114 | if okP { 115 | format = append(format, '.') 116 | format = strconv.AppendInt(format, int64(prec), 10) 117 | } 118 | format = append(format, string(verb)...) 119 | fmt.Fprintf(s, string(format), p.buf.String()) 120 | } else { 121 | io.Copy(s, &p.buf) 122 | } 123 | } 124 | 125 | var detailSep = []byte("\n ") 126 | 127 | // state tracks error printing state. It implements fmt.State. 128 | type state struct { 129 | fmt.State 130 | buf bytes.Buffer 131 | 132 | printDetail bool 133 | inDetail bool 134 | needColon bool 135 | needNewline bool 136 | } 137 | 138 | func (s *state) Write(b []byte) (n int, err error) { 139 | if s.printDetail { 140 | if len(b) == 0 { 141 | return 0, nil 142 | } 143 | if s.inDetail && s.needColon { 144 | s.needNewline = true 145 | if b[0] == '\n' { 146 | b = b[1:] 147 | } 148 | } 149 | k := 0 150 | for i, c := range b { 151 | if s.needNewline { 152 | if s.inDetail && s.needColon { 153 | s.buf.WriteByte(':') 154 | s.needColon = false 155 | } 156 | s.buf.Write(detailSep) 157 | s.needNewline = false 158 | } 159 | if c == '\n' { 160 | s.buf.Write(b[k:i]) 161 | k = i + 1 162 | s.needNewline = true 163 | } 164 | } 165 | s.buf.Write(b[k:]) 166 | if !s.inDetail { 167 | s.needColon = true 168 | } 169 | } else if !s.inDetail { 170 | s.buf.Write(b) 171 | } 172 | return len(b), nil 173 | } 174 | 175 | // printer wraps a state to implement an xerrors.Printer. 176 | type printer state 177 | 178 | func (s *printer) Print(args ...interface{}) { 179 | if !s.inDetail || s.printDetail { 180 | fmt.Fprint((*state)(s), args...) 181 | } 182 | } 183 | 184 | func (s *printer) Printf(format string, args ...interface{}) { 185 | if !s.inDetail || s.printDetail { 186 | fmt.Fprintf((*state)(s), format, args...) 187 | } 188 | } 189 | 190 | func (s *printer) Detail() bool { 191 | s.inDetail = true 192 | return s.printDetail 193 | } 194 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/codereview.cfg: -------------------------------------------------------------------------------- 1 | issuerepo: golang/go 2 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package xerrors implements functions to manipulate errors. 6 | // 7 | // This package is based on the Go 2 proposal for error values: 8 | // https://golang.org/design/29934-error-values 9 | // 10 | // These functions were incorporated into the standard library's errors package 11 | // in Go 1.13: 12 | // - Is 13 | // - As 14 | // - Unwrap 15 | // 16 | // Also, Errorf's %w verb was incorporated into fmt.Errorf. 17 | // 18 | // Use this package to get equivalent behavior in all supported Go versions. 19 | // 20 | // No other features of this package were included in Go 1.13, and at present 21 | // there are no plans to include any of them. 22 | package xerrors // import "golang.org/x/xerrors" 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | import "fmt" 8 | 9 | // errorString is a trivial implementation of error. 10 | type errorString struct { 11 | s string 12 | frame Frame 13 | } 14 | 15 | // New returns an error that formats as the given text. 16 | // 17 | // The returned error contains a Frame set to the caller's location and 18 | // implements Formatter to show this information when printed with details. 19 | func New(text string) error { 20 | return &errorString{text, Caller(1)} 21 | } 22 | 23 | func (e *errorString) Error() string { 24 | return e.s 25 | } 26 | 27 | func (e *errorString) Format(s fmt.State, v rune) { FormatError(e, s, v) } 28 | 29 | func (e *errorString) FormatError(p Printer) (next error) { 30 | p.Print(e.s) 31 | e.frame.Format(p) 32 | return nil 33 | } 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/errors_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors_test 6 | 7 | import ( 8 | "fmt" 9 | "regexp" 10 | "testing" 11 | 12 | "golang.org/x/xerrors" 13 | ) 14 | 15 | func TestNewEqual(t *testing.T) { 16 | // Different allocations should not be equal. 17 | if xerrors.New("abc") == xerrors.New("abc") { 18 | t.Errorf(`New("abc") == New("abc")`) 19 | } 20 | if xerrors.New("abc") == xerrors.New("xyz") { 21 | t.Errorf(`New("abc") == New("xyz")`) 22 | } 23 | 24 | // Same allocation should be equal to itself (not crash). 25 | err := xerrors.New("jkl") 26 | if err != err { 27 | t.Errorf(`err != err`) 28 | } 29 | } 30 | 31 | func TestErrorMethod(t *testing.T) { 32 | err := xerrors.New("abc") 33 | if err.Error() != "abc" { 34 | t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc") 35 | } 36 | } 37 | 38 | func TestNewDetail(t *testing.T) { 39 | got := fmt.Sprintf("%+v", xerrors.New("error")) 40 | want := `(?s)error:.+errors_test.go:\d+` 41 | ok, err := regexp.MatchString(want, got) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | if !ok { 46 | t.Errorf(`fmt.Sprintf("%%+v", New("error")) = %q, want %q"`, got, want) 47 | } 48 | } 49 | 50 | func ExampleNew() { 51 | err := xerrors.New("emit macho dwarf: elf header corrupted") 52 | if err != nil { 53 | fmt.Print(err) 54 | } 55 | // Output: emit macho dwarf: elf header corrupted 56 | } 57 | 58 | // The fmt package's Errorf function lets us use the package's formatting 59 | // features to create descriptive error messages. 60 | func ExampleNew_errorf() { 61 | const name, id = "bimmler", 17 62 | err := fmt.Errorf("user %q (id %d) not found", name, id) 63 | if err != nil { 64 | fmt.Print(err) 65 | } 66 | // Output: user "bimmler" (id 17) not found 67 | } 68 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/example_As_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors_test 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | 11 | "golang.org/x/xerrors" 12 | ) 13 | 14 | func ExampleAs() { 15 | _, err := os.Open("non-existing") 16 | if err != nil { 17 | var pathError *os.PathError 18 | if xerrors.As(err, &pathError) { 19 | fmt.Println("Failed at path:", pathError.Path) 20 | } 21 | } 22 | 23 | // Output: 24 | // Failed at path: non-existing 25 | } 26 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/example_FormatError_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors_test 6 | 7 | import ( 8 | "fmt" 9 | 10 | "golang.org/x/xerrors" 11 | ) 12 | 13 | type MyError2 struct { 14 | Message string 15 | frame xerrors.Frame 16 | } 17 | 18 | func (m *MyError2) Error() string { 19 | return m.Message 20 | } 21 | 22 | func (m *MyError2) Format(f fmt.State, c rune) { // implements fmt.Formatter 23 | xerrors.FormatError(m, f, c) 24 | } 25 | 26 | func (m *MyError2) FormatError(p xerrors.Printer) error { // implements xerrors.Formatter 27 | p.Print(m.Message) 28 | if p.Detail() { 29 | m.frame.Format(p) 30 | } 31 | return nil 32 | } 33 | 34 | func ExampleFormatError() { 35 | err := &MyError2{Message: "oops", frame: xerrors.Caller(1)} 36 | fmt.Printf("%v\n", err) 37 | fmt.Println() 38 | fmt.Printf("%+v\n", err) 39 | } 40 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors_test 6 | 7 | import ( 8 | "fmt" 9 | "time" 10 | ) 11 | 12 | // MyError is an error implementation that includes a time and message. 13 | type MyError struct { 14 | When time.Time 15 | What string 16 | } 17 | 18 | func (e MyError) Error() string { 19 | return fmt.Sprintf("%v: %v", e.When, e.What) 20 | } 21 | 22 | func oops() error { 23 | return MyError{ 24 | time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC), 25 | "the file system has gone away", 26 | } 27 | } 28 | 29 | func Example() { 30 | if err := oops(); err != nil { 31 | fmt.Println(err) 32 | } 33 | // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away 34 | } 35 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/fmt_unexported_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | import "testing" 8 | 9 | func TestParsePrintfVerb(t *testing.T) { 10 | for _, test := range []struct { 11 | in string 12 | wantSize int 13 | wantW bool 14 | }{ 15 | {"", 0, false}, 16 | {"%", 1, false}, 17 | {"%3.1", 4, false}, 18 | {"%w", 2, true}, 19 | {"%v", 2, false}, 20 | {"%3.*[4]d", 8, false}, 21 | } { 22 | gotSize, gotW := parsePrintfVerb(test.in) 23 | if gotSize != test.wantSize || gotW != test.wantW { 24 | t.Errorf("parsePrintfVerb(%q) = (%d, %t), want (%d, %t)", 25 | test.in, gotSize, gotW, test.wantSize, test.wantW) 26 | } 27 | } 28 | } 29 | 30 | func TestParsePercentW(t *testing.T) { 31 | for _, test := range []struct { 32 | in string 33 | wantIdx int 34 | wantFormat string 35 | wantOK bool 36 | }{ 37 | {"", -1, "", true}, 38 | {"%", -1, "%", true}, 39 | {"%w", 0, "%v", true}, 40 | {"%w%w", 0, "%v%v", false}, 41 | {"%3.2s %+q %% %w %#v", 2, "%3.2s %+q %% %v %#v", true}, 42 | {"%3.2s %w %% %w %#v", 1, "%3.2s %v %% %v %#v", false}, 43 | } { 44 | gotIdx, gotFormat, gotOK := parsePercentW(test.in) 45 | if gotIdx != test.wantIdx || gotFormat != test.wantFormat || gotOK != test.wantOK { 46 | t.Errorf("parsePercentW(%q) = (%d, %q, %t), want (%d, %q, %t)", 47 | test.in, gotIdx, gotFormat, gotOK, test.wantIdx, test.wantFormat, test.wantOK) 48 | 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/format.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | // A Formatter formats error messages. 8 | type Formatter interface { 9 | error 10 | 11 | // FormatError prints the receiver's first error and returns the next error in 12 | // the error chain, if any. 13 | FormatError(p Printer) (next error) 14 | } 15 | 16 | // A Printer formats error messages. 17 | // 18 | // The most common implementation of Printer is the one provided by package fmt 19 | // during Printf (as of Go 1.13). Localization packages such as golang.org/x/text/message 20 | // typically provide their own implementations. 21 | type Printer interface { 22 | // Print appends args to the message output. 23 | Print(args ...interface{}) 24 | 25 | // Printf writes a formatted string. 26 | Printf(format string, args ...interface{}) 27 | 28 | // Detail reports whether error detail is requested. 29 | // After the first call to Detail, all text written to the Printer 30 | // is formatted as additional detail, or ignored when 31 | // detail has not been requested. 32 | // If Detail returns false, the caller can avoid printing the detail at all. 33 | Detail() bool 34 | } 35 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/frame.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | import ( 8 | "runtime" 9 | ) 10 | 11 | // A Frame contains part of a call stack. 12 | type Frame struct { 13 | // Make room for three PCs: the one we were asked for, what it called, 14 | // and possibly a PC for skipPleaseUseCallersFrames. See: 15 | // https://go.googlesource.com/go/+/032678e0fb/src/runtime/extern.go#169 16 | frames [3]uintptr 17 | } 18 | 19 | // Caller returns a Frame that describes a frame on the caller's stack. 20 | // The argument skip is the number of frames to skip over. 21 | // Caller(0) returns the frame for the caller of Caller. 22 | func Caller(skip int) Frame { 23 | var s Frame 24 | runtime.Callers(skip+1, s.frames[:]) 25 | return s 26 | } 27 | 28 | // location reports the file, line, and function of a frame. 29 | // 30 | // The returned function may be "" even if file and line are not. 31 | func (f Frame) location() (function, file string, line int) { 32 | frames := runtime.CallersFrames(f.frames[:]) 33 | if _, ok := frames.Next(); !ok { 34 | return "", "", 0 35 | } 36 | fr, ok := frames.Next() 37 | if !ok { 38 | return "", "", 0 39 | } 40 | return fr.Function, fr.File, fr.Line 41 | } 42 | 43 | // Format prints the stack as error detail. 44 | // It should be called from an error's Format implementation 45 | // after printing any other error detail. 46 | func (f Frame) Format(p Printer) { 47 | if p.Detail() { 48 | function, file, line := f.location() 49 | if function != "" { 50 | p.Printf("%s\n ", function) 51 | } 52 | if file != "" { 53 | p.Printf("%s:%d\n", file, line) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/go.mod: -------------------------------------------------------------------------------- 1 | module golang.org/x/xerrors 2 | 3 | go 1.11 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/internal/internal.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package internal 6 | 7 | // EnableTrace indicates whether stack information should be recorded in errors. 8 | var EnableTrace = true 9 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/stack_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors_test 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "math/big" 11 | "testing" 12 | 13 | "golang.org/x/xerrors" 14 | "golang.org/x/xerrors/internal" 15 | ) 16 | 17 | type myType struct{} 18 | 19 | func (myType) Format(s fmt.State, v rune) { 20 | s.Write(bytes.Repeat([]byte("Hi! "), 10)) 21 | } 22 | 23 | func BenchmarkErrorf(b *testing.B) { 24 | err := xerrors.New("foo") 25 | // pi := big.NewFloat(3.14) // Something expensive. 26 | num := big.NewInt(5) 27 | args := func(a ...interface{}) []interface{} { return a } 28 | benchCases := []struct { 29 | name string 30 | format string 31 | args []interface{} 32 | }{ 33 | {"no_format", "msg: %v", args(err)}, 34 | {"with_format", "failed %d times: %v", args(5, err)}, 35 | {"method: mytype", "pi: %v", args("myfile.go", myType{}, err)}, 36 | {"method: number", "pi: %v", args("myfile.go", num, err)}, 37 | } 38 | for _, bc := range benchCases { 39 | b.Run(bc.name, func(b *testing.B) { 40 | b.Run("ExpWithTrace", func(b *testing.B) { 41 | for i := 0; i < b.N; i++ { 42 | xerrors.Errorf(bc.format, bc.args...) 43 | } 44 | }) 45 | b.Run("ExpNoTrace", func(b *testing.B) { 46 | internal.EnableTrace = false 47 | defer func() { internal.EnableTrace = true }() 48 | 49 | for i := 0; i < b.N; i++ { 50 | xerrors.Errorf(bc.format, bc.args...) 51 | } 52 | }) 53 | b.Run("Core", func(b *testing.B) { 54 | for i := 0; i < b.N; i++ { 55 | fmt.Errorf(bc.format, bc.args...) 56 | } 57 | }) 58 | }) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/wrap.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xerrors 6 | 7 | import ( 8 | "reflect" 9 | ) 10 | 11 | // A Wrapper provides context around another error. 12 | type Wrapper interface { 13 | // Unwrap returns the next error in the error chain. 14 | // If there is no next error, Unwrap returns nil. 15 | Unwrap() error 16 | } 17 | 18 | // Opaque returns an error with the same error formatting as err 19 | // but that does not match err and cannot be unwrapped. 20 | func Opaque(err error) error { 21 | return noWrapper{err} 22 | } 23 | 24 | type noWrapper struct { 25 | error 26 | } 27 | 28 | func (e noWrapper) FormatError(p Printer) (next error) { 29 | if f, ok := e.error.(Formatter); ok { 30 | return f.FormatError(p) 31 | } 32 | p.Print(e.error) 33 | return nil 34 | } 35 | 36 | // Unwrap returns the result of calling the Unwrap method on err, if err implements 37 | // Unwrap. Otherwise, Unwrap returns nil. 38 | func Unwrap(err error) error { 39 | u, ok := err.(Wrapper) 40 | if !ok { 41 | return nil 42 | } 43 | return u.Unwrap() 44 | } 45 | 46 | // Is reports whether any error in err's chain matches target. 47 | // 48 | // An error is considered to match a target if it is equal to that target or if 49 | // it implements a method Is(error) bool such that Is(target) returns true. 50 | func Is(err, target error) bool { 51 | if target == nil { 52 | return err == target 53 | } 54 | 55 | isComparable := reflect.TypeOf(target).Comparable() 56 | for { 57 | if isComparable && err == target { 58 | return true 59 | } 60 | if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) { 61 | return true 62 | } 63 | // TODO: consider supporing target.Is(err). This would allow 64 | // user-definable predicates, but also may allow for coping with sloppy 65 | // APIs, thereby making it easier to get away with them. 66 | if err = Unwrap(err); err == nil { 67 | return false 68 | } 69 | } 70 | } 71 | 72 | // As finds the first error in err's chain that matches the type to which target 73 | // points, and if so, sets the target to its value and returns true. An error 74 | // matches a type if it is assignable to the target type, or if it has a method 75 | // As(interface{}) bool such that As(target) returns true. As will panic if target 76 | // is not a non-nil pointer to a type which implements error or is of interface type. 77 | // 78 | // The As method should set the target to its value and return true if err 79 | // matches the type to which target points. 80 | func As(err error, target interface{}) bool { 81 | if target == nil { 82 | panic("errors: target cannot be nil") 83 | } 84 | val := reflect.ValueOf(target) 85 | typ := val.Type() 86 | if typ.Kind() != reflect.Ptr || val.IsNil() { 87 | panic("errors: target must be a non-nil pointer") 88 | } 89 | if e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) { 90 | panic("errors: *target must be interface or implement error") 91 | } 92 | targetType := typ.Elem() 93 | for err != nil { 94 | if reflect.TypeOf(err).AssignableTo(targetType) { 95 | val.Elem().Set(reflect.ValueOf(err)) 96 | return true 97 | } 98 | if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) { 99 | return true 100 | } 101 | err = Unwrap(err) 102 | } 103 | return false 104 | } 105 | 106 | var errorType = reflect.TypeOf((*error)(nil)).Elem() 107 | -------------------------------------------------------------------------------- /vendor/golang.org/x/xerrors/wrap_113_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //+build go1.13 6 | 7 | package xerrors_test 8 | 9 | import ( 10 | "errors" 11 | "testing" 12 | 13 | "golang.org/x/xerrors" 14 | ) 15 | 16 | func TestErrorsIs(t *testing.T) { 17 | var errSentinel = errors.New("sentinel") 18 | 19 | got := errors.Is(xerrors.Errorf("%w", errSentinel), errSentinel) 20 | if !got { 21 | t.Error("got false, want true") 22 | } 23 | 24 | got = errors.Is(xerrors.Errorf("%w: %s", errSentinel, "foo"), errSentinel) 25 | if !got { 26 | t.Error("got false, want true") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4 5 | - 1.5 6 | - 1.6 7 | - 1.7 8 | - 1.8 9 | - 1.9 10 | - tip 11 | 12 | go_import_path: gopkg.in/yaml.v2 13 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/LICENSE.libyaml: -------------------------------------------------------------------------------- 1 | The following files were ported to Go from C files of libyaml, and thus 2 | are still covered by their original copyright and license: 3 | 4 | apic.go 5 | emitterc.go 6 | parserc.go 7 | readerc.go 8 | scannerc.go 9 | writerc.go 10 | yamlh.go 11 | yamlprivateh.go 12 | 13 | Copyright (c) 2006 Kirill Simonov 14 | 15 | Permission is hereby granted, free of charge, to any person obtaining a copy of 16 | this software and associated documentation files (the "Software"), to deal in 17 | the Software without restriction, including without limitation the rights to 18 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 19 | of the Software, and to permit persons to whom the Software is furnished to do 20 | so, subject to the following conditions: 21 | 22 | The above copyright notice and this permission notice shall be included in all 23 | copies or substantial portions of the Software. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2011-2016 Canonical Ltd. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/README.md: -------------------------------------------------------------------------------- 1 | # YAML support for the Go language 2 | 3 | Introduction 4 | ------------ 5 | 6 | The yaml package enables Go programs to comfortably encode and decode YAML 7 | values. It was developed within [Canonical](https://www.canonical.com) as 8 | part of the [juju](https://juju.ubuntu.com) project, and is based on a 9 | pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) 10 | C library to parse and generate YAML data quickly and reliably. 11 | 12 | Compatibility 13 | ------------- 14 | 15 | The yaml package supports most of YAML 1.1 and 1.2, including support for 16 | anchors, tags, map merging, etc. Multi-document unmarshalling is not yet 17 | implemented, and base-60 floats from YAML 1.1 are purposefully not 18 | supported since they're a poor design and are gone in YAML 1.2. 19 | 20 | Installation and usage 21 | ---------------------- 22 | 23 | The import path for the package is *gopkg.in/yaml.v2*. 24 | 25 | To install it, run: 26 | 27 | go get gopkg.in/yaml.v2 28 | 29 | API documentation 30 | ----------------- 31 | 32 | If opened in a browser, the import path itself leads to the API documentation: 33 | 34 | * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) 35 | 36 | API stability 37 | ------------- 38 | 39 | The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). 40 | 41 | 42 | License 43 | ------- 44 | 45 | The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. 46 | 47 | 48 | Example 49 | ------- 50 | 51 | ```Go 52 | package main 53 | 54 | import ( 55 | "fmt" 56 | "log" 57 | 58 | "gopkg.in/yaml.v2" 59 | ) 60 | 61 | var data = ` 62 | a: Easy! 63 | b: 64 | c: 2 65 | d: [3, 4] 66 | ` 67 | 68 | // Note: struct fields must be public in order for unmarshal to 69 | // correctly populate the data. 70 | type T struct { 71 | A string 72 | B struct { 73 | RenamedC int `yaml:"c"` 74 | D []int `yaml:",flow"` 75 | } 76 | } 77 | 78 | func main() { 79 | t := T{} 80 | 81 | err := yaml.Unmarshal([]byte(data), &t) 82 | if err != nil { 83 | log.Fatalf("error: %v", err) 84 | } 85 | fmt.Printf("--- t:\n%v\n\n", t) 86 | 87 | d, err := yaml.Marshal(&t) 88 | if err != nil { 89 | log.Fatalf("error: %v", err) 90 | } 91 | fmt.Printf("--- t dump:\n%s\n\n", string(d)) 92 | 93 | m := make(map[interface{}]interface{}) 94 | 95 | err = yaml.Unmarshal([]byte(data), &m) 96 | if err != nil { 97 | log.Fatalf("error: %v", err) 98 | } 99 | fmt.Printf("--- m:\n%v\n\n", m) 100 | 101 | d, err = yaml.Marshal(&m) 102 | if err != nil { 103 | log.Fatalf("error: %v", err) 104 | } 105 | fmt.Printf("--- m dump:\n%s\n\n", string(d)) 106 | } 107 | ``` 108 | 109 | This example will generate the following output: 110 | 111 | ``` 112 | --- t: 113 | {Easy! {2 [3 4]}} 114 | 115 | --- t dump: 116 | a: Easy! 117 | b: 118 | c: 2 119 | d: [3, 4] 120 | 121 | 122 | --- m: 123 | map[a:Easy! b:map[c:2 d:[3 4]]] 124 | 125 | --- m dump: 126 | a: Easy! 127 | b: 128 | c: 2 129 | d: 130 | - 3 131 | - 4 132 | ``` 133 | 134 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/example_embedded_test.go: -------------------------------------------------------------------------------- 1 | package yaml_test 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "gopkg.in/yaml.v2" 8 | ) 9 | 10 | // An example showing how to unmarshal embedded 11 | // structs from YAML. 12 | 13 | type StructA struct { 14 | A string `yaml:"a"` 15 | } 16 | 17 | type StructB struct { 18 | // Embedded structs are not treated as embedded in YAML by default. To do that, 19 | // add the ",inline" annotation below 20 | StructA `yaml:",inline"` 21 | B string `yaml:"b"` 22 | } 23 | 24 | var data = ` 25 | a: a string from struct A 26 | b: a string from struct B 27 | ` 28 | 29 | func ExampleUnmarshal_embedded() { 30 | var b StructB 31 | 32 | err := yaml.Unmarshal([]byte(data), &b) 33 | if err != nil { 34 | log.Fatalf("cannot unmarshal data: %v", err) 35 | } 36 | fmt.Println(b.A) 37 | fmt.Println(b.B) 38 | // Output: 39 | // a string from struct A 40 | // a string from struct B 41 | } 42 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/go.mod: -------------------------------------------------------------------------------- 1 | module "gopkg.in/yaml.v2" 2 | 3 | require ( 4 | "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 5 | ) 6 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/limit_test.go: -------------------------------------------------------------------------------- 1 | package yaml_test 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | 7 | . "gopkg.in/check.v1" 8 | "gopkg.in/yaml.v2" 9 | ) 10 | 11 | var limitTests = []struct { 12 | name string 13 | data []byte 14 | error string 15 | }{ 16 | { 17 | name: "1000kb of maps with 100 aliases", 18 | data: []byte(`{a: &a [{a}` + strings.Repeat(`,{a}`, 1000*1024/4-100) + `], b: &b [*a` + strings.Repeat(`,*a`, 99) + `]}`), 19 | error: "yaml: document contains excessive aliasing", 20 | }, { 21 | name: "1000kb of deeply nested slices", 22 | data: []byte(strings.Repeat(`[`, 1000*1024)), 23 | error: "yaml: exceeded max depth of 10000", 24 | }, { 25 | name: "1000kb of deeply nested maps", 26 | data: []byte("x: " + strings.Repeat(`{`, 1000*1024)), 27 | error: "yaml: exceeded max depth of 10000", 28 | }, { 29 | name: "1000kb of deeply nested indents", 30 | data: []byte(strings.Repeat(`- `, 1000*1024)), 31 | error: "yaml: exceeded max depth of 10000", 32 | }, { 33 | name: "1000kb of 1000-indent lines", 34 | data: []byte(strings.Repeat(strings.Repeat(`- `, 1000)+"\n", 1024/2)), 35 | }, 36 | {name: "1kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 1*1024/4-1) + `]`)}, 37 | {name: "10kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 10*1024/4-1) + `]`)}, 38 | {name: "100kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 100*1024/4-1) + `]`)}, 39 | {name: "1000kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 1000*1024/4-1) + `]`)}, 40 | } 41 | 42 | func (s *S) TestLimits(c *C) { 43 | if testing.Short() { 44 | return 45 | } 46 | for _, tc := range limitTests { 47 | var v interface{} 48 | err := yaml.Unmarshal(tc.data, &v) 49 | if len(tc.error) > 0 { 50 | c.Assert(err, ErrorMatches, tc.error, Commentf("testcase: %s", tc.name)) 51 | } else { 52 | c.Assert(err, IsNil, Commentf("testcase: %s", tc.name)) 53 | } 54 | } 55 | } 56 | 57 | func Benchmark1000KB100Aliases(b *testing.B) { 58 | benchmark(b, "1000kb of maps with 100 aliases") 59 | } 60 | func Benchmark1000KBDeeplyNestedSlices(b *testing.B) { 61 | benchmark(b, "1000kb of deeply nested slices") 62 | } 63 | func Benchmark1000KBDeeplyNestedMaps(b *testing.B) { 64 | benchmark(b, "1000kb of deeply nested maps") 65 | } 66 | func Benchmark1000KBDeeplyNestedIndents(b *testing.B) { 67 | benchmark(b, "1000kb of deeply nested indents") 68 | } 69 | func Benchmark1000KB1000IndentLines(b *testing.B) { 70 | benchmark(b, "1000kb of 1000-indent lines") 71 | } 72 | func Benchmark1KBMaps(b *testing.B) { 73 | benchmark(b, "1kb of maps") 74 | } 75 | func Benchmark10KBMaps(b *testing.B) { 76 | benchmark(b, "10kb of maps") 77 | } 78 | func Benchmark100KBMaps(b *testing.B) { 79 | benchmark(b, "100kb of maps") 80 | } 81 | func Benchmark1000KBMaps(b *testing.B) { 82 | benchmark(b, "1000kb of maps") 83 | } 84 | 85 | func benchmark(b *testing.B, name string) { 86 | for _, t := range limitTests { 87 | if t.name != name { 88 | continue 89 | } 90 | 91 | b.ResetTimer() 92 | 93 | for i := 0; i < b.N; i++ { 94 | var v interface{} 95 | err := yaml.Unmarshal(t.data, &v) 96 | if len(t.error) > 0 { 97 | if err == nil { 98 | b.Errorf("expected error, got none") 99 | } else if err.Error() != t.error { 100 | b.Errorf("expected error '%s', got '%s'", t.error, err.Error()) 101 | } 102 | } else { 103 | if err != nil { 104 | b.Errorf("unexpected error: %v", err) 105 | } 106 | } 107 | } 108 | 109 | return 110 | } 111 | 112 | b.Errorf("testcase %q not found", name) 113 | } 114 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/sorter.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "reflect" 5 | "unicode" 6 | ) 7 | 8 | type keyList []reflect.Value 9 | 10 | func (l keyList) Len() int { return len(l) } 11 | func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } 12 | func (l keyList) Less(i, j int) bool { 13 | a := l[i] 14 | b := l[j] 15 | ak := a.Kind() 16 | bk := b.Kind() 17 | for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { 18 | a = a.Elem() 19 | ak = a.Kind() 20 | } 21 | for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { 22 | b = b.Elem() 23 | bk = b.Kind() 24 | } 25 | af, aok := keyFloat(a) 26 | bf, bok := keyFloat(b) 27 | if aok && bok { 28 | if af != bf { 29 | return af < bf 30 | } 31 | if ak != bk { 32 | return ak < bk 33 | } 34 | return numLess(a, b) 35 | } 36 | if ak != reflect.String || bk != reflect.String { 37 | return ak < bk 38 | } 39 | ar, br := []rune(a.String()), []rune(b.String()) 40 | for i := 0; i < len(ar) && i < len(br); i++ { 41 | if ar[i] == br[i] { 42 | continue 43 | } 44 | al := unicode.IsLetter(ar[i]) 45 | bl := unicode.IsLetter(br[i]) 46 | if al && bl { 47 | return ar[i] < br[i] 48 | } 49 | if al || bl { 50 | return bl 51 | } 52 | var ai, bi int 53 | var an, bn int64 54 | if ar[i] == '0' || br[i] == '0' { 55 | for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { 56 | if ar[j] != '0' { 57 | an = 1 58 | bn = 1 59 | break 60 | } 61 | } 62 | } 63 | for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { 64 | an = an*10 + int64(ar[ai]-'0') 65 | } 66 | for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { 67 | bn = bn*10 + int64(br[bi]-'0') 68 | } 69 | if an != bn { 70 | return an < bn 71 | } 72 | if ai != bi { 73 | return ai < bi 74 | } 75 | return ar[i] < br[i] 76 | } 77 | return len(ar) < len(br) 78 | } 79 | 80 | // keyFloat returns a float value for v if it is a number/bool 81 | // and whether it is a number/bool or not. 82 | func keyFloat(v reflect.Value) (f float64, ok bool) { 83 | switch v.Kind() { 84 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 85 | return float64(v.Int()), true 86 | case reflect.Float32, reflect.Float64: 87 | return v.Float(), true 88 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 89 | return float64(v.Uint()), true 90 | case reflect.Bool: 91 | if v.Bool() { 92 | return 1, true 93 | } 94 | return 0, true 95 | } 96 | return 0, false 97 | } 98 | 99 | // numLess returns whether a < b. 100 | // a and b must necessarily have the same kind. 101 | func numLess(a, b reflect.Value) bool { 102 | switch a.Kind() { 103 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 104 | return a.Int() < b.Int() 105 | case reflect.Float32, reflect.Float64: 106 | return a.Float() < b.Float() 107 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 108 | return a.Uint() < b.Uint() 109 | case reflect.Bool: 110 | return !a.Bool() && b.Bool() 111 | } 112 | panic("not a number") 113 | } 114 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/suite_test.go: -------------------------------------------------------------------------------- 1 | package yaml_test 2 | 3 | import ( 4 | . "gopkg.in/check.v1" 5 | "testing" 6 | ) 7 | 8 | func Test(t *testing.T) { TestingT(t) } 9 | 10 | type S struct{} 11 | 12 | var _ = Suite(&S{}) 13 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/writerc.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | // Set the writer error and return false. 4 | func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { 5 | emitter.error = yaml_WRITER_ERROR 6 | emitter.problem = problem 7 | return false 8 | } 9 | 10 | // Flush the output buffer. 11 | func yaml_emitter_flush(emitter *yaml_emitter_t) bool { 12 | if emitter.write_handler == nil { 13 | panic("write handler not set") 14 | } 15 | 16 | // Check if the buffer is empty. 17 | if emitter.buffer_pos == 0 { 18 | return true 19 | } 20 | 21 | if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { 22 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 23 | } 24 | emitter.buffer_pos = 0 25 | return true 26 | } 27 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/yamlprivateh.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | const ( 4 | // The size of the input raw buffer. 5 | input_raw_buffer_size = 512 6 | 7 | // The size of the input buffer. 8 | // It should be possible to decode the whole raw buffer. 9 | input_buffer_size = input_raw_buffer_size * 3 10 | 11 | // The size of the output buffer. 12 | output_buffer_size = 128 13 | 14 | // The size of the output raw buffer. 15 | // It should be possible to encode the whole output buffer. 16 | output_raw_buffer_size = (output_buffer_size*2 + 2) 17 | 18 | // The size of other stacks and queues. 19 | initial_stack_size = 16 20 | initial_queue_size = 16 21 | initial_string_size = 16 22 | ) 23 | 24 | // Check if the character at the specified position is an alphabetical 25 | // character, a digit, '_', or '-'. 26 | func is_alpha(b []byte, i int) bool { 27 | return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' 28 | } 29 | 30 | // Check if the character at the specified position is a digit. 31 | func is_digit(b []byte, i int) bool { 32 | return b[i] >= '0' && b[i] <= '9' 33 | } 34 | 35 | // Get the value of a digit. 36 | func as_digit(b []byte, i int) int { 37 | return int(b[i]) - '0' 38 | } 39 | 40 | // Check if the character at the specified position is a hex-digit. 41 | func is_hex(b []byte, i int) bool { 42 | return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' 43 | } 44 | 45 | // Get the value of a hex-digit. 46 | func as_hex(b []byte, i int) int { 47 | bi := b[i] 48 | if bi >= 'A' && bi <= 'F' { 49 | return int(bi) - 'A' + 10 50 | } 51 | if bi >= 'a' && bi <= 'f' { 52 | return int(bi) - 'a' + 10 53 | } 54 | return int(bi) - '0' 55 | } 56 | 57 | // Check if the character is ASCII. 58 | func is_ascii(b []byte, i int) bool { 59 | return b[i] <= 0x7F 60 | } 61 | 62 | // Check if the character at the start of the buffer can be printed unescaped. 63 | func is_printable(b []byte, i int) bool { 64 | return ((b[i] == 0x0A) || // . == #x0A 65 | (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E 66 | (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF 67 | (b[i] > 0xC2 && b[i] < 0xED) || 68 | (b[i] == 0xED && b[i+1] < 0xA0) || 69 | (b[i] == 0xEE) || 70 | (b[i] == 0xEF && // #xE000 <= . <= #xFFFD 71 | !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF 72 | !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) 73 | } 74 | 75 | // Check if the character at the specified position is NUL. 76 | func is_z(b []byte, i int) bool { 77 | return b[i] == 0x00 78 | } 79 | 80 | // Check if the beginning of the buffer is a BOM. 81 | func is_bom(b []byte, i int) bool { 82 | return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF 83 | } 84 | 85 | // Check if the character at the specified position is space. 86 | func is_space(b []byte, i int) bool { 87 | return b[i] == ' ' 88 | } 89 | 90 | // Check if the character at the specified position is tab. 91 | func is_tab(b []byte, i int) bool { 92 | return b[i] == '\t' 93 | } 94 | 95 | // Check if the character at the specified position is blank (space or tab). 96 | func is_blank(b []byte, i int) bool { 97 | //return is_space(b, i) || is_tab(b, i) 98 | return b[i] == ' ' || b[i] == '\t' 99 | } 100 | 101 | // Check if the character at the specified position is a line break. 102 | func is_break(b []byte, i int) bool { 103 | return (b[i] == '\r' || // CR (#xD) 104 | b[i] == '\n' || // LF (#xA) 105 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) 106 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) 107 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) 108 | } 109 | 110 | func is_crlf(b []byte, i int) bool { 111 | return b[i] == '\r' && b[i+1] == '\n' 112 | } 113 | 114 | // Check if the character is a line break or NUL. 115 | func is_breakz(b []byte, i int) bool { 116 | //return is_break(b, i) || is_z(b, i) 117 | return ( // is_break: 118 | b[i] == '\r' || // CR (#xD) 119 | b[i] == '\n' || // LF (#xA) 120 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) 121 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) 122 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) 123 | // is_z: 124 | b[i] == 0) 125 | } 126 | 127 | // Check if the character is a line break, space, or NUL. 128 | func is_spacez(b []byte, i int) bool { 129 | //return is_space(b, i) || is_breakz(b, i) 130 | return ( // is_space: 131 | b[i] == ' ' || 132 | // is_breakz: 133 | b[i] == '\r' || // CR (#xD) 134 | b[i] == '\n' || // LF (#xA) 135 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) 136 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) 137 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) 138 | b[i] == 0) 139 | } 140 | 141 | // Check if the character is a line break, space, tab, or NUL. 142 | func is_blankz(b []byte, i int) bool { 143 | //return is_blank(b, i) || is_breakz(b, i) 144 | return ( // is_blank: 145 | b[i] == ' ' || b[i] == '\t' || 146 | // is_breakz: 147 | b[i] == '\r' || // CR (#xD) 148 | b[i] == '\n' || // LF (#xA) 149 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) 150 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) 151 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) 152 | b[i] == 0) 153 | } 154 | 155 | // Determine the width of the character. 156 | func width(b byte) int { 157 | // Don't replace these by a switch without first 158 | // confirming that it is being inlined. 159 | if b&0x80 == 0x00 { 160 | return 1 161 | } 162 | if b&0xE0 == 0xC0 { 163 | return 2 164 | } 165 | if b&0xF0 == 0xE0 { 166 | return 3 167 | } 168 | if b&0xF8 == 0xF0 { 169 | return 4 170 | } 171 | return 0 172 | 173 | } 174 | --------------------------------------------------------------------------------