diff --git a/accounts/benchmark_cache_test.go b/accounts/benchmark_cache_test.go new file mode 100644 index 000000000..baebe994b --- /dev/null +++ b/accounts/benchmark_cache_test.go @@ -0,0 +1,257 @@ +package accounts + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func benchmarkCacheAccounts(n int, b *testing.B) { + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + kfiles, _ := ioutil.ReadDir(staticKeyFilesResourcePath) + lf := len(kfiles) - 1 // accounts.db + + start := time.Now() + cache := newAddrCache(staticKeyFilesResourcePath) + elapsed := time.Since(start) + + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + as := cache.accounts() + if len(as) < lf { // FIXME. Why is there a mismatch? File dupes? Corrupted files? Actually handling the sync errors might help... + b.Errorf("cacheaccount/files mismatch: cacheacounts: %v, files: %v", len(as), lf) + } + as = nil + } + cache.close() +} + +func BenchmarkCacheAccounts100(b *testing.B) { benchmarkCacheAccounts(100, b) } +func BenchmarkCacheAccounts500(b *testing.B) { benchmarkCacheAccounts(500, b) } +func BenchmarkCacheAccounts1000(b *testing.B) { benchmarkCacheAccounts(1000, b) } +func BenchmarkCacheAccounts5000(b *testing.B) { benchmarkCacheAccounts(5000, b) } +func BenchmarkCacheAccounts10000(b *testing.B) { benchmarkCacheAccounts(10000, b) } +func BenchmarkCacheAccounts20000(b *testing.B) { benchmarkCacheAccounts(20000, b) } +func BenchmarkCacheAccounts100000(b *testing.B) { benchmarkCacheAccounts(100000, b) } +func BenchmarkCacheAccounts500000(b *testing.B) { benchmarkCacheAccounts(500000, b) } + +// ac.add checks ac.all to see if given account already exists in cache, +// iff it doesn't, it adds account to byAddr map. +// +// No accounts added here are existing in cache, so *sort.Search* will iterate through all +// cached accounts _up to_ relevant alphabetizing. This is somewhat redundant to test cache.accounts(), +// except will test sort.Search instead of sort.Sort. +// +// Note that this _does not_ include ac.newAddrCache. +func benchmarkCacheAdd(n int, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + start := time.Now() + cache := newAddrCache(staticKeyFilesResourcePath) + elapsed := time.Since(start) + + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + // cacheTestAccounts are constant established in cache_test.go + for _, a := range cachetestAccounts { + cache.add(a) + } + } + cache.close() +} + +func BenchmarkCacheAdd100(b *testing.B) { benchmarkCacheAdd(100, b) } +func BenchmarkCacheAdd500(b *testing.B) { benchmarkCacheAdd(500, b) } +func BenchmarkCacheAdd1000(b *testing.B) { benchmarkCacheAdd(1000, b) } +func BenchmarkCacheAdd5000(b *testing.B) { benchmarkCacheAdd(5000, b) } +func BenchmarkCacheAdd10000(b *testing.B) { benchmarkCacheAdd(10000, b) } +func BenchmarkCacheAdd20000(b *testing.B) { benchmarkCacheAdd(20000, b) } +func BenchmarkCacheAdd100000(b *testing.B) { benchmarkCacheAdd(100000, b) } +func BenchmarkCacheAdd500000(b *testing.B) { benchmarkCacheAdd(500000, b) } + +// ac.find checks ac.all to see if given account already exists in cache, +// iff it doesn't, it adds account to byAddr map. +// +// 3/4 added here are existing in cache; .find will iterate through ac.all +// cached, breaking only upon a find. There is no sort. method here. +// +// Note that this _does not_ include ac.newAddrCache. +func benchmarkCacheFind(n int, onlyExisting bool, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + start := time.Now() + cache := newAddrCache(staticKeyFilesResourcePath) + elapsed := time.Since(start) + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + accs := cache.accounts() + + // Set up 1 DNE and 3 existing accs. + // Using the last accs because they should take the longest to iterate to. + var findAccounts []Account + + if !onlyExisting { + findAccounts = append(cachetestAccounts[(len(cachetestAccounts)-1):], accs[(len(accs)-3):]...) + if len(findAccounts) != 4 { + b.Fatalf("wrong number find accs: got: %v, want: 4", len(findAccounts)) + } + } else { + findAccounts = accs[(len(accs) - 4):] + } + accs = nil // clear mem? + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + for _, a := range findAccounts { + cache.find(a) + } + } + cache.close() +} + +func BenchmarkCacheFind100(b *testing.B) { benchmarkCacheFind(100, false, b) } +func BenchmarkCacheFind500(b *testing.B) { benchmarkCacheFind(500, false, b) } +func BenchmarkCacheFind1000(b *testing.B) { benchmarkCacheFind(1000, false, b) } +func BenchmarkCacheFind5000(b *testing.B) { benchmarkCacheFind(5000, false, b) } +func BenchmarkCacheFind10000(b *testing.B) { benchmarkCacheFind(10000, false, b) } +func BenchmarkCacheFind20000(b *testing.B) { benchmarkCacheFind(20000, false, b) } +func BenchmarkCacheFind100000(b *testing.B) { benchmarkCacheFind(100000, false, b) } +func BenchmarkCacheFind500000(b *testing.B) { benchmarkCacheFind(500000, false, b) } +func BenchmarkCacheFind100OnlyExisting(b *testing.B) { benchmarkCacheFind(100, true, b) } +func BenchmarkCacheFind500OnlyExisting(b *testing.B) { benchmarkCacheFind(500, true, b) } +func BenchmarkCacheFind1000OnlyExisting(b *testing.B) { benchmarkCacheFind(1000, true, b) } +func BenchmarkCacheFind5000OnlyExisting(b *testing.B) { benchmarkCacheFind(5000, true, b) } +func BenchmarkCacheFind10000OnlyExisting(b *testing.B) { benchmarkCacheFind(10000, true, b) } +func BenchmarkCacheFind20000OnlyExisting(b *testing.B) { benchmarkCacheFind(20000, true, b) } +func BenchmarkCacheFind100000OnlyExisting(b *testing.B) { benchmarkCacheFind(100000, true, b) } +func BenchmarkCacheFind500000OnlyExisting(b *testing.B) { benchmarkCacheFind(500000, true, b) } + +// https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04 +// CopyFile copies the contents of the file named src to the file named +// by dst. The file will be created if it does not already exist. If the +// destination file exists, all it's contents will be replaced by the contents +// of the source file. The file mode will be copied from the source and +// the copied data is synced/flushed to stable storage. +func CopyFile(src, dst string) (err error) { + in, err := os.Open(src) + if err != nil { + return + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return + } + defer func() { + if e := out.Close(); e != nil { + err = e + } + }() + + _, err = io.Copy(out, in) + if err != nil { + return + } + + err = out.Sync() + if err != nil { + return + } + + si, err := os.Stat(src) + if err != nil { + return + } + err = os.Chmod(dst, si.Mode()) + if err != nil { + return + } + + return +} + +// CopyDir recursively copies a directory tree, attempting to preserve permissions. +// Source directory must exist. +// Symlinks are ignored and skipped. +func CopyDir(src string, dst string) (err error) { + src = filepath.Clean(src) + dst = filepath.Clean(dst) + + si, err := os.Stat(src) + if err != nil { + return err + } + if !si.IsDir() { + return fmt.Errorf("source is not a directory") + } + + entries, err := ioutil.ReadDir(src) + if err != nil { + return + } + + for _, entry := range entries { + srcPath := filepath.Join(src, entry.Name()) + dstPath := filepath.Join(dst, entry.Name()) + + if entry.IsDir() { + err = CopyDir(srcPath, dstPath) + if err != nil { + return + } + } else { + // Skip symlinks. + if entry.Mode()&os.ModeSymlink != 0 { + continue + } + if skipKeyFile(entry) { + continue + } + + err = CopyFile(srcPath, dstPath) + if err != nil { + return + } + } + } + + return +} diff --git a/accounts/benchmark_cachedb_test.go b/accounts/benchmark_cachedb_test.go new file mode 100644 index 000000000..8c8d9abb1 --- /dev/null +++ b/accounts/benchmark_cachedb_test.go @@ -0,0 +1,161 @@ +package accounts + +import ( + "io/ioutil" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func benchmarkCacheDBAccounts(n int, b *testing.B) { + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + kfiles, _ := ioutil.ReadDir(staticKeyFilesResourcePath) + lf := len(kfiles) - 1 // accounts.db + + start := time.Now() + cache := newCacheDB(staticKeyFilesResourcePath) + elapsed := time.Since(start) + + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + as := cache.accounts() + if len(as) < lf { // FIXME. Why is there a mismatch? File dupes? Corrupted files? Actually handling the sync errors might help... + b.Errorf("cacheaccount/files mismatch: cacheacounts: %v, files: %v", len(as), lf) + } + as = nil + } + cache.close() +} + +func BenchmarkCacheDBAccounts100(b *testing.B) { benchmarkCacheDBAccounts(100, b) } +func BenchmarkCacheDBAccounts500(b *testing.B) { benchmarkCacheDBAccounts(500, b) } +func BenchmarkCacheDBAccounts1000(b *testing.B) { benchmarkCacheDBAccounts(1000, b) } +func BenchmarkCacheDBAccounts5000(b *testing.B) { benchmarkCacheDBAccounts(5000, b) } +func BenchmarkCacheDBAccounts10000(b *testing.B) { benchmarkCacheDBAccounts(10000, b) } +func BenchmarkCacheDBAccounts20000(b *testing.B) { benchmarkCacheDBAccounts(20000, b) } +func BenchmarkCacheDBAccounts100000(b *testing.B) { benchmarkCacheDBAccounts(100000, b) } +func BenchmarkCacheDBAccounts500000(b *testing.B) { benchmarkCacheDBAccounts(500000, b) } + +// ac.add checks ac.all to see if given account already exists in cache, +// iff it doesn't, it adds account to byAddr map. +// +// No accounts added here are existing in cache, so *sort.Search* will iterate through all +// cached accounts _up to_ relevant alphabetizing. This is somewhat redundant to test cache.accounts(), +// except will test sort.Search instead of sort.Sort. +// +// Note that this _does not_ include ac.newCacheDB. +func benchmarkCacheDBAdd(n int, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + start := time.Now() + cache := newCacheDB(staticKeyFilesResourcePath) + elapsed := time.Since(start) + + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + // cacheTestAccounts are constant established in cache_test.go + for _, a := range cachetestAccounts { + cache.add(a) + } + } + cache.close() +} + +func BenchmarkCacheDBAdd100(b *testing.B) { benchmarkCacheDBAdd(100, b) } +func BenchmarkCacheDBAdd500(b *testing.B) { benchmarkCacheDBAdd(500, b) } +func BenchmarkCacheDBAdd1000(b *testing.B) { benchmarkCacheDBAdd(1000, b) } +func BenchmarkCacheDBAdd5000(b *testing.B) { benchmarkCacheDBAdd(5000, b) } +func BenchmarkCacheDBAdd10000(b *testing.B) { benchmarkCacheDBAdd(10000, b) } +func BenchmarkCacheDBAdd20000(b *testing.B) { benchmarkCacheDBAdd(20000, b) } +func BenchmarkCacheDBAdd100000(b *testing.B) { benchmarkCacheDBAdd(100000, b) } +func BenchmarkCacheDBAdd500000(b *testing.B) { benchmarkCacheDBAdd(500000, b) } + +// ac.find checks ac.all to see if given account already exists in cache, +// iff it doesn't, it adds account to byAddr map. +// +// 3/4 added here are existing in cache; .find will iterate through ac.all +// cached, breaking only upon a find. There is no sort. method here. +// +// Note that this _does not_ include ac.newCacheDB. +func benchmarkCacheDBFind(n int, onlyExisting bool, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + start := time.Now() + cache := newCacheDB(staticKeyFilesResourcePath) + elapsed := time.Since(start) + b.Logf("establishing cache for %v accs: %v", n, elapsed) + + accs := cache.accounts() + + // Set up 1 DNE and 3 existing accs. + // Using the last accs because they should take the longest to iterate to. + var findAccounts []Account + + if !onlyExisting { + findAccounts = append(cachetestAccounts[(len(cachetestAccounts)-1):], accs[(len(accs)-3):]...) + if len(findAccounts) != 4 { + b.Fatalf("wrong number find accs: got: %v, want: 4", len(findAccounts)) + } + } else { + findAccounts = accs[(len(accs) - 4):] + } + accs = nil // clear mem? + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + for _, a := range findAccounts { + cache.find(a) + } + } + cache.close() +} + +func BenchmarkCacheDBFind100(b *testing.B) { benchmarkCacheDBFind(100, false, b) } +func BenchmarkCacheDBFind500(b *testing.B) { benchmarkCacheDBFind(500, false, b) } +func BenchmarkCacheDBFind1000(b *testing.B) { benchmarkCacheDBFind(1000, false, b) } +func BenchmarkCacheDBFind5000(b *testing.B) { benchmarkCacheDBFind(5000, false, b) } +func BenchmarkCacheDBFind10000(b *testing.B) { benchmarkCacheDBFind(10000, false, b) } +func BenchmarkCacheDBFind20000(b *testing.B) { benchmarkCacheDBFind(20000, false, b) } +func BenchmarkCacheDBFind100000(b *testing.B) { benchmarkCacheDBFind(100000, false, b) } +func BenchmarkCacheDBFind500000(b *testing.B) { benchmarkCacheDBFind(500000, false, b) } +func BenchmarkCacheDBFind100OnlyExisting(b *testing.B) { benchmarkCacheDBFind(100, true, b) } +func BenchmarkCacheDBFind500OnlyExisting(b *testing.B) { benchmarkCacheDBFind(500, true, b) } +func BenchmarkCacheDBFind1000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(1000, true, b) } +func BenchmarkCacheDBFind5000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(5000, true, b) } +func BenchmarkCacheDBFind10000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(10000, true, b) } +func BenchmarkCacheDBFind20000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(20000, true, b) } +func BenchmarkCacheDBFind100000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(100000, true, b) } +func BenchmarkCacheDBFind500000OnlyExisting(b *testing.B) { benchmarkCacheDBFind(500000, true, b) } diff --git a/accounts/benchmark_manager_test.go b/accounts/benchmark_manager_test.go new file mode 100644 index 000000000..01bd37c97 --- /dev/null +++ b/accounts/benchmark_manager_test.go @@ -0,0 +1,442 @@ +package accounts + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" +) + +//func BenchmarkAccountSignScaling(b *testing.B) { +// var cases = []struct { +// dir string +// numKeyFiles int +// resetAll, resetCache bool +// }{ +// // You can use resetCache: false to save some time if you've already run the benchmark. +// // Note that if you make any changes to the structure of the cachedb you'll need to +// // dump and reinitialize accounts.db. +// {dir: "benchmark_keystore100", numKeyFiles: 100, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore100", numKeyFiles: 100, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore500", numKeyFiles: 500, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore500", numKeyFiles: 500, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore1k", numKeyFiles: 1000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore1k", numKeyFiles: 1000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore5k", numKeyFiles: 5000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore5k", numKeyFiles: 5000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore10k", numKeyFiles: 10000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore10k", numKeyFiles: 10000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore20k", numKeyFiles: 20000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore20k", numKeyFiles: 20000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore100k", numKeyFiles: 100000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore100k", numKeyFiles: 100000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore500k", numKeyFiles: 500000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore500k", numKeyFiles: 500000, resetAll: false, resetCache: false}, +// } +// +// for _, c := range cases { +// b.Run(fmt.Sprintf("KeyFiles#:%v, CacheFromScratch:%v", c.numKeyFiles, c.resetCache), func(b *testing.B) { +// am := setupBenchmarkAccountFlowFast(filepath.Join("testdata", c.dir), c.numKeyFiles, c.resetAll, c.resetCache, b) +// benchmarkAccountSignFast(am.keyStore.baseDir, am, c.numKeyFiles-1, b) +// am = nil +// }) +// } +//} +// +//func BenchmarkAccountFlowScaling(b *testing.B) { +// var cases = []struct { +// dir string +// numKeyFiles int +// resetAll, resetCache bool +// }{ +// {dir: "benchmark_keystore100", numKeyFiles: 100, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore100", numKeyFiles: 100, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore500", numKeyFiles: 500, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore500", numKeyFiles: 500, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore1k", numKeyFiles: 1000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore1k", numKeyFiles: 1000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore5k", numKeyFiles: 5000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore5k", numKeyFiles: 5000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore10k", numKeyFiles: 10000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore10k", numKeyFiles: 10000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore20k", numKeyFiles: 20000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore20k", numKeyFiles: 20000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore100k", numKeyFiles: 100000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore100k", numKeyFiles: 100000, resetAll: false, resetCache: false}, +// {dir: "benchmark_keystore500k", numKeyFiles: 500000, resetAll: false, resetCache: true}, +// //{dir: "benchmark_keystore500k", numKeyFiles: 500000, resetAll: false, resetCache: false}, +// } +// +// for _, c := range cases { +// b.Run(fmt.Sprintf("KeyFiles#:%v, CacheFromScratch:%v", c.numKeyFiles, c.resetCache), func(b *testing.B) { +// am := setupBenchmarkAccountFlowFast(filepath.Join("testdata", c.dir), c.numKeyFiles, c.resetAll, c.resetCache, b) +// benchmarkAccountFlowFast(filepath.Join("testdata", c.dir), am, b) +// am = nil +// }) +// } +//} +// +//// Signing an account requires finding the keyfile. +//func testAccountSign(am *Manager, account Account, dir string) error { +// if _, err := am.SignWithPassphrase(account.Address, "foo", testSigData); err != nil { +// return err +// } +// return nil +//} +// +func testAccountFlow(am *Manager, dir string) error { + + // Create. + a, err := am.NewAccount("foo") + if err != nil { + return err + } + p, e := filepath.Abs(dir) + if e != nil { + return fmt.Errorf("could not determine absolute path for temp dir: %v", e) + } + if !strings.HasPrefix(a.File, p+"/") { + return fmt.Errorf("account file %s doesn't have dir prefix; %v", a.File, p) + } + stat, err := os.Stat(a.File) + if err != nil { + return fmt.Errorf("account file %s doesn't exist (%v)", a.File, err) + } + if runtime.GOOS != "windows" && stat.Mode() != 0600 { + return fmt.Errorf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600) + } + if !am.HasAddress(a.Address) { + return fmt.Errorf("HasAddres(%x) should've returned true", a.Address) + } + + // Update. + if err := am.Update(a, "foo", "bar"); err != nil { + return fmt.Errorf("Update error: %v", err) + } + + // Sign with passphrase. + _, err = am.SignWithPassphrase(a.Address, "bar", testSigData) // testSigData is an empty [32]byte established in manager_test.go + if err != nil { + return fmt.Errorf("should be able to sign from account: %v", err) + } + + // Delete. + if err := am.DeleteAccount(a, "bar"); err != nil { + return fmt.Errorf("DeleteAccount error: %v", err) + } + if _, err := os.Stat(a.File); err == nil || !os.IsNotExist(err) { + return fmt.Errorf("account file %s should be gone after DeleteAccount", a.File) + } + if am.HasAddress(a.Address) { + return fmt.Errorf("HasAddress(%x) should've returned true after DeleteAccount", a.Address) + } + return nil +} + +// +//func createTestAccount(am *Manager, dir string) error { +// a, err := am.NewAccount("foo") +// if err != nil { +// return err +// } +// p, e := filepath.Abs(dir) +// if e != nil { +// return fmt.Errorf("could not determine absolute path for temp dir: %v", e) +// } +// if !strings.HasPrefix(a.File, p+"/") { +// return fmt.Errorf("account file %s doesn't have dir prefix; %v", a.File, p) +// } +// stat, err := os.Stat(a.File) +// if err != nil { +// return fmt.Errorf("account file %s doesn't exist (%v)", a.File, err) +// } +// if runtime.GOOS != "windows" && stat.Mode() != 0600 { +// return fmt.Errorf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600) +// } +// if !am.HasAddress(a.Address) { +// return fmt.Errorf("HasAddres(%x) should've returned true", a.Address) +// } +// return nil +//} +// +//func getRandomIntN(n int) int { +// rand.Seed(time.Now().UTC().UnixNano()) +// return int(rand.Int31n(int32(n))) +//} +// +//// Test benchmark for CRUSD/account; create, update, sign, delete. +//// Runs against setting of 10, 100, 1000, 10k, (100k, 1m) _existing_ accounts. +//func benchmarkAccountSignFast(dir string, am *Manager, accountsN int, b *testing.B) { +// for i := 0; i < b.N; i++ { +// j := getRandomIntN(accountsN) +// b.Logf("signing with account index: %v", j) +// account, e := am.AccountByIndex(j) +// j = 0 +// if e != nil { +// b.Fatal(e) +// } +// if e := testAccountSign(am, account, dir); e != nil { +// b.Fatalf("error signing with account: %v", e) +// } +// } +//} +// +//func getFSvsCacheAccountN(dir string, ac *addrCache, b *testing.B) (fN, acN int) { +// +// files, err := ioutil.ReadDir(ac.keydir) +// if err != nil { +// b.Fatalf("readdir: %v", err) +// } +// +// acN = len(ac.accounts()) +// fN = len(files) - 1 // - 1 because accounts.db is there too +// +// return fN, acN +//} +// +//func setupBenchmarkAccountFlowFast(dir string, n int, resetAll, resetCache bool, b *testing.B) { +// // Optionally: don't remove so we can compound accounts more quickly. +// if resetAll { +// b.Log("removing testdata keystore") +// os.RemoveAll(dir) +// } else if resetCache { +// b.Log("removing existing cache") +// os.Remove(filepath.Join(dir, "accounts.db")) // Remove cache db so we have to set up (scan()) every time. +// } else { +// b.Log("using existing cache and keystore") +// } +// +// // Ensure any removed dir exists. +// if e := os.MkdirAll(dir, os.ModePerm); e != nil { +// b.Fatalf("could not mkdir -p '%v': %v", dir, e) +// } +// +// files, err := ioutil.ReadDir(dir) +// if err != nil { +// b.Fatalf("readdir: %v", err) +// } +// +// ks, e := newKeyStore(dir, veryLightScryptN, veryLightScryptP) +// if e != nil { +// b.Fatalf("keystore: %v", e) +// } +// +// for i := len(files); i < n+1; i++ { +// _, _, err := storeNewKey(ks, "foo") +// if err != nil { +// b.Fatalf("storenewkey: %v", err) +// } +// } +// ks = nil +// files = nil +// // +// //manStart := time.Now() +// //am, err := NewManager(dir, veryLightScryptN, veryLightScryptP) +// //if err != nil { +// // b.Fatal(err) +// //} +// // +// //am.get.watcher.running = true // cache.watcher.running = true // prevent unexpected reloads +// // +// //b.Logf("setup time for manager: %v", time.Since(manStart)) +// // +// //fsN, acN := getFSvsCacheAccountN(dir, am.cache, b) +// // +// //if acN > fsN { // Can allow greater number of keyfiles, in the case that there are invalids or dupes. +// // b.Errorf("accounts/files count mismatch: keyfiles: %v, accounts: %v", fsN, acN) +// //} else { +// // b.Logf("files: %v, accounts: %v", fsN, acN) +// //} +// // +// //b.Logf("setup time for manager: %v", time.Since(manStart)) +// // +// //b.ResetTimer() // _benchmark_ timer, not setup timer. +// // +// //return am +//} +// +//// Test benchmark for CRUSD/account; create, update, sign, delete. +//// Runs against setting of 10, 100, 1000, 10k, (100k, 1m) _existing_ accounts. +//func benchmarkAccountFlowFast(dir string, am *Manager, b *testing.B) { +// for i := 0; i < b.N; i++ { +// if e := testAccountFlow(am, dir); e != nil { +// b.Fatalf("error setting up account: %v", e) +// } +// } +//} + +func BenchmarkManager_SignWithPassphrase(b *testing.B) { + var cases = []struct { + numKeyFiles int + wantCacheDB, resetCacheDB bool + }{ + // You can use resetCache: false to save some time if you've already run the benchmark. + // Note that if you make any changes to the structure of the cachedb you'll need to + // dump and reinitialize accounts.db. + {numKeyFiles: 100, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 100, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 500, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 500, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 1000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 1000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 5000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 5000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 10000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 10000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 20000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 20000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 100000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 100000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 200000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 200000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 500000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 500000, wantCacheDB: true, resetCacheDB: false}, + } + + for _, c := range cases { + b.Run(fmt.Sprintf("CRUSD:KeyFiles#:%v,DB:%v,reset:%v", c.numKeyFiles, c.wantCacheDB, c.resetCacheDB), func(b *testing.B) { + benchmarkManager_SignWithPassphrase(c.numKeyFiles, c.wantCacheDB, c.resetCacheDB, b) + }) + } +} + +func benchmarkManager_SignWithPassphrase(n int, wantcachedb bool, resetcachedb bool, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + if !wantcachedb { + p, e := filepath.Abs(staticKeyFilesResourcePath) + if e != nil { + b.Fatal(e) + } + staticKeyFilesResourcePath = p + } + + + start := time.Now() + am, me := NewManager(staticKeyFilesResourcePath, veryLightScryptN, veryLightScryptP, wantcachedb) + if me != nil { + b.Fatal(me) + } + elapsed := time.Since(start) + b.Logf("establishing manager for %v accs: %v", n, elapsed) + + accs := am.Accounts() + if !wantcachedb { + am.ac.getWatcher().running = true + } + if len(accs) == 0 { + b.Fatal("no accounts") + } + + // Set up 1 DNE and 3 existing accs. + // Using the last accs because they should take the longest to iterate to. + var signAccounts []Account + //signAccounts = accs[(len(accs) - 4):] + signAccounts = accs[(len(accs) - 3):] + accs = nil + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + for _, a := range signAccounts { + if _, e := am.SignWithPassphrase(a.Address, "foo", testSigData); e != nil { + b.Errorf("signing with passphrase: %v", e) + } + } + } + am.ac.close() + am = nil +} + +func BenchmarkManagerCRUSD(b *testing.B) { + var cases = []struct { + numKeyFiles int + wantCacheDB, resetCacheDB bool + }{ + // You can use resetCache: false to save some time if you've already run the benchmark. + // Note that if you make any changes to the structure of the cachedb you'll need to + // dump and reinitialize accounts.db. + {numKeyFiles: 100, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 100, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 500, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 500, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 1000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 1000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 5000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 5000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 10000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 10000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 20000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 20000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 100000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 100000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 200000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 200000, wantCacheDB: true, resetCacheDB: false}, + {numKeyFiles: 500000, wantCacheDB: false, resetCacheDB: false}, + {numKeyFiles: 500000, wantCacheDB: true, resetCacheDB: false}, + } + + for _, c := range cases { + b.Run(fmt.Sprintf("CRUSD:KeyFiles#:%v,DB:%v,reset:%v", c.numKeyFiles, c.wantCacheDB, c.resetCacheDB), func(b *testing.B) { + benchmarkManager_CRUSD(c.numKeyFiles, c.wantCacheDB, c.resetCacheDB, b) + }) + } +} + +func benchmarkManager_CRUSD(n int, wantcachedb bool, resetcachedb bool, b *testing.B) { + + // 20000 -> 20k + staticKeyFilesResourcePath := strconv.Itoa(n) + if strings.HasSuffix(staticKeyFilesResourcePath, "000") { + staticKeyFilesResourcePath = strings.TrimSuffix(staticKeyFilesResourcePath, "000") + staticKeyFilesResourcePath += "k" + } + + staticKeyFilesResourcePath = filepath.Join("testdata", "benchmark_keystore"+staticKeyFilesResourcePath) + + if !wantcachedb { + p, e := filepath.Abs(staticKeyFilesResourcePath) + if e != nil { + b.Fatal(e) + } + staticKeyFilesResourcePath = p + } + + if resetcachedb { + os.Remove(filepath.Join(staticKeyFilesResourcePath, "accounts.db")) + } + + start := time.Now() + am, me := NewManager(staticKeyFilesResourcePath, veryLightScryptN, veryLightScryptP, wantcachedb) + if !wantcachedb { + am.ac.getWatcher().running = true + } + + if me != nil { + b.Fatal(me) + } + elapsed := time.Since(start) + b.Logf("establishing manager for %v accs: %v", n, elapsed) + + b.ResetTimer() // _benchmark_ timer, not setup timer. + + for i := 0; i < b.N; i++ { + if e := testAccountFlow(am, staticKeyFilesResourcePath); e != nil { + b.Errorf("account flow (CRUSD): %v (db: %v)", e, wantcachedb) + } + } + am.ac.close() + am = nil +} diff --git a/accounts/cache.go b/accounts/cache.go index 9068d0a49..bd8ce0c3b 100644 --- a/accounts/cache.go +++ b/accounts/cache.go @@ -62,6 +62,26 @@ func (err *AmbiguousAddrError) Error() string { return fmt.Sprintf("multiple keys match address (%s)", files) } +type caching interface { + muLock() + muUnlock() + getKeydir() string + getWatcher() *watcher + getThrottle() *time.Timer + + maybeReload() + reload() + Syncfs2db(time.Time) []error + + hasAddress(address common.Address) bool + accounts() []Account + add(Account) + delete(Account) + find(Account) (Account, error) + + close() +} + // addrCache is a live index of all accounts in the keystore. type addrCache struct { keydir string @@ -81,6 +101,29 @@ func newAddrCache(keydir string) *addrCache { return ac } +func (ac *addrCache) muLock() { + ac.mu.Lock() +} +func (ac *addrCache) muUnlock() { + ac.mu.Unlock() +} + +func (ac *addrCache) getKeydir() string { + return ac.keydir +} + +func (ac *addrCache) getWatcher() *watcher { + return ac.watcher +} + +func (ac *addrCache) getThrottle() *time.Timer { + return ac.throttle +} + +func (ac *addrCache) Syncfs2db(t time.Time) []error { + panic("Invalid use; syncfs2db only available for db cache.") +} + func (ac *addrCache) accounts() []Account { ac.maybeReload() ac.mu.Lock() @@ -261,9 +304,12 @@ func skipKeyFile(fi os.FileInfo) bool { if strings.HasSuffix(fi.Name(), "~") || strings.HasPrefix(fi.Name(), ".") { return true } + if strings.HasSuffix(fi.Name(), "accounts.db") { + return true + } // Skip misc special files, directories (yes, symlinks too). if fi.IsDir() || fi.Mode()&os.ModeType != 0 { return true } return false -} +} \ No newline at end of file diff --git a/accounts/cache_test.go b/accounts/cache_test.go index bb0bc2792..017c2c58e 100644 --- a/accounts/cache_test.go +++ b/accounts/cache_test.go @@ -18,6 +18,8 @@ package accounts import ( "fmt" + "github.com/davecgh/go-spew/spew" + "github.com/ethereumproject/go-ethereum/common" "io/ioutil" "math/rand" "os" @@ -26,9 +28,6 @@ import ( "sort" "testing" "time" - - "github.com/davecgh/go-spew/spew" - "github.com/ethereumproject/go-ethereum/common" ) var ( @@ -57,22 +56,27 @@ func TestWatchNewFile(t *testing.T) { // Ensure the watcher is started before adding any files. am.Accounts() - time.Sleep(200 * time.Millisecond) + time.Sleep(5 * time.Second) + if w := am.ac.getWatcher(); !w.running { + t.Fatalf("watcher not running after %v: %v", 5*time.Second, spew.Sdump(w)) + } // Move in the files. wantAccounts := make([]Account, len(cachetestAccounts)) for i := range cachetestAccounts { a := cachetestAccounts[i] - a.File = filepath.Join(dir, filepath.Base(a.File)) + a.File = filepath.Join(dir, filepath.Base(a.File)) // rename test file to base from temp dir wantAccounts[i] = a - data, err := ioutil.ReadFile(cachetestAccounts[i].File) + data, err := ioutil.ReadFile(cachetestAccounts[i].File) // but we still have to read from original file path if err != nil { t.Fatal(err) } + // write to temp dir if err := ioutil.WriteFile(a.File, data, 0666); err != nil { t.Fatal(err) } } + sort.Sort(accountsByFile(wantAccounts)) // am should see the accounts. var list []Account @@ -91,8 +95,14 @@ func TestWatchNoDir(t *testing.T) { // Create am but not the directory that it watches. rand.Seed(time.Now().UnixNano()) - dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-watch-test-%d-%d", os.Getpid(), rand.Int())) - am, err := NewManager(dir, LightScryptN, LightScryptP) + rp := fmt.Sprintf("eth-keystore-watch-test-%d-%d", os.Getpid(), rand.Int()) + dir, e := ioutil.TempDir("", rp) + if e != nil { + t.Fatal(e) + } + defer os.RemoveAll(dir) + + am, err := NewManager(dir, LightScryptN, LightScryptP, false) if err != nil { t.Fatal(err) } @@ -101,14 +111,18 @@ func TestWatchNoDir(t *testing.T) { if len(list) > 0 { t.Error("initial account list not empty:", list) } - time.Sleep(100 * time.Millisecond) + time.Sleep(5 * time.Second) + if w := am.ac.getWatcher(); !w.running { + t.Fatalf("watcher not running after %v: %v", 5*time.Second, spew.Sdump(w)) + } // Create the directory and copy a key file into it. os.MkdirAll(dir, 0700) defer os.RemoveAll(dir) file := filepath.Join(dir, "aaa") - data, err := ioutil.ReadFile(cachetestAccounts[0].File) + // This filepath-ing is redundant but ensure parallel tests don't fuck each other up... I think. + data, err := ioutil.ReadFile(filepath.Join(cachetestDir, filepath.Base(cachetestAccounts[0].File))) if err != nil { t.Fatal(err) } @@ -123,36 +137,34 @@ func TestWatchNoDir(t *testing.T) { ff.Close() // am should see the account. - wantAccounts := []Account{cachetestAccounts[0]} - wantAccounts[0].File = file - var seen, gotAccounts = make(map[time.Duration]bool), make(map[time.Duration][]Account) - for d := 200 * time.Second; d < 8*time.Second; d *= 2 { - list = am.Accounts() - seen[d] = false - if reflect.DeepEqual(list, wantAccounts) { - seen[d] = true - } else { + a := cachetestAccounts[0] + a.File = file + wantAccounts := []Account{a} + var gotAccounts []Account + for d := 500 * time.Millisecond; d <= 2*minReloadInterval; d *= 2 { + gotAccounts = am.Accounts() + if reflect.DeepEqual(gotAccounts, wantAccounts) { + return } - gotAccounts[d] = list time.Sleep(d) } - for i, saw := range seen { - if !saw { - t.Errorf("\nat %v got %v\nwant %v", i, gotAccounts[i], wantAccounts) - } - } + t.Errorf("account watcher never saw changes: got: %v, want: %v", spew.Sdump(gotAccounts), spew.Sdump(wantAccounts)) } func TestCacheInitialReload(t *testing.T) { + cache := newAddrCache(cachetestDir) + accounts := cache.accounts() + if !reflect.DeepEqual(accounts, cachetestAccounts) { - t.Fatalf("got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachetestAccounts)) + t.Errorf("got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachetestAccounts)) } } func TestCacheAddDeleteOrder(t *testing.T) { cache := newAddrCache("testdata/no-such-dir") + defer os.RemoveAll("testdata/no-such-dir") cache.watcher.running = true // prevent unexpected reloads accounts := []Account{ @@ -237,6 +249,7 @@ func TestCacheAddDeleteOrder(t *testing.T) { func TestCacheFind(t *testing.T) { dir := filepath.Join("testdata", "dir") + defer os.RemoveAll(dir) cache := newAddrCache(dir) cache.watcher.running = true // prevent unexpected reloads @@ -262,6 +275,14 @@ func TestCacheFind(t *testing.T) { cache.add(a) } + if lca := cache.accounts(); len(lca) != len(accounts) { + t.Fatalf("wrong number of accounts, got: %v, want: %v", len(lca), len(accounts)) + } + + if !reflect.DeepEqual(cache.accounts(), accounts) { + t.Fatalf("not matching initial accounts: got %v, want: %v", spew.Sdump(cache.accounts()), spew.Sdump(accounts)) + } + nomatchAccount := Account{ Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"), File: filepath.Join(dir, "something"), @@ -307,3 +328,81 @@ func TestCacheFind(t *testing.T) { } } } + +func TestAccountCache_WatchRemove(t *testing.T) { + t.Parallel() + + // setup temp dir + rp := fmt.Sprintf("eth-cacheremove-watch-test-%d-%d", os.Getpid(), rand.Int()) + tmpDir, e := ioutil.TempDir("", rp) + if e != nil { + t.Fatalf("create temp dir: %v", e) + } + defer os.RemoveAll(tmpDir) + + // copy 3 test account files into temp dir + wantAccounts := make([]Account, len(cachetestAccounts)) + for i := range cachetestAccounts { + a := cachetestAccounts[i] + a.File = filepath.Join(tmpDir, filepath.Base(a.File)) + wantAccounts[i] = a + data, err := ioutil.ReadFile(cachetestAccounts[i].File) + if err != nil { + t.Fatal(err) + } + ff, err := os.Create(a.File) + if err != nil { + t.Fatal(err) + } + _, err = ff.Write(data) + if err != nil { + t.Fatal(err) + } + ff.Close() + } + + // make manager in temp dir + ma, e := NewManager(tmpDir, veryLightScryptN, veryLightScryptP, false) + if e != nil { + t.Errorf("create manager in temp dir: %v", e) + } + + // test manager has all accounts + initAccs := ma.Accounts() + if !reflect.DeepEqual(initAccs, wantAccounts) { + t.Errorf("got %v, want: %v", spew.Sdump(initAccs), spew.Sdump(wantAccounts)) + } + time.Sleep(minReloadInterval) + + // test watcher is watching + if w := ma.ac.getWatcher(); !w.running { + t.Errorf("watcher not running") + } + + // remove file + rmPath := filepath.Join(tmpDir, filepath.Base(wantAccounts[0].File)) + if e := os.Remove(rmPath); e != nil { + t.Fatalf("removing key file: %v", e) + } + // ensure it's gone + if _, e := os.Stat(rmPath); e == nil { + t.Fatalf("removed file not actually rm'd") + } + + // test manager does not have account + wantAccounts = wantAccounts[1:] + if len(wantAccounts) != 2 { + t.Errorf("dummy") + } + + gotAccounts := []Account{} + for d := 500 * time.Millisecond; d < 5*time.Second; d *= 2 { + gotAccounts = ma.Accounts() + // If it's ever all the same, we're good. Exit with aplomb. + if reflect.DeepEqual(gotAccounts, wantAccounts) { + return + } + time.Sleep(d) + } + t.Errorf("got: %v, want: %v", spew.Sdump(gotAccounts), spew.Sdump(wantAccounts)) +} diff --git a/accounts/cachedb.go b/accounts/cachedb.go new file mode 100644 index 000000000..f99e7cb80 --- /dev/null +++ b/accounts/cachedb.go @@ -0,0 +1,535 @@ +// Copyright 2016 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package accounts + +import ( + "bufio" + "encoding/json" + "io/ioutil" + "os" + "path/filepath" + "time" + + "github.com/boltdb/bolt" + "github.com/ethereumproject/go-ethereum/common" + "github.com/ethereumproject/go-ethereum/logger" + "github.com/ethereumproject/go-ethereum/logger/glog" + "sort" + "bytes" + "errors" + "sync" + "github.com/mailru/easyjson" + "fmt" + "runtime" +) + +var addrBucketName = []byte("byAddr") +var fileBucketName = []byte("byFile") +var statsBucketName = []byte("stats") +var ErrCacheDBNoUpdateStamp = errors.New("cachedb has no updated timestamp; expected for newborn dbs.") + +// addrCache is a live index of all accounts in the keystore. +type cacheDB struct { + keydir string + watcher *watcher + mu sync.Mutex + throttle *time.Timer + db *bolt.DB +} + +func newCacheDB(keydir string) *cacheDB { + if e := os.MkdirAll(keydir, os.ModePerm); e != nil { + panic(e) + } + + dbpath := filepath.Join(keydir, "accounts.db") + bdb, e := bolt.Open(dbpath, 0600, nil) // TODO configure more? + if e != nil { + panic(e) + } + + cdb := &cacheDB{ + db: bdb, + } + cdb.keydir = keydir + + if e := cdb.db.Update(func(tx *bolt.Tx) error { + if _, e := tx.CreateBucketIfNotExists(addrBucketName); e != nil { + return e + } + if _, e := tx.CreateBucketIfNotExists(fileBucketName); e != nil { + return e + } + if _, e := tx.CreateBucketIfNotExists(statsBucketName); e != nil { + return e + } + return nil + }); e != nil { + panic(e) + } + + return cdb +} + +// Getter functions to implement caching interface. +func (cdb *cacheDB) muLock() { + cdb.mu.Lock() +} + +func (cdb *cacheDB) muUnlock() { + cdb.mu.Unlock() +} + +func (cdb *cacheDB) getKeydir() string { + return cdb.keydir +} + +func (cdb *cacheDB) getWatcher() *watcher { + return cdb.watcher +} + +func (cdb *cacheDB) getThrottle() *time.Timer { + return cdb.throttle +} + +func (cdb *cacheDB) maybeReload() { + // do nothing (implements caching interface) +} + +func (cdb *cacheDB) reload() { + // do nothing (implements caching interface) +} + +// Gets all accounts _byFile_, which contains and possibly exceed byAddr content +// because it may contain dupe address/key pairs (given dupe files) +func (cdb *cacheDB) accounts() []Account { + var as []Account + if e := cdb.db.View(func(tx *bolt.Tx) error { + b := tx.Bucket(fileBucketName) + c := b.Cursor() + + for k, v := c.First(); k != nil; k, v = c.Next() { + a := bytesToAccount(v) + a.File = string(k) + as = append(as, a) + } + + return nil + }); e != nil { + panic(e) + } + + sort.Sort(accountsByFile(as)) // this is important for getting AccountByIndex + + cpy := make([]Account, len(as)) + copy(cpy, as) + + return cpy +} + +// note, again, that this return an _slice_ +func (cdb *cacheDB) getCachedAccountsByAddress(addr common.Address) (accounts []Account, err error) { + err = cdb.db.View(func(tx *bolt.Tx) error { + c := tx.Bucket(addrBucketName).Cursor() + + prefix := []byte(addr.Hex()) + for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() { + accounts = append(accounts, Account{Address: addr, File: string(bytes.Replace(k, prefix, []byte(""), 1))}) + } + return nil + }) + if err == nil && (len(accounts) == 0) { + return accounts, ErrNoMatch + } + return accounts, err +} + +// ... and this returns an Account +func (cdb *cacheDB) getCachedAccountByFile(file string) (account Account, err error) { + if file == "" { + return Account{}, ErrNoMatch + } + err = cdb.db.View(func(tx *bolt.Tx) error { + b := tx.Bucket(fileBucketName) + if v := b.Get([]byte(file)); v != nil { + account = bytesToAccount(v) + } + return nil + }) + if err == nil && (account == Account{}) { + return account, ErrNoMatch + } + return account, err +} + +func (cdb *cacheDB) hasAddress(addr common.Address) bool { + as, e := cdb.getCachedAccountsByAddress(addr) + return e == nil && len(as) > 0 +} + +// add makes the assumption that if the account is not cached by file, it won't be listed +// by address either. thusly, when and iff it adds an account to the cache(s), it adds bothly. +func (cdb *cacheDB) add(newAccount Account) { + defer cdb.setLastUpdated() + cdb.db.Update(func(tx *bolt.Tx) error { + newAccount.File = filepath.Base(newAccount.File) + if newAccount.File != "" { + bf := tx.Bucket(fileBucketName) + bf.Put([]byte(newAccount.File), accountToBytes(newAccount)) + } + if (newAccount.Address != common.Address{}) { + b := tx.Bucket(addrBucketName) + return b.Put([]byte(newAccount.Address.Hex()+newAccount.File), []byte(time.Now().String())) + } + return nil + }) +} + +// note: removed needs to be unique here (i.e. both File and Address must be set). +func (cdb *cacheDB) delete(removed Account) { + defer cdb.setLastUpdated() + if e := cdb.db.Update(func(tx *bolt.Tx) error { + removed.File = filepath.Base(removed.File) + + b := tx.Bucket(fileBucketName) + if e := b.Delete([]byte(removed.File)); e != nil { + return e + } + + ba := tx.Bucket(addrBucketName) + if e := ba.Delete([]byte(removed.Address.Hex() + removed.File)); e != nil { + return e + } + return nil + }); e != nil { + glog.V(logger.Error).Infof("failed to delete from cache: %v \n%v", e, removed.File) + } +} + +// find returns the cached account for address if there is a unique match. +// The exact matching rules are explained by the documentation of Account. +// Callers must hold ac.mu. +func (cdb *cacheDB) find(a Account) (Account, error) { + + var acc Account + var matches []Account + var e error + + if a.File != "" { + acc, e = cdb.getCachedAccountByFile(a.File) + if e == nil && (acc != Account{}) { + return acc, e + } + // no other possible way + if (a.Address == common.Address{}) { + return Account{}, ErrNoMatch + } + } + + if (a.Address != common.Address{}) { + matches, e = cdb.getCachedAccountsByAddress(a.Address) + } + + switch len(matches) { + case 1: + return matches[0], e + case 0: + return Account{}, ErrNoMatch + default: + err := &AmbiguousAddrError{Addr: a.Address, Matches: make([]Account, len(matches))} + copy(err.Matches, matches) + return Account{}, err + } +} + +func (cdb *cacheDB) close() { + cdb.mu.Lock() + cdb.db.Close() + cdb.mu.Unlock() +} + +func (cdb *cacheDB) setLastUpdated() error { + return cdb.db.Update(func (tx *bolt.Tx) error { + b := tx.Bucket(statsBucketName) + return b.Put([]byte("lastUpdated"), []byte(time.Now().Add(minReloadInterval).String())) // ensure no close calls with directory mod time + }) +} + +func (cdb *cacheDB) getLastUpdated() (t time.Time, err error) { + e := cdb.db.View(func (tx *bolt.Tx) error { + b := tx.Bucket(statsBucketName) + v := b.Get([]byte("lastUpdated")) + if v == nil { + t, err = time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "1900-01-02 15:04:05.999999999 -0700 MST") + return ErrCacheDBNoUpdateStamp + } + pt, e := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", string(v)) + if e != nil { + return e + } + t = pt + return nil + }) + return t, e +} + +// setBatchAccounts sets many accounts in a single db tx. +// It saves a lot of time in disk write. +func (cdb *cacheDB) setBatchAccounts(accs []Account) (errs []error) { + if len(accs) == 0 { + return nil + } + defer cdb.setLastUpdated() + + tx, err := cdb.db.Begin(true) + if err != nil { + return append(errs, err) + } + + ba := tx.Bucket(addrBucketName) + bf := tx.Bucket(fileBucketName) + + for _, a := range accs { + // Put in byAddr bucket. + if e := ba.Put([]byte(a.Address.Hex() + a.File), []byte(time.Now().String())); e != nil { + errs = append(errs, e) + } + // Put in byFile bucket. + if e := bf.Put([]byte(a.File), accountToBytes(a)); e != nil { + errs = append(errs, e) + } + } + + if len(errs) == 0 { + // Close tx. + if err := tx.Commit(); err != nil { + return append(errs, err) + } + } else { + tx.Rollback() + } + return errs +} + +// Syncfs2db syncronises an existing cachedb with a corresponding fs. +func (cdb *cacheDB) Syncfs2db(lastUpdated time.Time) (errs []error) { + + // Check if directory was modified. Makes function somewhat idempotent... + //di, de := os.Stat(cdb.keydir) + //if de != nil { + // return append(errs, de) + //} + // ... but I don't trust/know when directory stamps get modified (ie for tests). + //dbLastMod, lue := cdb.getLastUpdated() + //if lue != nil { + // errs = append(errs, lue) + //} else { + // directoryLastMod := di.ModTime() + // if dbLastMod.After(directoryLastMod) { + // glog.V(logger.Info).Info("Directory has not been modified since DB was updated. Not syncing.") + // return errs + // } + //} + + defer cdb.setLastUpdated() + + var ( + accounts []Account + ) + + // SYNC: DB --> FS. + + // Remove all cache entries. + e := cdb.db.Update(func (tx *bolt.Tx) error { + + tx.DeleteBucket(addrBucketName) + tx.DeleteBucket(fileBucketName) + if _, e := tx.CreateBucketIfNotExists(addrBucketName); e != nil { + return e + } + if _, e := tx.CreateBucketIfNotExists(fileBucketName); e != nil { + return e + } + + return nil + }) + + files, err := ioutil.ReadDir(cdb.keydir) + if err != nil { + return append(errs, err) + } + numFiles := len(files) + + glog.V(logger.Debug).Infof("Syncing index db: %v files", numFiles) + + waitUp := &sync.WaitGroup{} + achan := make(chan Account) + echan := make(chan error) + done := make(chan bool, 1) + + // SYNC: FS --> DB. + + // Handle receiving errors/accounts. + go func(wg *sync.WaitGroup, achan chan Account, echan chan error) { + + for j := 0; j < len(files); j++ { + select { + case a := <-achan: + if (a == Account{}) { + continue + } + accounts = append(accounts, a) + if len(accounts) == 20000 { + if e := cdb.setBatchAccounts(accounts); len(e) != 0 { + for _, ee := range e { + if ee != nil { + errs = append(errs, e...) + } + } + } + accounts = nil + } + case e := <-echan: + if e != nil { + errs = append(errs, e) + } + } + } + + waitUp.Wait() + close(achan) + close(echan) + + if e := cdb.setBatchAccounts(accounts); len(e) != 0 { + for _, ee := range e { + if ee != nil { + errs = append(errs, e...) + } + } + } + + done <- true + }(waitUp, achan, echan) + + + // Iterate files. + for i, fi := range files { + + // fi.Name() is used for storing the file in the case db + // This assumes that the keystore/ dir is not designed to walk recursively. + // See testdata/keystore/foo/UTC-afd..... compared with cacheTestAccounts for + // test proof of this assumption. + path := filepath.Join(cdb.keydir, fi.Name()) + if e != nil { + errs = append(errs, e) + } + waitUp.Add(1) + // TODO: inform go routine allowance based on memory statistics + if runtime.NumGoroutine() > runtime.NumCPU()*300 { + + processKeyFile(waitUp, path, fi, i, numFiles, achan, echan) + } else { + go processKeyFile(waitUp, path, fi, i, numFiles, achan, echan) + } + } + + <-done + + accounts = nil + + for _, e := range errs { + if e != nil { + glog.V(logger.Debug).Infof("Error: %v", e) + } + } + + return errs +} + +// it is important this send one value of one of either account OR error channels +func processKeyFile(wg *sync.WaitGroup, path string, fi os.FileInfo, i int, numFiles int, aChan chan Account, errs chan error) { + defer wg.Done() + if skipKeyFile(fi) { + glog.V(logger.Debug).Infof("(%v/%v) Ignoring file %s", i, numFiles, fi.Name()) + errs <- nil + return + } else { + + glog.V(logger.Debug).Infof("(%v/%v) Adding key file to db: %v", i, numFiles, fi.Name()) + + keyJSON := struct { + Address common.Address `json:"address"` + }{} + + buf := new(bufio.Reader) + fd, err := os.Open(path) + if err != nil { + errs <- err + return + } + buf.Reset(fd) + // Parse the address. + keyJSON.Address = common.Address{} + err = json.NewDecoder(buf).Decode(&keyJSON) + fd.Close() + + web3JSON := []byte{} + web3JSON, err = ioutil.ReadFile(path) + if err != nil { + errs <- err + return + } + + switch { + case err != nil: + glog.V(logger.Debug).Infof("(%v/%v) can't decode key %s: %v", i, numFiles, path, err) + errs <- err + case (keyJSON.Address == common.Address{}): + glog.V(logger.Debug).Infof("(%v/%v) can't decode key %s: missing or zero address", i, numFiles, path) + errs <- fmt.Errorf("(%v/%v) can't decode key %s: missing or zero address", i, numFiles, path) + default: + aChan <- Account{Address: keyJSON.Address, File: fi.Name(), EncryptedKey: string(web3JSON)} + } + } +} + +func bytesToAccount(bs []byte) Account { + var aux AccountJSON + if e := easyjson.Unmarshal(bs, &aux); e != nil { + panic(e) + //return Account{} + } + return Account{ + Address: common.HexToAddress(aux.Address), + EncryptedKey: aux.EncryptedKey, + File: aux.File, + } +} + +func accountToBytes(account Account) []byte { + aux := &AccountJSON{ + Address: account.Address.Hex(), + EncryptedKey: account.EncryptedKey, + File: account.File, + } + b, e := easyjson.Marshal(aux) + if e != nil { + panic(e) + // return nil + } + return b +} \ No newline at end of file diff --git a/accounts/cachedb_test.go b/accounts/cachedb_test.go new file mode 100644 index 000000000..6662c9236 --- /dev/null +++ b/accounts/cachedb_test.go @@ -0,0 +1,469 @@ +package accounts + +import ( + "io/ioutil" + "os" + "path/filepath" + "reflect" + "sort" + "testing" + "time" + + "github.com/davecgh/go-spew/spew" + "github.com/ethereumproject/go-ethereum/common" +) + +var ( + //cachedbtestDir, _ = filepath.Abs(filepath.Join("testdata", "keystore")) + cachedbtestAccounts = []Account{ + { + Address: common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), + File: "UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8", + EncryptedKey: "{\"address\":\"7ef5a6135f1fd6a02593eedc869c6d41d934aef8\",\"crypto\":{\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"1d0839166e7a15b9c1333fc865d69858b22df26815ccf601b28219b6192974e1\",\"cipherparams\":{\"iv\":\"8df6caa7ff1b00c4e871f002cb7921ed\"},\"kdf\":\"scrypt\",\"kdfparams\":{\"dklen\":32,\"n\":8,\"p\":16,\"r\":8,\"salt\":\"e5e6ef3f4ea695f496b643ebd3f75c0aa58ef4070e90c80c5d3fb0241bf1595c\"},\"mac\":\"6d16dfde774845e4585357f24bce530528bc69f4f84e1e22880d34fa45c273e5\"},\"id\":\"950077c7-71e3-4c44-a4a1-143919141ed4\",\"version\":3}", + }, + { + Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"), + File: "aaa", + EncryptedKey: "{\"address\":\"f466859ead1932d743d622cb74fc058882e8648a\",\"crypto\":{\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d\",\"cipherparams\":{\"iv\":\"dfd9ee70812add5f4b8f89d0811c9158\"},\"kdf\":\"scrypt\",\"kdfparams\":{\"dklen\":32,\"n\":8,\"p\":16,\"r\":8,\"salt\":\"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1\"},\"mac\":\"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9\"},\"id\":\"472e8b3d-afb6-45b5-8111-72c89895099a\",\"version\":3}", + }, + { + Address: common.HexToAddress("289d485d9771714cce91d3393d764e1311907acc"), + File: "zzz", + EncryptedKey: "{\"address\":\"289d485d9771714cce91d3393d764e1311907acc\",\"crypto\":{\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"faf32ca89d286b107f5e6d842802e05263c49b78d46eac74e6109e9a963378ab\",\"cipherparams\":{\"iv\":\"558833eec4a665a8c55608d7d503407d\"},\"kdf\":\"scrypt\",\"kdfparams\":{\"dklen\":32,\"n\":8,\"p\":16,\"r\":8,\"salt\":\"d571fff447ffb24314f9513f5160246f09997b857ac71348b73e785aab40dc04\"},\"mac\":\"21edb85ff7d0dab1767b9bf498f2c3cb7be7609490756bd32300bb213b59effe\"},\"id\":\"3279afcf-55ba-43ff-8997-02dcc46a6525\",\"version\":3}", + }, + } +) + +// Setup/teardown. +func TestMain(m *testing.M) { + m.Run() +} +// +//func TestWatchNewFile_CacheDB(t *testing.T) { +// t.Parallel() +// +// dir, am := tmpManager_CacheDB(t) +// defer os.RemoveAll(dir) +// +// // Ensure the watcher is started before adding any files. +// am.Accounts() +// time.Sleep(5 * time.Second) +// if w := am.ac.getWatcher(); !w.running { +// t.Fatalf("watcher not running after %v: %v", 5*time.Second, spew.Sdump(w)) +// } +// +// initAccs := am.Accounts() +// if len(initAccs) != 0 { +// t.Fatalf("initial accounts not empty: %v", len(initAccs)) +// } +// initAccs = nil +// +// // Move in the files. +// wantAccounts := make([]Account, len(cachedbtestAccounts)) +// for i := range cachedbtestAccounts { +// a := cachedbtestAccounts[i] +// //a.File = filepath.Join(dir, filepath.Base(a.File)) // rename test file to base from temp dir +// wantAccounts[i] = a +// data, err := ioutil.ReadFile(filepath.Join(cachetestDir, cachedbtestAccounts[i].File)) // but we still have to read from original file path +// if err != nil { +// t.Fatal(err) +// } +// // write to temp dir +// if err := ioutil.WriteFile(filepath.Join(dir, a.File), data, 0666); err != nil { +// t.Fatal(err) +// } +// } +// sort.Sort(accountsByFile(wantAccounts)) +// +// // am should see the accounts. +// var list []Account +// for d := 200 * time.Millisecond; d <= 2 * minReloadInterval; d *= 2 { +// list = am.Accounts() +// if reflect.DeepEqual(list, wantAccounts) { +// return +// } +// time.Sleep(d) +// } +// t.Errorf("got %s, want %s", spew.Sdump(list), spew.Sdump(wantAccounts)) +//} + +//func TestWatchNoDir_CacheDB(t *testing.T) { +// t.Parallel() +// +// // Create am but not the directory that it watches. +// rand.Seed(time.Now().UnixNano()) +// dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-watch-test-%d-%d", os.Getpid(), rand.Int())) +// am, err := NewManager(dir, LightScryptN, LightScryptP, true) +// if err != nil { +// t.Fatal(err) +// } +// +// list := am.Accounts() +// if len(list) > 0 { +// t.Error("initial account list not empty:", list) +// } +// time.Sleep(5 * time.Second) +// if w := am.ac.getWatcher(); !w.running { +// t.Fatalf("watcher not running after %v: %v", 5*time.Second, spew.Sdump(w)) +// } +// +// // Create the directory and copy a key file into it. +// os.MkdirAll(dir, 0700) +// defer os.RemoveAll(dir) +// +// file := filepath.Join(dir, cachedbtestAccounts[0].File) +// data, err := ioutil.ReadFile(filepath.Join(cachetestDir, cachedbtestAccounts[0].File)) +// if err != nil { +// t.Fatal(err) +// } +// ff, err := os.Create(file) +// if err != nil { +// t.Fatal(err) +// } +// _, err = ff.Write(data) +// if err != nil { +// t.Fatal(err) +// } +// ff.Close() +// +// // am should see the account. +// wantAccounts := []Account{cachedbtestAccounts[0]} +// var gotAccounts []Account +// for d := 500 * time.Millisecond; d <= 2 * minReloadInterval; d *= 2 { +// gotAccounts = am.Accounts() +// if reflect.DeepEqual(gotAccounts, wantAccounts) { +// return +// } +// time.Sleep(d) +// } +// t.Errorf("account watcher never saw changes: got: %v, want: %v", spew.Sdump(gotAccounts), spew.Sdump(wantAccounts)) +//} + +func TestCacheInitialReload_CacheDB(t *testing.T) { + + cache := newCacheDB(cachetestDir) + + accounts := cache.accounts() + + if !reflect.DeepEqual(accounts, cachedbtestAccounts) { + t.Errorf("got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachedbtestAccounts)) + } +} + +func TestCacheAddDeleteOrder_CacheDB(t *testing.T) { + cache := newCacheDB("testdata/no-such-dir") + defer os.RemoveAll("testdata/no-such-dir") + + accounts := []Account{ + { + Address: common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), + File: "-309830980", + }, + { + Address: common.HexToAddress("2cac1adea150210703ba75ed097ddfe24e14f213"), + File: "ggg", + }, + { + Address: common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), + File: "zzzzzz-the-very-last-one.keyXXX", + }, + { + Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"), + File: "SOMETHING.key", + }, + { + Address: common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), + File: "UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8", + }, + { + Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"), + File: "aaa", + }, + { + Address: common.HexToAddress("289d485d9771714cce91d3393d764e1311907acc"), + File: "zzz", + }, + } + for _, a := range accounts { + cache.add(a) + } + // Add some of them twice to check that they don't get reinserted. + cache.add(accounts[0]) + cache.add(accounts[2]) + + // Check that the account list is sorted by filename. + wantAccounts := make([]Account, len(accounts)) + copy(wantAccounts, accounts) + sort.Sort(accountsByFile(wantAccounts)) + list := cache.accounts() + if !reflect.DeepEqual(list, wantAccounts) { + t.Fatalf("got accounts: %s\nwant %s", spew.Sdump(accounts), spew.Sdump(wantAccounts)) + } + for _, a := range accounts { + if !cache.hasAddress(a.Address) { + t.Errorf("expected hasAccount(%x) to return true", a.Address) + } + } + if cache.hasAddress(common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e")) { + t.Errorf("expected hasAccount(%x) to return false", common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e")) + } + + // Delete a few keys from the cache. + for i := 0; i < len(accounts); i += 2 { + cache.delete(wantAccounts[i]) + } + cache.delete(Account{Address: common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e"), File: "something"}) + + // Check content again after deletion. + wantAccountsAfterDelete := []Account{ + wantAccounts[1], + wantAccounts[3], + wantAccounts[5], + } + list = cache.accounts() + if !reflect.DeepEqual(list, wantAccountsAfterDelete) { + t.Fatalf("got accounts after delete: %s\nwant %s", spew.Sdump(list), spew.Sdump(wantAccountsAfterDelete)) + } + for _, a := range wantAccountsAfterDelete { + if !cache.hasAddress(a.Address) { + t.Errorf("expected hasAccount(%x) to return true", a.Address) + } + } + if cache.hasAddress(wantAccounts[0].Address) { + t.Errorf("expected hasAccount(%x) to return false", wantAccounts[0].Address) + } +} + +func TestCacheFind_CacheFind(t *testing.T) { + dir := filepath.Join("testdata", "dir") + defer os.RemoveAll(dir) + cache := newCacheDB(dir) + + accounts := []Account{ + { + Address: common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), + File: "a.key", + }, + { + Address: common.HexToAddress("2cac1adea150210703ba75ed097ddfe24e14f213"), + File: "b.key", + }, + { + Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"), + File: "c.key", + }, + { + Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"), + File: "c2.key", + }, + } + for _, a := range accounts { + cache.add(a) + } + + if lca := cache.accounts(); len(lca) != len(accounts) { + t.Fatalf("wrong number of accounts, got: %v, want: %v", len(lca), len(accounts)) + } + + if !reflect.DeepEqual(cache.accounts(), accounts) { + t.Fatalf("not matching initial accounts: got %v, want: %v", spew.Sdump(cache.accounts()), spew.Sdump(accounts)) + } + + nomatchAccount := Account{ + Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"), + File: filepath.Join(dir, "something"), + } + tests := []struct { + Query Account + WantResult Account + WantError error + }{ + // by address + {Query: Account{Address: accounts[0].Address}, WantResult: accounts[0]}, + // by file + {Query: Account{File: accounts[0].File}, WantResult: accounts[0]}, + // by basename + {Query: Account{File: filepath.Base(accounts[0].File)}, WantResult: accounts[0]}, + // by file and address + {Query: accounts[0], WantResult: accounts[0]}, + // ambiguous address, tie resolved by file + {Query: accounts[2], WantResult: accounts[2]}, + // ambiguous address error + { + Query: Account{Address: accounts[2].Address}, + WantError: &AmbiguousAddrError{ + Addr: accounts[2].Address, + Matches: []Account{accounts[2], accounts[3]}, + }, + }, + // no match error + {Query: nomatchAccount, WantError: ErrNoMatch}, + {Query: Account{File: nomatchAccount.File}, WantError: ErrNoMatch}, + {Query: Account{File: filepath.Base(nomatchAccount.File)}, WantError: ErrNoMatch}, + {Query: Account{Address: nomatchAccount.Address}, WantError: ErrNoMatch}, + } + for i, test := range tests { + a, err := cache.find(test.Query) + if !reflect.DeepEqual(err, test.WantError) { + t.Errorf("test %d: error mismatch for query %v\ngot %q\nwant %q", i, test.Query, err, test.WantError) + continue + } + if a != test.WantResult { + t.Errorf("test %d: result mismatch for query %v\ngot %v\nwant %v", i, test.Query, a, test.WantResult) + continue + } + } +} + +func TestAccountCache_CacheDB_SyncFS2DB(t *testing.T) { + // setup temp dir + tmpDir, e := ioutil.TempDir("", "cachedb-remover-test") + if e != nil { + t.Fatalf("create temp dir: %v", e) + } + defer os.RemoveAll(tmpDir) + + // make manager in temp dir + ma, e := NewManager(tmpDir, veryLightScryptN, veryLightScryptP, true) + if e != nil { + t.Errorf("create manager in temp dir: %v", e) + } + // test manager has no accounts + initAccs := ma.Accounts() + if !reflect.DeepEqual(initAccs, []Account{}) { + t.Errorf("got %v, want: %v", spew.Sdump(initAccs), spew.Sdump([]Account{})) + } + // close manager + ma.ac.close() + ma = nil + + // copy 3 key files to temp dir + for _, acc := range cachedbtestAccounts { + data, err := ioutil.ReadFile(filepath.Join(cachetestDir, acc.File)) + if err != nil { + t.Fatal(err) + } + ff, err := os.Create(filepath.Join(tmpDir, acc.File)) + if err != nil { + t.Fatal(err) + } + _, err = ff.Write(data) + if err != nil { + t.Fatal(err) + } + ff.Close() + } + + // restart manager in temp dir + ma, e = NewManager(tmpDir, veryLightScryptN, veryLightScryptP, true) + if e != nil { + t.Errorf("create manager in temp dir: %v", e) + } + + ma.ac.Syncfs2db(time.Now()) + + // test manager has 3 accounts + initAccs = ma.Accounts() + if !reflect.DeepEqual(initAccs, cachedbtestAccounts) { + t.Errorf("got %v, want: %v", spew.Sdump(initAccs), spew.Sdump(cachedbtestAccounts)) + } + + // close manager + ma.ac.close() + ma = nil + + // remove 1 key file from temp dir + rmPath := filepath.Join(tmpDir, cachedbtestAccounts[0].File) + if e := os.Remove(rmPath); e != nil { + t.Fatalf("removing key file: %v", e) + } + + // restart manager in temp dir + ma, e = NewManager(tmpDir, veryLightScryptN, veryLightScryptP, true) + if e != nil { + t.Errorf("create manager in temp dir: %v", e) + } + ma.ac.Syncfs2db(time.Now()) + + // test manager has 2 accounts + initAccs = ma.Accounts() + if !reflect.DeepEqual(initAccs, cachedbtestAccounts[1:]) { + t.Errorf("got %v, want: %v", spew.Sdump(initAccs), spew.Sdump(cachedbtestAccounts[1:])) + } + ma.ac.close() + ma = nil +} + +//func TestAccountCache_CacheDB_WatchRemove(t *testing.T) { +// t.Parallel() +// +// // setup temp dir +// rp := fmt.Sprintf("eth-keystore-watch-cachedb-test-%d-%d", os.Getpid(), rand.Int()) +// tmpDir, e := ioutil.TempDir("", rp) +// if e != nil { +// t.Fatalf("create temp dir: %v", e) +// } +// defer os.RemoveAll(tmpDir) +// +// // copy 3 test account files into temp dir +// for _, acc := range cachedbtestAccounts { +// data, err := ioutil.ReadFile(filepath.Join(cachetestDir, acc.File)) +// if err != nil { +// t.Fatal(err) +// } +// ff, err := os.Create(filepath.Join(tmpDir, acc.File)) +// if err != nil { +// t.Fatal(err) +// } +// _, err = ff.Write(data) +// if err != nil { +// t.Fatal(err) +// } +// ff.Close() +// } +// +// // make manager in temp dir +// ma, e := NewManager(tmpDir, veryLightScryptN, veryLightScryptP, true) +// if e != nil { +// t.Errorf("create manager in temp dir: %v", e) +// } +// +// // test manager has all accounts +// initAccs := ma.Accounts() +// if !reflect.DeepEqual(initAccs, cachedbtestAccounts) { +// t.Errorf("got %v, want: %v", spew.Sdump(initAccs), spew.Sdump(cachedbtestAccounts)) +// } +// time.Sleep(2 * time.Second) +// +// // test watcher is watching +// if w := ma.ac.getWatcher(); !w.running { +// t.Errorf("watcher not running") +// } +// +// // remove file +// rmPath := filepath.Join(tmpDir, cachedbtestAccounts[0].File) +// if e := os.Remove(rmPath); e != nil { +// t.Fatalf("removing key file: %v", e) +// } +// // ensure it's gone +// if _, e := os.Stat(filepath.Join(tmpDir, cachedbtestAccounts[0].File)); e == nil { +// t.Fatalf("removed file not actually rm'd") +// } +// +// // test manager does not have account +// wantAccounts := cachedbtestAccounts[1:] +// if len(wantAccounts) != 2 { +// t.Errorf("dummy") +// } +// +// gotAccounts := []Account{} +// for d := 500 * time.Millisecond; d <= 2 * minReloadInterval; d *= 2 { +// gotAccounts = ma.Accounts() +// // If it's ever all the same, we're good. Exit with aplomb. +// if reflect.DeepEqual(gotAccounts, wantAccounts) { +// return +// } +// time.Sleep(d) +// } +// t.Errorf("got: %v, want: %v", spew.Sdump(gotAccounts), spew.Sdump(wantAccounts)) +//} \ No newline at end of file diff --git a/accounts/keystore.go b/accounts/keystore.go index 4900fc6d5..96ee78bc1 100644 --- a/accounts/keystore.go +++ b/accounts/keystore.go @@ -158,6 +158,14 @@ func newKeyStore(dir string, scryptN, scryptP int) (*keyStore, error) { }, nil } +func (store *keyStore) DecryptKey (data []byte, secret string) (*key, error) { + key, err := decryptKey(data, secret) + if err != nil { + return nil, err + } + return key, nil +} + func (store *keyStore) Lookup(file string, secret string) (*key, error) { if !filepath.IsAbs(file) { file = filepath.Join(store.baseDir, file) diff --git a/accounts/manager.go b/accounts/manager.go index f5a95bcae..99d11cf99 100644 --- a/accounts/manager.go +++ b/accounts/manager.go @@ -22,7 +22,6 @@ package accounts import ( "crypto/ecdsa" - "encoding/json" "errors" "fmt" "os" @@ -32,6 +31,8 @@ import ( "github.com/ethereumproject/go-ethereum/common" "github.com/ethereumproject/go-ethereum/crypto" + "path/filepath" + "encoding/json" ) var ( @@ -46,6 +47,7 @@ var ( // When used as an argument, it selects a unique key file to act on. type Account struct { Address common.Address // Ethereum account address derived from the key + EncryptedKey string // web3JSON format // File contains the key file name. // When Acccount is used as an argument to select a key, File can be left blank to @@ -54,6 +56,14 @@ type Account struct { File string } +// AccountJSON is an auxiliary between Account and EasyMarshal'd structs. +//easyjson:json +type AccountJSON struct { + Address string `json:"address"` + EncryptedKey string `json:"key"` + File string `json:"file"` +} + func (acc *Account) MarshalJSON() ([]byte, error) { return []byte(`"` + acc.Address.Hex() + `"`), nil } @@ -64,7 +74,7 @@ func (acc *Account) UnmarshalJSON(raw []byte) error { // Manager manages a key storage directory on disk. type Manager struct { - cache *addrCache + ac caching keyStore keyStore mu sync.RWMutex unlocked map[common.Address]*unlocked @@ -89,7 +99,7 @@ const ( ) // NewManager creates a manager for the given directory. -func NewManager(keydir string, scryptN, scryptP int) (*Manager, error) { +func NewManager(keydir string, scryptN, scryptP int, wantCacheDB bool) (*Manager, error) { store, err := newKeyStore(keydir, scryptN, scryptP) if err != nil { return nil, err @@ -98,27 +108,42 @@ func NewManager(keydir string, scryptN, scryptP int) (*Manager, error) { am := &Manager{ keyStore: *store, unlocked: make(map[common.Address]*unlocked), - cache: newAddrCache(keydir), + } + if wantCacheDB { + am.ac = newCacheDB(keydir) + } else { + am.ac = newAddrCache(keydir) } // TODO: In order for this finalizer to work, there must be no references // to am. addrCache doesn't keep a reference but unlocked keys do, // so the finalizer will not trigger until all timed unlocks have expired. runtime.SetFinalizer(am, func(m *Manager) { - m.cache.close() + // bug(whilei): I was getting panic: close of closed channel when running tests as package; + // individually each test would pass but not when run in a bunch. + // either manager reference was stuck somewhere or the tests were outpacing themselves + // checking for nil seems to fix the issue. + if am.ac != nil { + m.ac.close() + } + }) return am, nil } +func (am *Manager) BuildIndexDB() []error { + return am.ac.Syncfs2db(time.Now().Add(-60*24*7*30*120*time.Minute)) // arbitrarily long "last updated" +} + // HasAddress reports whether a key with the given address is present. func (am *Manager) HasAddress(addr common.Address) bool { - return am.cache.hasAddress(addr) + return am.ac.hasAddress(addr) } // Accounts returns all key files present in the directory. func (am *Manager) Accounts() []Account { - return am.cache.accounts() + return am.ac.accounts() } // DeleteAccount deletes the key matched by account if the passphrase is correct. @@ -134,12 +159,18 @@ func (am *Manager) DeleteAccount(a Account, passphrase string) error { if err != nil { return err } + + if !filepath.IsAbs(a.File) { + p := filepath.Join(am.ac.getKeydir(), a.File) + a.File = p + } + // The order is crucial here. The key is dropped from the // cache after the file is gone so that a reload happening in // between won't insert it into the cache again. err = os.Remove(a.File) if err == nil { - am.cache.delete(a) + am.ac.delete(a) } return err } @@ -148,6 +179,7 @@ func (am *Manager) DeleteAccount(a Account, passphrase string) error { func (am *Manager) Sign(addr common.Address, hash []byte) (signature []byte, err error) { am.mu.RLock() defer am.mu.RUnlock() + unlockedKey, found := am.unlocked[addr] if !found { return nil, ErrLocked @@ -222,15 +254,21 @@ func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Durati } func (am *Manager) getDecryptedKey(a Account, auth string) (Account, *key, error) { - am.cache.maybeReload() - am.cache.mu.Lock() - a, err := am.cache.find(a) - am.cache.mu.Unlock() + am.ac.maybeReload() + am.ac.muLock() + a, err := am.ac.find(a) + am.ac.muUnlock() if err != nil { return Account{}, nil, err } - key, err := am.keyStore.Lookup(a.File, auth) + key := &key{} + if a.EncryptedKey != "" { + key, err = am.keyStore.DecryptKey([]byte(a.EncryptedKey), auth) + } else { + key, err = am.keyStore.Lookup(a.File, auth) + } + if err != nil { return Account{}, nil, err } @@ -270,7 +308,7 @@ func (am *Manager) NewAccount(passphrase string) (Account, error) { } // Add the account to the cache immediately rather // than waiting for file system notifications to pick it up. - am.cache.add(account) + am.ac.add(account) return account, nil } @@ -311,7 +349,7 @@ func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Accou return Account{}, err } - if am.cache.hasAddress(key.Address) { + if am.ac.hasAddress(key.Address) { return Account{}, fmt.Errorf("account already exists") } @@ -325,7 +363,7 @@ func (am *Manager) importKey(key *key, passphrase string) (Account, error) { } a := Account{File: file, Address: key.Address} - am.cache.add(a) + am.ac.add(a) return a, nil } @@ -345,7 +383,7 @@ func (am *Manager) ImportPreSaleKey(keyJSON []byte, passphrase string) (Account, if err != nil { return a, err } - am.cache.add(a) + am.ac.add(a) return a, nil } diff --git a/accounts/manager_easyjson.go b/accounts/manager_easyjson.go new file mode 100644 index 000000000..2d9da48c3 --- /dev/null +++ b/accounts/manager_easyjson.go @@ -0,0 +1,103 @@ +// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT. + +package accounts + +import ( + json "encoding/json" + + easyjson "github.com/mailru/easyjson" + jlexer "github.com/mailru/easyjson/jlexer" + jwriter "github.com/mailru/easyjson/jwriter" +) + +// suppress unused package warning +var ( + _ *json.RawMessage + _ *jlexer.Lexer + _ *jwriter.Writer + _ easyjson.Marshaler +) + +func easyjsonEd74d837DecodeGithubComEthereumprojectGoEthereumAccounts(in *jlexer.Lexer, out *AccountJSON) { + isTopLevel := in.IsStart() + if in.IsNull() { + if isTopLevel { + in.Consumed() + } + in.Skip() + return + } + in.Delim('{') + for !in.IsDelim('}') { + key := in.UnsafeString() + in.WantColon() + if in.IsNull() { + in.Skip() + in.WantComma() + continue + } + switch key { + case "address": + out.Address = string(in.String()) + case "key": + out.EncryptedKey = string(in.String()) + case "file": + out.File = string(in.String()) + default: + in.SkipRecursive() + } + in.WantComma() + } + in.Delim('}') + if isTopLevel { + in.Consumed() + } +} +func easyjsonEd74d837EncodeGithubComEthereumprojectGoEthereumAccounts(out *jwriter.Writer, in AccountJSON) { + out.RawByte('{') + first := true + _ = first + if !first { + out.RawByte(',') + } + first = false + out.RawString("\"address\":") + out.String(string(in.Address)) + if !first { + out.RawByte(',') + } + first = false + out.RawString("\"key\":") + out.String(string(in.EncryptedKey)) + if !first { + out.RawByte(',') + } + first = false + out.RawString("\"file\":") + out.String(string(in.File)) + out.RawByte('}') +} + +// MarshalJSON supports json.Marshaler interface +func (v AccountJSON) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + easyjsonEd74d837EncodeGithubComEthereumprojectGoEthereumAccounts(&w, v) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalEasyJSON supports easyjson.Marshaler interface +func (v AccountJSON) MarshalEasyJSON(w *jwriter.Writer) { + easyjsonEd74d837EncodeGithubComEthereumprojectGoEthereumAccounts(w, v) +} + +// UnmarshalJSON supports json.Unmarshaler interface +func (v *AccountJSON) UnmarshalJSON(data []byte) error { + r := jlexer.Lexer{Data: data} + easyjsonEd74d837DecodeGithubComEthereumprojectGoEthereumAccounts(&r, v) + return r.Error() +} + +// UnmarshalEasyJSON supports easyjson.Unmarshaler interface +func (v *AccountJSON) UnmarshalEasyJSON(l *jlexer.Lexer) { + easyjsonEd74d837DecodeGithubComEthereumprojectGoEthereumAccounts(l, v) +} diff --git a/accounts/manager_test.go b/accounts/manager_test.go index fc90f1a6f..2cd1f621c 100644 --- a/accounts/manager_test.go +++ b/accounts/manager_test.go @@ -23,11 +23,29 @@ import ( "strings" "testing" "time" + "reflect" + "github.com/davecgh/go-spew/spew" + "fmt" + "math/rand" ) var testSigData = make([]byte, 32) -func TestManager(t *testing.T) { +func tmpManager(t *testing.T) (string, *Manager) { + rand.Seed(time.Now().UnixNano()) + dir, err := ioutil.TempDir("", fmt.Sprintf("eth-manager-mem-test-%d-%d", os.Getpid(), rand.Int())) + if err != nil { + t.Fatal(err) + } + + m, err := NewManager(dir, veryLightScryptN, veryLightScryptP, false) + if err != nil { + t.Fatal(err) + } + return dir, m +} + +func TestManager_Mem(t *testing.T) { dir, am := tmpManager(t) defer os.RemoveAll(dir) @@ -62,7 +80,36 @@ func TestManager(t *testing.T) { } } -func TestSignWithPassphrase(t *testing.T) { +func TestManager_Accounts_Mem(t *testing.T) { + am, err := NewManager(cachetestDir, LightScryptN, LightScryptP, false) + if err != nil { + t.Fatal(err) + } + accounts := am.Accounts() + if !reflect.DeepEqual(accounts, cachetestAccounts) { + t.Fatalf("mem got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachetestAccounts)) + } +} + +func TestManager_AccountsByIndex(t *testing.T) { + am, err := NewManager(cachetestDir, LightScryptN, LightScryptP, false) + if err != nil { + t.Fatal(err) + } + + for i := range cachetestAccounts { + wantAccount := cachetestAccounts[i] + gotAccount, e := am.AccountByIndex(i) + if e != nil { + t.Fatalf("manager cache mem #accountsbyindex: %v", e) + } + if !reflect.DeepEqual(wantAccount, gotAccount) { + t.Fatalf("want: %v, got: %v", wantAccount, gotAccount) + } + } +} + +func TestSignWithPassphrase_Mem(t *testing.T) { dir, am := tmpManager(t) defer os.RemoveAll(dir) @@ -90,7 +137,8 @@ func TestSignWithPassphrase(t *testing.T) { } } -func TestTimedUnlock(t *testing.T) { +// unlocks newly created account in temp dir +func TestTimedUnlock_Mem(t *testing.T) { dir, am := tmpManager(t) defer os.RemoveAll(dir) @@ -122,7 +170,35 @@ func TestTimedUnlock(t *testing.T) { } } -func TestOverrideUnlock(t *testing.T) { +// unlocks account from manager created in existing testdata/keystore dir +func TestTimedUnlock_Mem2(t *testing.T) { + am, err := NewManager(cachetestDir, veryLightScryptN, veryLightScryptP, false) + if err != nil { + t.Fatal(err) + } + + a1 := cachetestAccounts[1] + + // Signing with passphrase works + if err := am.TimedUnlock(a1, "foobar", 100*time.Millisecond); err != nil { + t.Fatal(err) + } + + // Signing without passphrase works because account is temp unlocked + _, err = am.Sign(a1.Address, testSigData) + if err != nil { + t.Fatal("Signing shouldn't return an error after unlocking, got ", err) + } + + // Signing fails again after automatic locking + time.Sleep(250 * time.Millisecond) + _, err = am.Sign(a1.Address, testSigData) + if err != ErrLocked { + t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) + } +} + +func TestOverrideUnlock_Mem(t *testing.T) { dir, am := tmpManager(t) defer os.RemoveAll(dir) @@ -160,7 +236,7 @@ func TestOverrideUnlock(t *testing.T) { } // This test should fail under -race if signing races the expiration goroutine. -func TestSignRace(t *testing.T) { +func TestSignRace_Mem(t *testing.T) { dir, am := tmpManager(t) defer os.RemoveAll(dir) @@ -183,18 +259,5 @@ func TestSignRace(t *testing.T) { } time.Sleep(1 * time.Millisecond) } - t.Errorf("Account did not lock within the timeout") -} - -func tmpManager(t *testing.T) (string, *Manager) { - dir, err := ioutil.TempDir("", "eth-keystore-test") - if err != nil { - t.Fatal(err) - } - - m, err := NewManager(dir, veryLightScryptN, veryLightScryptP) - if err != nil { - t.Fatal(err) - } - return dir, m + t.Error("Account did not lock within the timeout") } diff --git a/accounts/managerdb_test.go b/accounts/managerdb_test.go new file mode 100644 index 000000000..17174a501 --- /dev/null +++ b/accounts/managerdb_test.go @@ -0,0 +1,272 @@ +package accounts + +import ( + "testing" + "time" + "os" + "strings" + "fmt" + "runtime" + "io/ioutil" + "math/rand" + "reflect" + "github.com/davecgh/go-spew/spew" + "path/filepath" +) + +func tmpManager_CacheDB(t *testing.T) (string, *Manager) { + rand.Seed(time.Now().UnixNano()) + dir, err := ioutil.TempDir("", fmt.Sprintf("eth-manager-cachedb-test-%d-%d", os.Getpid(), rand.Int())) + if err != nil { + t.Fatal(err) + } + + m, err := NewManager(dir, veryLightScryptN, veryLightScryptP, true) + if err != nil { + t.Fatal(err) + } + return dir, m +} + +func TestManager_DB(t *testing.T) { + + dir, am := tmpManager_CacheDB(t) + defer os.RemoveAll(dir) + + a, err := am.NewAccount("foo") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(a.File, dir) { + t.Errorf("account file %s doesn't have dir prefix", a.File) + } + stat, err := os.Stat(a.File) + if err != nil { + t.Fatalf("account file %s doesn't exist (%v)", a.File, err) + } + if runtime.GOOS != "windows" && stat.Mode() != 0600 { + t.Fatalf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600) + } + if !am.HasAddress(a.Address) { + t.Errorf("HasAddres(%x) should've returned true", a.Address) + } + if err := am.Update(a, "foo", "bar"); err != nil { + t.Errorf("Update error: %v", err) + } + if err := am.DeleteAccount(a, "bar"); err != nil { + t.Errorf("DeleteAccount error: %v", err) + } + if _, err := os.Stat(a.File); err == nil || !os.IsNotExist(err) { + t.Errorf("account file %s should be gone after DeleteAccount", a.File) + } + if am.HasAddress(a.Address) { + t.Errorf("HasAddress(%x) should've returned true after DeleteAccount", a.Address) + } + am.ac.close() + am = nil +} + +func TestManager_Accounts_CacheDB(t *testing.T) { + // bug(whilei): I don't know why you have to do rm. + // Running the file as a standalone test is no problem. + // Running the suite (ie go test -v ./accounts/), it hangs here. + // Again, I think it has to do with test concurrency. + os.Remove(filepath.Join(cachetestDir, "accounts.db")) + am, err := NewManager(cachetestDir, LightScryptN, LightScryptP, true) + if err != nil { + t.Fatal(err) + } + am.ac.Syncfs2db(time.Now()) + accounts := am.Accounts() + if !reflect.DeepEqual(accounts, cachedbtestAccounts) { + t.Fatalf("cachedb got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachedbtestAccounts)) + } + am.ac.close() + am = nil +} + +func TestManager_AccountsByIndex_CacheDB(t *testing.T) { + os.Remove(filepath.Join(cachetestDir, "accounts.db")) + am, err := NewManager(cachetestDir, LightScryptN, LightScryptP, true) + if err != nil { + t.Fatal(err) + } + am.ac.Syncfs2db(time.Now()) + + for i := range cachedbtestAccounts { + wantAccount := cachedbtestAccounts[i] + gotAccount, e := am.AccountByIndex(i) + if e != nil { + t.Fatalf("manager cache db #accountsbyindex: %v", e) + } + if !reflect.DeepEqual(wantAccount, gotAccount) { + t.Fatalf("got: %v, want: %v", spew.Sdump(gotAccount), spew.Sdump(wantAccount)) + } + } + am.ac.close() + am = nil +} + +func TestSignWithPassphrase_DB(t *testing.T) { + dir, am := tmpManager_CacheDB(t) + defer os.RemoveAll(dir) + + pass := "passwd" + acc, err := am.NewAccount(pass) + if err != nil { + t.Fatal(err) + } + + if _, unlocked := am.unlocked[acc.Address]; unlocked { + t.Fatal("expected account to be locked") + } + + _, err = am.SignWithPassphrase(acc.Address, pass, testSigData) + if err != nil { + t.Fatal(err) + } + + if _, unlocked := am.unlocked[acc.Address]; unlocked { + t.Fatal("expected account to be locked") + } + + if _, err = am.SignWithPassphrase(acc.Address, "invalid passwd", testSigData); err == nil { + t.Fatal("expected SignHash to fail with invalid password") + } + am.ac.close() + am = nil +} + +func TestTimedUnlock_DB(t *testing.T) { + dir, am := tmpManager_CacheDB(t) + defer os.RemoveAll(dir) + + pass := "foo" + a1, err := am.NewAccount(pass) + + // Signing without passphrase fails because account is locked + _, err = am.Sign(a1.Address, testSigData) + if err != ErrLocked { + t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err) + } + + // Signing with passphrase works + if err = am.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil { + t.Fatal(err) + } + + // Signing without passphrase works because account is temp unlocked + _, err = am.Sign(a1.Address, testSigData) + if err != nil { + t.Fatal("Signing shouldn't return an error after unlocking, got ", err) + } + + // Signing fails again after automatic locking + time.Sleep(250 * time.Millisecond) + _, err = am.Sign(a1.Address, testSigData) + if err != ErrLocked { + t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) + } + am.ac.close() + am = nil +} + +func TestOverrideUnlock_DB(t *testing.T) { + dir, am := tmpManager_CacheDB(t) + defer os.RemoveAll(dir) + + pass := "foo" + a1, err := am.NewAccount(pass) + + // Unlock indefinitely. + if err = am.TimedUnlock(a1, pass, 5*time.Minute); err != nil { + t.Fatal(err) + } + + // Signing without passphrase works because account is temp unlocked + _, err = am.Sign(a1.Address, testSigData) + if err != nil { + t.Fatal("Signing shouldn't return an error after unlocking, got ", err) + } + + // reset unlock to a shorter period, invalidates the previous unlock + if err = am.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil { + t.Fatal(err) + } + + // Signing without passphrase still works because account is temp unlocked + _, err = am.Sign(a1.Address, testSigData) + if err != nil { + t.Fatal("Signing shouldn't return an error after unlocking, got ", err) + } + + // Signing fails again after automatic locking + time.Sleep(250 * time.Millisecond) + _, err = am.Sign(a1.Address, testSigData) + if err != ErrLocked { + t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) + } + am.ac.close() + am = nil +} + +// unlocks account from manager created in existing testdata/keystore dir +func TestTimedUnlock_DB2(t *testing.T) { + + am, err := NewManager(cachetestDir, veryLightScryptN, veryLightScryptP, true) + if err != nil { + t.Fatal(err) + } + + a1 := cachetestAccounts[1] + + // Signing with passphrase works + if err := am.TimedUnlock(a1, "foobar", 100*time.Millisecond); err != nil { + t.Fatal(err) + } + + // Signing without passphrase works because account is temp unlocked + _, err = am.Sign(a1.Address, testSigData) + if err != nil { + t.Fatal("Signing shouldn't return an error after unlocking, got ", err) + } + + // Signing fails again after automatic locking + time.Sleep(250 * time.Millisecond) + _, err = am.Sign(a1.Address, testSigData) + if err != ErrLocked { + t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) + } + am.ac.close() + am = nil +} + + +// This test should fail under -race if signing races the expiration goroutine. +func TestSignRace_DB(t *testing.T) { + dir, am := tmpManager_CacheDB(t) + defer os.RemoveAll(dir) + + // Create a test account. + a1, err := am.NewAccount("") + if err != nil { + t.Fatal("could not create the test account", err) + } + + if err := am.TimedUnlock(a1, "", 15*time.Millisecond); err != nil { + t.Fatal("could not unlock the test account", err) + } + end := time.Now().Add(500 * time.Millisecond) + for time.Now().Before(end) { + if _, err := am.Sign(a1.Address, testSigData); err == ErrLocked { + return + } else if err != nil { + t.Errorf("Sign error: %v", err) + return + } + time.Sleep(1 * time.Millisecond) + } + t.Error("Account did not lock within the timeout") + am.ac.close() + am = nil +} diff --git a/accounts/testdata/benchmark_results/BenchmarkAccountFlow100Fast_in_manager_benchmarks_test_go.html b/accounts/testdata/benchmark_results/BenchmarkAccountFlow100Fast_in_manager_benchmarks_test_go.html new file mode 100644 index 000000000..e4b8a21cd --- /dev/null +++ b/accounts/testdata/benchmark_results/BenchmarkAccountFlow100Fast_in_manager_benchmarks_test_go.html @@ -0,0 +1,609 @@ + + + + +Test Results — BenchmarkAccountFlow100Fast in manager_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    23 ms
    +
    passedBenchmarkAccountFlow100Fast
    +
      +
    • +100 26860804 ns/op
      --- BENCH: BenchmarkAccountFlow100Fast-2
      manager_benchmarks_test.go:205: removing testdata keystore
      manager_benchmarks_test.go:239: setup time for cache: 163.521158ms
      manager_benchmarks_test.go:247: files: 2, accounts: 2
      manager_benchmarks_test.go:255: setup time for manager: 264.924001ms
      manager_benchmarks_test.go:205: removing testdata keystore
      manager_benchmarks_test.go:239: setup time for cache: 245.865776ms
      manager_benchmarks_test.go:247: files: 11, accounts: 11
      manager_benchmarks_test.go:255: setup time for manager: 141.235116ms
      manager_benchmarks_test.go:205: removing testdata keystore
      manager_benchmarks_test.go:239: setup time for cache: 418.954254ms
      ... [output truncated]
      PASS
      Process finished with exit code 0
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go-to20k.html b/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go-to20k.html new file mode 100644 index 000000000..9dbbbb565 --- /dev/null +++ b/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go-to20k.html @@ -0,0 +1,724 @@ + + + + +Test Results — BenchmarkAccountFlowScaling in manager_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    2.41 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:true-2
    +
      +
    • +100 24925111 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 212.975703ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 24.520169ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 29.203876ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 35.221074ms
      +
    • +
    +
  • +
  • + +
    2.99 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:false-2
    +
      +
    • +100 22233228 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 29.927166ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 27.316429ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 77.894848ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 22.244841ms
      +
    • +
    +
  • +
  • + +
    5.16 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:true-2
    +
      +
    • +100 24203154 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 271.518618ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 118.131787ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 51.09664ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 88.595512ms
      +
    • +
    +
  • +
  • + +
    5.19 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:false-2
    +
      +
    • +100 45006617 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 137.549985ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 130.990309ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 134.767976ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 220.571442ms
      +
    • +
    +
  • +
  • + +
    3.04 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:true-2
    +
      +
    • +50 26493611 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 1.268633593s
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 336.276726ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 227.155971ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 304.101404ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 247.756081ms
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    9.23 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:false-2
    +
      +
    • +50 29450880 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 374.045648ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 421.392432ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 322.757007ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 345.667261ms
      +
    • +
    +
  • +
  • + +
    7.37 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:true-2
    +
      +
    • +50 25277729 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2.897009674s
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 1.380366497s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 647.259443ms
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 804.259087ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 496.317944ms
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    14.26 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:false-2
    +
      +
    • +50 30061424 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 979.240805ms
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 897.133112ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 796.820749ms
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 780.790993ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 899.45848ms
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    16.05 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:true-2
    +
      +
    • +50 34539930 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 5.946551437s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 2.540158373s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 1.350949907s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 2.061050968s
      +
    • +
    +
  • +
  • + +
    33.80 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:false-2
    +
      +
    • +50 31121693 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 4.183841021s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.936779721s
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 1.709278543s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.551064465s
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 1.874526666s
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    20.13 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:true-2
    +
      +
    • +30 39365578 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 22.512707688s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 3.103199916s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2.281424651s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 3.486707915s
      +
    • +
    +
  • +
  • + +
    7 m 31 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:false-2
    +
      +
    • +50 55362930 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 3.512253868s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 3.693148722s
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 3.684216903s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 5.562605294s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2m33.594659052s
      manager_benchmarks_test.go:282: accounts/files count mismatch: keyfiles: 102275, accounts: 102274
      manager_benchmarks_test.go:295: setup time for manager: 3m44.134143281s
      Process finished with exit code 130 (interrupted by signal 2: SIGINT)
      +
    • +
    +
  • +
  • + +
    6 m 34 s
    +
    failedBenchmarkAccountFlowScaling/KeyFiles#:100000,_CacheFromScratch:true
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go_to100k.html b/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go_to100k.html new file mode 100644 index 000000000..82c4f0001 --- /dev/null +++ b/accounts/testdata/benchmark_results/BenchmarkAccountFlowScaling_in_manager_benchmarks_test_go_to100k.html @@ -0,0 +1,732 @@ + + + + +Test Results — BenchmarkAccountFlowScaling in manager_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    2.28 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:true-2
    +
      +
    • +100 35732762 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 142.554848ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 20.886503ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 21.396212ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 19.702057ms
      +
    • +
    +
  • +
  • + +
    3.01 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:false-2
    +
      +
    • +100 21054876 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:100,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 77.362359ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 24.582713ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 21.197ms
      manager_benchmarks_test.go:284: files: 101, accounts: 101
      manager_benchmarks_test.go:295: setup time for manager: 23.92464ms
      +
    • +
    +
  • +
  • + +
    2.75 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:true-2
    +
      +
    • +100 23928439 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 275.560197ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 75.695811ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 54.203227ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 69.689492ms
      +
    • +
    +
  • +
  • + +
    5.06 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:false-2
    +
      +
    • +100 24243834 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:500,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 75.840107ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 71.299309ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 78.864261ms
      manager_benchmarks_test.go:284: files: 501, accounts: 501
      manager_benchmarks_test.go:295: setup time for manager: 70.806848ms
      +
    • +
    +
  • +
  • + +
    3.99 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:true-2
    +
      +
    • +100 25529793 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 1.053875423s
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 235.859453ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 284.852208ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 242.556118ms
      +
    • +
    +
  • +
  • + +
    24.24 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:false-2
    +
      +
    • +30 55557713 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:1000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 541.419271ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 540.596881ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 549.990134ms
      manager_benchmarks_test.go:284: files: 2000, accounts: 2000
      manager_benchmarks_test.go:295: setup time for manager: 550.495666ms
      +
    • +
    +
  • +
  • + +
    6.82 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:true-2
    +
      +
    • +100 27998865 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 17.538801875s
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 736.146596ms
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 510.595821ms
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 611.434522ms
      +
    • +
    +
  • +
  • + +
    15.43 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:false-2
    +
      +
    • +100 29291272 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:5000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 1.35616044s
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 712.139439ms
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 749.346366ms
      manager_benchmarks_test.go:284: files: 5001, accounts: 5001
      manager_benchmarks_test.go:295: setup time for manager: 812.696503ms
      +
    • +
    +
  • +
  • + +
    15.97 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:true-2
    +
      +
    • +30 41441215 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 6.554966245s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.494605502s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2.585497467s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.546883209s
      +
    • +
    +
  • +
  • + +
    47.73 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:false-2
    +
      +
    • +100 99081186 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:10000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 1.327025555s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.385727415s
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 1.530928576s
      manager_benchmarks_test.go:284: files: 10001, accounts: 10001
      manager_benchmarks_test.go:295: setup time for manager: 1.369154852s
      +
    • +
    +
  • +
  • + +
    16.09 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:true-2
    +
      +
    • +50 45948028 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 27.469240073s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 2.690861576s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 5.044602079s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 2.714802266s
      +
    • +
    +
  • +
  • + +
    19 m 5 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:false-2
    +
      +
    • +20 68412488 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:20000,_CacheFromScratch:false-2
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 3.279509025s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 3.02247039s
      manager_benchmarks_test.go:247: using existing cache and keystore
      manager_benchmarks_test.go:276: setup time for cache: 3.403255459s
      manager_benchmarks_test.go:284: files: 20001, accounts: 20001
      manager_benchmarks_test.go:295: setup time for manager: 3.916542683s
      +
    • +
    +
  • +
  • + +
    22 m 1 s
    +
    passedBenchmarkAccountFlowScaling/KeyFiles#:100000,_CacheFromScratch:true-2
    +
      +
    • +20 70379149 ns/op
      --- BENCH: BenchmarkAccountFlowScaling/KeyFiles#:100000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2m38.061283212s
      manager_benchmarks_test.go:284: files: 102275, accounts: 102274
      manager_benchmarks_test.go:295: setup time for manager: 3m28.782144982s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2m9.872309251s
      manager_benchmarks_test.go:284: files: 102275, accounts: 102274
      manager_benchmarks_test.go:295: setup time for manager: 4m53.633345674s
      manager_benchmarks_test.go:244: removing existing cache
      manager_benchmarks_test.go:276: setup time for cache: 2m8.317416763s
      ... [output truncated]
      Process finished with exit code 130 (interrupted by signal 2: SIGINT)
      +
    • +
    +
  • +
  • +skippedBenchmarkAccountFlowScaling/KeyFiles#:100000,_CacheFromScratch:false-2 +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/BenchmarkAccountSignScaling_in_manager_benchmarks_test_go.html b/accounts/testdata/benchmark_results/BenchmarkAccountSignScaling_in_manager_benchmarks_test_go.html new file mode 100644 index 000000000..aee3051dd --- /dev/null +++ b/accounts/testdata/benchmark_results/BenchmarkAccountSignScaling_in_manager_benchmarks_test_go.html @@ -0,0 +1,669 @@ + + + + +Test Results — BenchmarkAccountSignScaling in manager_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    2.03 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:100,_CacheFromScratch:true-2
    +
      +
    • +1000 1242289 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:100,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 37.94468ms
      manager_benchmarks_test.go:302: files: 101, accounts: 101
      manager_benchmarks_test.go:305: setup time for manager: 39.5565ms
      manager_benchmarks_test.go:160: signing with account index: 85
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 23.525302ms
      manager_benchmarks_test.go:302: files: 101, accounts: 101
      manager_benchmarks_test.go:305: setup time for manager: 24.836877ms
      manager_benchmarks_test.go:160: signing with account index: 45
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    3.26 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:500,_CacheFromScratch:true-2
    +
      +
    • +500 2937388 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:500,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 81.421491ms
      manager_benchmarks_test.go:302: files: 501, accounts: 501
      manager_benchmarks_test.go:305: setup time for manager: 88.036877ms
      manager_benchmarks_test.go:160: signing with account index: 31
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 74.154747ms
      manager_benchmarks_test.go:302: files: 501, accounts: 501
      manager_benchmarks_test.go:305: setup time for manager: 80.33761ms
      manager_benchmarks_test.go:160: signing with account index: 96
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    9.14 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:1000,_CacheFromScratch:true-2
    +
      +
    • +100 10195839 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:1000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 1.299158785s
      manager_benchmarks_test.go:302: files: 2000, accounts: 2000
      manager_benchmarks_test.go:305: setup time for manager: 1.329710375s
      manager_benchmarks_test.go:160: signing with account index: 782
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 315.392714ms
      manager_benchmarks_test.go:302: files: 2000, accounts: 2000
      manager_benchmarks_test.go:305: setup time for manager: 348.410302ms
      manager_benchmarks_test.go:160: signing with account index: 167
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    11.88 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:5000,_CacheFromScratch:true-2
    +
      +
    • +100 25598822 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:5000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 3.49594792s
      manager_benchmarks_test.go:302: files: 5001, accounts: 5001
      manager_benchmarks_test.go:305: setup time for manager: 3.58991851s
      manager_benchmarks_test.go:160: signing with account index: 3211
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 821.305373ms
      manager_benchmarks_test.go:302: files: 5001, accounts: 5001
      manager_benchmarks_test.go:305: setup time for manager: 896.035204ms
      manager_benchmarks_test.go:160: signing with account index: 574
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    27.33 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:10000,_CacheFromScratch:true-2
    +
      +
    • +30 50116811 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:10000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 6.17533518s
      manager_benchmarks_test.go:302: files: 10001, accounts: 10001
      manager_benchmarks_test.go:305: setup time for manager: 6.331251404s
      manager_benchmarks_test.go:160: signing with account index: 2956
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 1.946968915s
      manager_benchmarks_test.go:302: files: 10001, accounts: 10001
      manager_benchmarks_test.go:305: setup time for manager: 2.092279532s
      manager_benchmarks_test.go:160: signing with account index: 4474
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    9 m 23 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:20000,_CacheFromScratch:true-2
    +
      +
    • +20 122902501 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:20000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 17.644467843s
      manager_benchmarks_test.go:302: files: 20001, accounts: 20001
      manager_benchmarks_test.go:305: setup time for manager: 17.998734796s
      manager_benchmarks_test.go:160: signing with account index: 17629
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 3.341426456s
      manager_benchmarks_test.go:302: files: 20001, accounts: 20001
      manager_benchmarks_test.go:305: setup time for manager: 3.659512701s
      manager_benchmarks_test.go:160: signing with account index: 8898
      ... [output truncated]
      +
    • +
    +
  • +
  • + +
    25 m 3 s
    +
    passedBenchmarkAccountSignScaling/KeyFiles#:100000,_CacheFromScratch:true-2
    +
      +
    • +2 650279609 ns/op
      --- BENCH: BenchmarkAccountSignScaling/KeyFiles#:100000,_CacheFromScratch:true-2
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 6m3.273311256s
      manager_benchmarks_test.go:302: files: 102275, accounts: 102274
      manager_benchmarks_test.go:305: setup time for manager: 6m4.964938893s
      manager_benchmarks_test.go:160: signing with account index: 85527
      manager_benchmarks_test.go:258: removing existing cache
      manager_benchmarks_test.go:295: setup time for manager: 2m52.623593005s
      manager_benchmarks_test.go:302: files: 102275, accounts: 102274
      manager_benchmarks_test.go:305: setup time for manager: 2m54.323583328s
      manager_benchmarks_test.go:160: signing with account index: 61780
      ... [output truncated]
      Process finished with exit code 130 (interrupted by signal 2: SIGINT)
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/BenchmarkCacheFind100000_in_cache_benchmarks_test_go-kvdb.html b/accounts/testdata/benchmark_results/BenchmarkCacheFind100000_in_cache_benchmarks_test_go-kvdb.html new file mode 100644 index 000000000..67d5309d0 --- /dev/null +++ b/accounts/testdata/benchmark_results/BenchmarkCacheFind100000_in_cache_benchmarks_test_go-kvdb.html @@ -0,0 +1,609 @@ + + + + +Test Results — BenchmarkCacheFind100000 in cache_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    138 ms
    +
    passedBenchmarkCacheFind100000
    +
      +
    • +1 36203740387 ns/op
      --- BENCH: BenchmarkCacheFind100000-2
      cache_benchmarks_test.go:142: establishing cache for 100000 accs: 2m0.011038962s
      PASS
      Process finished with exit code 0
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/gobench_account_benchmarks_test_go.html b/accounts/testdata/benchmark_results/gobench_account_benchmarks_test_go.html new file mode 100644 index 000000000..e36c514d5 --- /dev/null +++ b/accounts/testdata/benchmark_results/gobench_account_benchmarks_test_go.html @@ -0,0 +1,659 @@ + + + + +Test Results — gobench account_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    3.66 s
    +
    passedBenchmarkAccountFlow100
    +
      +
    • +200 6377202 ns/op
      --- BENCH: BenchmarkAccountFlow100-2
      account_benchmarks_test.go:83: setting up 100 accounts took 224.694142ms
      account_benchmarks_test.go:83: setting up 100 accounts took 144.149999ms
      account_benchmarks_test.go:83: setting up 100 accounts took 95.905249ms
      +
    • +
    +
  • +
  • + +
    7.77 s
    +
    passedBenchmarkAccountFlow500
    +
      +
    • +200 6719782 ns/op
      --- BENCH: BenchmarkAccountFlow500-2
      account_benchmarks_test.go:83: setting up 500 accounts took 844.38401ms
      account_benchmarks_test.go:83: setting up 500 accounts took 536.546008ms
      account_benchmarks_test.go:83: setting up 500 accounts took 634.408408ms
      +
    • +
    +
  • +
  • + +
    43.27 s
    +
    passedBenchmarkAccountFlow1000
    +
      +
    • +200 8408826 ns/op
      --- BENCH: BenchmarkAccountFlow1000-2
      account_benchmarks_test.go:83: setting up 1000 accounts took 1.158953785s
      account_benchmarks_test.go:83: setting up 1000 accounts took 968.942643ms
      account_benchmarks_test.go:83: setting up 1000 accounts took 2.133768535s
      account_benchmarks_test.go:83: setting up 1000 accounts took 967.430774ms
      +
    • +
    +
  • +
  • + +
    20.62 s
    +
    passedBenchmarkAccountFlow5000
    +
      +
    • +20 60688053 ns/op
      --- BENCH: BenchmarkAccountFlow5000-2
      account_benchmarks_test.go:83: setting up 5000 accounts took 7.904508069s
      account_benchmarks_test.go:83: setting up 5000 accounts took 8.954979697s
      account_benchmarks_test.go:83: setting up 5000 accounts took 7.610294052s
      account_benchmarks_test.go:83: setting up 5000 accounts took 7.700995201s
      account_benchmarks_test.go:83: setting up 5000 accounts took 7.194188575s
      +
    • +
    +
  • +
  • + +
    1 m 3 s
    +
    passedBenchmarkAccountFlow10000
    +
      +
    • +1 1992894048 ns/op
      --- BENCH: BenchmarkAccountFlow10000-2
      account_benchmarks_test.go:83: setting up 10000 accounts took 18.624211928s
      +
    • +
    +
  • +
  • + +
    21 ms
    +
    passedBenchmarkAccountFlow20000
    +
      +
    • +1 3442054123 ns/op
      --- BENCH: BenchmarkAccountFlow20000-2
      account_benchmarks_test.go:83: setting up 20000 accounts took 59.300116346s
      PASS
      Process finished with exit code 0
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go-kvdb.html b/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go-kvdb.html new file mode 100644 index 000000000..6495bbe87 --- /dev/null +++ b/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go-kvdb.html @@ -0,0 +1,779 @@ + + + + +Test Results — gobench cache_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    5.22 s
    +
    passedBenchmarkCacheAccounts100
    +
      +
    • +3000 433817 ns/op
      --- BENCH: BenchmarkCacheAccounts100-2
      cache_benchmarks_test.go:41: establishing cache for 100 accs: 21.281047ms
      cache_benchmarks_test.go:41: establishing cache for 100 accs: 29.047351ms
      cache_benchmarks_test.go:41: establishing cache for 100 accs: 26.552284ms
      +
    • +
    +
  • +
  • + +
    20.50 s
    +
    passedBenchmarkCacheAccounts500
    +
      +
    • +1000 1575225 ns/op
      --- BENCH: BenchmarkCacheAccounts500-2
      cache_benchmarks_test.go:41: establishing cache for 500 accs: 88.421201ms
      cache_benchmarks_test.go:41: establishing cache for 500 accs: 59.501207ms
      cache_benchmarks_test.go:41: establishing cache for 500 accs: 54.22553ms
      cache_benchmarks_test.go:41: establishing cache for 500 accs: 56.884377ms
      +
    • +
    +
  • +
  • + +
    38.41 s
    +
    passedBenchmarkCacheAccounts1000
    +
      +
    • +200 9392068 ns/op
      --- BENCH: BenchmarkCacheAccounts1000-2
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 256.675245ms
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 270.345547ms
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 419.532238ms
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 240.156793ms
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 202.555396ms
      cache_benchmarks_test.go:41: establishing cache for 1000 accs: 235.892895ms
      +
    • +
    +
  • +
  • + +
    1 m 14 s
    +
    passedBenchmarkCacheAccounts5000
    +
      +
    • +10 372678014 ns/op
      --- BENCH: BenchmarkCacheAccounts5000-2
      cache_benchmarks_test.go:41: establishing cache for 5000 accs: 602.190682ms
      cache_benchmarks_test.go:41: establishing cache for 5000 accs: 640.365624ms
      cache_benchmarks_test.go:41: establishing cache for 5000 accs: 621.5478ms
      cache_benchmarks_test.go:41: establishing cache for 5000 accs: 600.498733ms
      cache_benchmarks_test.go:41: establishing cache for 5000 accs: 2.008598558s
      +
    • +
    +
  • +
  • + +
    1 m 44 s
    +
    passedBenchmarkCacheAccounts10000
    +
      +
    • +1 6548891979 ns/op
      --- BENCH: BenchmarkCacheAccounts10000-2
      cache_benchmarks_test.go:41: establishing cache for 10000 accs: 19.12188566s
      +
    • +
    +
  • +
  • + +
    5.11 s
    +
    passedBenchmarkCacheAccounts20000
    +
      +
    • +1 5148997456 ns/op
      --- BENCH: BenchmarkCacheAccounts20000-2
      cache_benchmarks_test.go:41: establishing cache for 20000 accs: 14.212803178s
      +
    • +
    +
  • +
  • + +
    14.57 s
    +
    passedBenchmarkCacheAdd100
    +
      +
    • +200 16995173 ns/op
      --- BENCH: BenchmarkCacheAdd100-2
      cache_benchmarks_test.go:93: establishing cache for 100 accs: 20.074916ms
      cache_benchmarks_test.go:93: establishing cache for 100 accs: 19.458885ms
      cache_benchmarks_test.go:93: establishing cache for 100 accs: 20.37763ms
      +
    • +
    +
  • +
  • + +
    26.99 s
    +
    passedBenchmarkCacheAdd500
    +
      +
    • +20 91683873 ns/op
      --- BENCH: BenchmarkCacheAdd500-2
      cache_benchmarks_test.go:93: establishing cache for 500 accs: 75.496123ms
      cache_benchmarks_test.go:93: establishing cache for 500 accs: 201.557569ms
      cache_benchmarks_test.go:93: establishing cache for 500 accs: 276.957909ms
      +
    • +
    +
  • +
  • + +
    34.65 s
    +
    passedBenchmarkCacheAdd1000
    +
      +
    • +100 16802860 ns/op
      --- BENCH: BenchmarkCacheAdd1000-2
      cache_benchmarks_test.go:93: establishing cache for 1000 accs: 268.221564ms
      cache_benchmarks_test.go:93: establishing cache for 1000 accs: 796.47272ms
      cache_benchmarks_test.go:93: establishing cache for 1000 accs: 323.507085ms
      cache_benchmarks_test.go:93: establishing cache for 1000 accs: 335.940805ms
      cache_benchmarks_test.go:93: establishing cache for 1000 accs: 423.823171ms
      +
    • +
    +
  • +
  • + +
    1 m 59 s
    +
    passedBenchmarkCacheAdd5000
    +
      +
    • +2 542475035 ns/op
      --- BENCH: BenchmarkCacheAdd5000-2
      cache_benchmarks_test.go:93: establishing cache for 5000 accs: 3.040898764s
      cache_benchmarks_test.go:93: establishing cache for 5000 accs: 684.860342ms
      +
    • +
    +
  • +
  • + +
    1 m 11 s
    +
    passedBenchmarkCacheAdd10000
    +
      +
    • +1 2730458794 ns/op
      --- BENCH: BenchmarkCacheAdd10000-2
      cache_benchmarks_test.go:93: establishing cache for 10000 accs: 21.397036711s
      +
    • +
    +
  • +
  • + +
    0 ms
    +
    passedBenchmarkCacheAdd20000
    +
      +
    • +1 6780362618 ns/op
      --- BENCH: BenchmarkCacheAdd20000-2
      cache_benchmarks_test.go:93: establishing cache for 20000 accs: 2.788197492s
      +
    • +
    +
  • +
  • + +
    13.54 s
    +
    passedBenchmarkCacheFind100
    +
      +
    • +30000 42118 ns/op
      --- BENCH: BenchmarkCacheFind100-2
      cache_benchmarks_test.go:142: establishing cache for 100 accs: 22.57341ms
      cache_benchmarks_test.go:142: establishing cache for 100 accs: 44.327657ms
      cache_benchmarks_test.go:142: establishing cache for 100 accs: 78.066461ms
      cache_benchmarks_test.go:142: establishing cache for 100 accs: 20.440855ms
      +
    • +
    +
  • +
  • + +
    12.70 s
    +
    passedBenchmarkCacheFind500
    +
      +
    • +20000 63051 ns/op
      --- BENCH: BenchmarkCacheFind500-2
      cache_benchmarks_test.go:142: establishing cache for 500 accs: 66.120837ms
      cache_benchmarks_test.go:142: establishing cache for 500 accs: 62.933027ms
      cache_benchmarks_test.go:142: establishing cache for 500 accs: 318.242429ms
      cache_benchmarks_test.go:142: establishing cache for 500 accs: 82.992834ms
      +
    • +
    +
  • +
  • + +
    24.70 s
    +
    passedBenchmarkCacheFind1000
    +
      +
    • +500 2596306 ns/op
      --- BENCH: BenchmarkCacheFind1000-2
      cache_benchmarks_test.go:142: establishing cache for 1000 accs: 527.020399ms
      cache_benchmarks_test.go:142: establishing cache for 1000 accs: 296.943762ms
      cache_benchmarks_test.go:142: establishing cache for 1000 accs: 289.333909ms
      cache_benchmarks_test.go:142: establishing cache for 1000 accs: 258.270982ms
      cache_benchmarks_test.go:142: establishing cache for 1000 accs: 882.97661ms
      +
    • +
    +
  • +
  • + +
    59.72 s
    +
    passedBenchmarkCacheFind5000
    +
      +
    • +1 1248069276 ns/op
      --- BENCH: BenchmarkCacheFind5000-2
      cache_benchmarks_test.go:142: establishing cache for 5000 accs: 675.404345ms
      +
    • +
    +
  • +
  • + +
    1 m 8 s
    +
    passedBenchmarkCacheFind10000
    +
      +
    • +1 4211006480 ns/op
      --- BENCH: BenchmarkCacheFind10000-2
      cache_benchmarks_test.go:142: establishing cache for 10000 accs: 1.837125111s
      +
    • +
    +
  • +
  • + +
    1 ms
    +
    passedBenchmarkCacheFind20000
    +
      +
    • +1 5994037085 ns/op
      --- BENCH: BenchmarkCacheFind20000-2
      cache_benchmarks_test.go:142: establishing cache for 20000 accs: 2.572403418s
      PASS
      Process finished with exit code 0
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go.html b/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go.html new file mode 100644 index 000000000..e2b7f0f28 --- /dev/null +++ b/accounts/testdata/benchmark_results/gobench_cache_benchmarks_test_go.html @@ -0,0 +1,909 @@ + + + + +Test Results — gobench cache_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    1.44 s
    +
    passedBenchmarkCacheAccounts100
    +
      +
    • +3000 434397 ns/op
      --- BENCH: BenchmarkCacheAccounts100-2
      cache_benchmarks_test.go:32: establishing cache for 100 accs: 5.130101ms
      cache_benchmarks_test.go:32: establishing cache for 100 accs: 3.883681ms
      cache_benchmarks_test.go:32: establishing cache for 100 accs: 4.402677ms
      cache_benchmarks_test.go:32: establishing cache for 100 accs: 3.704741ms
      +
    • +
    +
  • +
  • + +
    1.17 s
    +
    passedBenchmarkCacheAccounts500
    +
      +
    • +500 2214490 ns/op
      --- BENCH: BenchmarkCacheAccounts500-2
      cache_benchmarks_test.go:32: establishing cache for 500 accs: 6.699653ms
      cache_benchmarks_test.go:32: establishing cache for 500 accs: 8.991376ms
      cache_benchmarks_test.go:32: establishing cache for 500 accs: 5.785804ms
      +
    • +
    +
  • +
  • + +
    2.32 s
    +
    passedBenchmarkCacheAccounts1000
    +
      +
    • +100 10887682 ns/op
      --- BENCH: BenchmarkCacheAccounts1000-2
      cache_benchmarks_test.go:32: establishing cache for 1000 accs: 6.068964ms
      cache_benchmarks_test.go:32: establishing cache for 1000 accs: 8.436565ms
      +
    • +
    +
  • +
  • + +
    1.39 s
    +
    passedBenchmarkCacheAccounts5000
    +
      +
    • +50 27254377 ns/op
      --- BENCH: BenchmarkCacheAccounts5000-2
      cache_benchmarks_test.go:32: establishing cache for 5000 accs: 4.378312ms
      cache_benchmarks_test.go:32: establishing cache for 5000 accs: 4.146479ms
      cache_benchmarks_test.go:32: establishing cache for 5000 accs: 4.105339ms
      +
    • +
    +
  • +
  • + +
    5.17 s
    +
    passedBenchmarkCacheAccounts10000
    +
      +
    • +20 55995882 ns/op
      --- BENCH: BenchmarkCacheAccounts10000-2
      cache_benchmarks_test.go:32: establishing cache for 10000 accs: 4.232035ms
      cache_benchmarks_test.go:32: establishing cache for 10000 accs: 4.75007ms
      +
    • +
    +
  • +
  • + +
    4 m 24 s
    +
    passedBenchmarkCacheAccounts20000
    +
      +
    • +1 4839684491 ns/op
      --- BENCH: BenchmarkCacheAccounts20000-2
      cache_benchmarks_test.go:32: establishing cache for 20000 accs: 25.373979ms
      cache_benchmarks_test.go:32: establishing cache for 100000 accs: 45.331149ms
      cache_benchmarks_test.go:39: cacheaccount/files mismatch: cacheacounts: 102274, files: 102275
      cache_benchmarks_test.go:32: establishing cache for 500000 accs: 117.366375ms
      cache_benchmarks_test.go:39: cacheaccount/files mismatch: cacheacounts: 270000, files: 500001
      +
    • +
    +
  • +
  • + +
    43.49 s
    +
    failedBenchmarkCacheAccounts100000
    +
  • +
  • + +
    4 m 22 s
    +
    failedBenchmarkCacheAccounts500000
    +
  • +
  • + +
    1.33 s
    +
    passedBenchmarkCacheAdd100
    +
      +
    • +20 84673014 ns/op
      --- BENCH: BenchmarkCacheAdd100-2
      cache_benchmarks_test.go:78: establishing cache for 100 accs: 48.656261ms
      cache_benchmarks_test.go:78: establishing cache for 100 accs: 4.02753ms
      +
    • +
    +
  • +
  • + +
    2.49 s
    +
    passedBenchmarkCacheAdd500
    +
      +
    • +30 41468462 ns/op
      --- BENCH: BenchmarkCacheAdd500-2
      cache_benchmarks_test.go:78: establishing cache for 500 accs: 35.30715ms
      cache_benchmarks_test.go:78: establishing cache for 500 accs: 5.745184ms
      +
    • +
    +
  • +
  • + +
    2.13 s
    +
    passedBenchmarkCacheAdd1000
    +
      +
    • +30 60002994 ns/op
      --- BENCH: BenchmarkCacheAdd1000-2
      cache_benchmarks_test.go:78: establishing cache for 1000 accs: 66.538312ms
      cache_benchmarks_test.go:78: establishing cache for 1000 accs: 5.040161ms
      cache_benchmarks_test.go:78: establishing cache for 1000 accs: 8.577603ms
      +
    • +
    +
  • +
  • + +
    4.71 s
    +
    passedBenchmarkCacheAdd5000
    +
      +
    • +30 49478967 ns/op
      --- BENCH: BenchmarkCacheAdd5000-2
      cache_benchmarks_test.go:78: establishing cache for 5000 accs: 220.05183ms
      cache_benchmarks_test.go:78: establishing cache for 5000 accs: 5.494888ms
      cache_benchmarks_test.go:78: establishing cache for 5000 accs: 4.662998ms
      +
    • +
    +
  • +
  • + +
    1.94 s
    +
    passedBenchmarkCacheAdd10000
    +
      +
    • +20 58029842 ns/op
      --- BENCH: BenchmarkCacheAdd10000-2
      cache_benchmarks_test.go:78: establishing cache for 10000 accs: 239.83154ms
      cache_benchmarks_test.go:78: establishing cache for 10000 accs: 109.932668ms
      cache_benchmarks_test.go:78: establishing cache for 10000 accs: 22.576432ms
      cache_benchmarks_test.go:78: establishing cache for 10000 accs: 40.115009ms
      cache_benchmarks_test.go:78: establishing cache for 10000 accs: 6.078025ms
      +
    • +
    +
  • +
  • + +
    3.09 s
    +
    passedBenchmarkCacheAdd20000
    +
      +
    • +30 41492334 ns/op
      --- BENCH: BenchmarkCacheAdd20000-2
      cache_benchmarks_test.go:78: establishing cache for 20000 accs: 60.204804ms
      cache_benchmarks_test.go:78: establishing cache for 20000 accs: 5.034289ms
      cache_benchmarks_test.go:78: establishing cache for 20000 accs: 5.269119ms
      +
    • +
    +
  • +
  • + +
    2.89 s
    +
    passedBenchmarkCacheAdd100000
    +
      +
    • +20 93526923 ns/op
      --- BENCH: BenchmarkCacheAdd100000-2
      cache_benchmarks_test.go:78: establishing cache for 100000 accs: 87.548516ms
      cache_benchmarks_test.go:78: establishing cache for 100000 accs: 10.637192ms
      cache_benchmarks_test.go:78: establishing cache for 100000 accs: 7.171697ms
      +
    • +
    +
  • +
  • + +
    2.08 s
    +
    passedBenchmarkCacheAdd500000
    +
      +
    • +10 162532131 ns/op
      --- BENCH: BenchmarkCacheAdd500000-2
      cache_benchmarks_test.go:78: establishing cache for 500000 accs: 82.856923ms
      cache_benchmarks_test.go:78: establishing cache for 500000 accs: 14.389393ms
      cache_benchmarks_test.go:78: establishing cache for 500000 accs: 98.082942ms
      +
    • +
    +
  • +
  • + +
    2.32 s
    +
    passedBenchmarkCacheFind100
    +
      +
    • +30000 42234 ns/op
      --- BENCH: BenchmarkCacheFind100-2
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 24.697653ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 4.306602ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 4.264659ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 83.81965ms
      +
    • +
    +
  • +
  • + +
    4.08 s
    +
    passedBenchmarkCacheFind500
    +
      +
    • +50000 31611 ns/op
      --- BENCH: BenchmarkCacheFind500-2
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 59.090965ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 9.046244ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 4.090376ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 6.698421ms
      +
    • +
    +
  • +
  • + +
    3.43 s
    +
    passedBenchmarkCacheFind1000
    +
      +
    • +50000 33702 ns/op
      --- BENCH: BenchmarkCacheFind1000-2
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 16.644853ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 5.09637ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 57.596635ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 43.140187ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 7.401ms
      +
    • +
    +
  • +
  • + +
    6.46 s
    +
    passedBenchmarkCacheFind5000
    +
      +
    • +50000 28632 ns/op
      --- BENCH: BenchmarkCacheFind5000-2
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 20.921666ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 41.281122ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 3.383304ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 5.518601ms
      +
    • +
    +
  • +
  • + +
    21.34 s
    +
    passedBenchmarkCacheFind10000
    +
      +
    • +50000 30852 ns/op
      --- BENCH: BenchmarkCacheFind10000-2
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 102.564183ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 7.725566ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 6.097058ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 5.660287ms
      +
    • +
    +
  • +
  • + +
    44.05 s
    +
    passedBenchmarkCacheFind20000
    +
      +
    • +50000 31883 ns/op
      --- BENCH: BenchmarkCacheFind20000-2
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 21.834358ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 5.880463ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 6.013156ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 12.901998ms
      +
    • +
    +
  • +
  • + +
    2 m 19 s
    +
    passedBenchmarkCacheFind100000
    +
      +
    • +50000 33579 ns/op
      --- BENCH: BenchmarkCacheFind100000-2
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 43.466658ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 9.528022ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 9.138373ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 28.950903ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 17.549608ms
      +
    • +
    +
  • +
  • + +
    2.41 s
    +
    passedBenchmarkCacheFind500000
    +
      +
    • +30000 37301 ns/op
      --- BENCH: BenchmarkCacheFind500000-2
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 138.702543ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 51.674986ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 61.99408ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 9.071671ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 18.7083ms
      +
    • +
    +
  • +
  • + +
    3.16 s
    +
    passedBenchmarkCacheFind100OnlyExisting
    +
      +
    • +50000 34692 ns/op
      --- BENCH: BenchmarkCacheFind100OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 78.429751ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 4.159572ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 3.969306ms
      cache_benchmarks_test.go:121: establishing cache for 100 accs: 6.258552ms
      +
    • +
    +
  • +
  • + +
    6.49 s
    +
    passedBenchmarkCacheFind500OnlyExisting
    +
      +
    • +30000 35155 ns/op
      --- BENCH: BenchmarkCacheFind500OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 183.878245ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 12.034228ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 4.60545ms
      cache_benchmarks_test.go:121: establishing cache for 500 accs: 120.93647ms
      +
    • +
    +
  • +
  • + +
    3.51 s
    +
    passedBenchmarkCacheFind1000OnlyExisting
    +
      +
    • +50000 39392 ns/op
      --- BENCH: BenchmarkCacheFind1000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 94.003447ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 112.063077ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 30.163878ms
      cache_benchmarks_test.go:121: establishing cache for 1000 accs: 55.974073ms
      +
    • +
    +
  • +
  • + +
    5.67 s
    +
    passedBenchmarkCacheFind5000OnlyExisting
    +
      +
    • +30000 38393 ns/op
      --- BENCH: BenchmarkCacheFind5000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 56.338554ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 4.532574ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 5.30663ms
      cache_benchmarks_test.go:121: establishing cache for 5000 accs: 61.745435ms
      +
    • +
    +
  • +
  • + +
    7.98 s
    +
    passedBenchmarkCacheFind10000OnlyExisting
    +
      +
    • +50000 39084 ns/op
      --- BENCH: BenchmarkCacheFind10000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 60.858815ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 4.492851ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 7.458046ms
      cache_benchmarks_test.go:121: establishing cache for 10000 accs: 7.281596ms
      +
    • +
    +
  • +
  • + +
    1 m 8 s
    +
    passedBenchmarkCacheFind20000OnlyExisting
    +
      +
    • +50000 36456 ns/op
      --- BENCH: BenchmarkCacheFind20000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 60.065026ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 5.039528ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 6.73507ms
      cache_benchmarks_test.go:121: establishing cache for 20000 accs: 11.552259ms
      +
    • +
    +
  • +
  • + +
    1 m 34 s
    +
    passedBenchmarkCacheFind100000OnlyExisting
    +
      +
    • +50000 37137 ns/op
      --- BENCH: BenchmarkCacheFind100000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 176.113766ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 93.64281ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 11.175224ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 14.059861ms
      cache_benchmarks_test.go:121: establishing cache for 100000 accs: 204.130267ms
      +
    • +
    +
  • +
  • + +
    88 ms
    +
    passedBenchmarkCacheFind500000OnlyExisting
    +
      +
    • +30000 37095 ns/op
      --- BENCH: BenchmarkCacheFind500000OnlyExisting-2
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 78.77702ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 10.068361ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 8.807031ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 29.177191ms
      cache_benchmarks_test.go:121: establishing cache for 500000 accs: 8.563907ms
      FAIL
      Process finished with exit code 1
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/benchmark_results/gobench_manager_benchmarks_test_go.html b/accounts/testdata/benchmark_results/gobench_manager_benchmarks_test_go.html new file mode 100644 index 000000000..61076641e --- /dev/null +++ b/accounts/testdata/benchmark_results/gobench_manager_benchmarks_test_go.html @@ -0,0 +1,759 @@ + + + + +Test Results — gobench manager_benchmarks_test.go + + + + + + + + + +
+ +
+
    +
  • + +
    4.12 s
    +
    passedBenchmarkManager_SignWithPassphrase100
    +
      +
    • +500 3298326 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase100-2
      manager_benchmarks_test.go:309: establishing manager for 100 accs: 109.002763ms
      manager_benchmarks_test.go:309: establishing manager for 100 accs: 60.44696ms
      manager_benchmarks_test.go:309: establishing manager for 100 accs: 3.045473ms
      +
    • +
    +
  • +
  • + +
    2.96 s
    +
    passedBenchmarkManager_SignWithPassphrase500
    +
      +
    • +500 3276475 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase500-2
      manager_benchmarks_test.go:309: establishing manager for 500 accs: 33.418506ms
      manager_benchmarks_test.go:309: establishing manager for 500 accs: 58.884629ms
      manager_benchmarks_test.go:309: establishing manager for 500 accs: 59.746996ms
      +
    • +
    +
  • +
  • + +
    4.57 s
    +
    passedBenchmarkManager_SignWithPassphrase1000
    +
      +
    • +500 3202891 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase1000-2
      manager_benchmarks_test.go:309: establishing manager for 1000 accs: 103.699423ms
      manager_benchmarks_test.go:309: establishing manager for 1000 accs: 60.112226ms
      manager_benchmarks_test.go:309: establishing manager for 1000 accs: 73.236982ms
      +
    • +
    +
  • +
  • + +
    3.78 s
    +
    passedBenchmarkManager_SignWithPassphrase5000
    +
      +
    • +500 3069767 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase5000-2
      manager_benchmarks_test.go:309: establishing manager for 5000 accs: 35.704349ms
      manager_benchmarks_test.go:309: establishing manager for 5000 accs: 23.318539ms
      manager_benchmarks_test.go:309: establishing manager for 5000 accs: 59.224371ms
      +
    • +
    +
  • +
  • + +
    5.89 s
    +
    passedBenchmarkManager_SignWithPassphrase10000
    +
      +
    • +500 3400757 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase10000-2
      manager_benchmarks_test.go:309: establishing manager for 10000 accs: 43.803984ms
      manager_benchmarks_test.go:309: establishing manager for 10000 accs: 58.443376ms
      manager_benchmarks_test.go:309: establishing manager for 10000 accs: 61.027546ms
      +
    • +
    +
  • +
  • + +
    28.29 s
    +
    passedBenchmarkManager_SignWithPassphrase20000
    +
      +
    • +500 3394578 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase20000-2
      manager_benchmarks_test.go:309: establishing manager for 20000 accs: 75.370248ms
      manager_benchmarks_test.go:309: establishing manager for 20000 accs: 58.691241ms
      manager_benchmarks_test.go:309: establishing manager for 20000 accs: 58.309409ms
      +
    • +
    +
  • +
  • + +
    1 m 15 s
    +
    passedBenchmarkManager_SignWithPassphrase100000
    +
      +
    • +500 3538710 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase100000-2
      manager_benchmarks_test.go:309: establishing manager for 100000 accs: 208.317403ms
      manager_benchmarks_test.go:309: establishing manager for 100000 accs: 64.148611ms
      manager_benchmarks_test.go:309: establishing manager for 100000 accs: 8.122843ms
      +
    • +
    +
  • +
  • + +
    2.20 s
    +
    passedBenchmarkManager_SignWithPassphrase500000
    +
      +
    • +300 4279667 ns/op
      --- BENCH: BenchmarkManager_SignWithPassphrase500000-2
      manager_benchmarks_test.go:309: establishing manager for 500000 accs: 168.247823ms
      manager_benchmarks_test.go:309: establishing manager for 500000 accs: 62.266334ms
      manager_benchmarks_test.go:309: establishing manager for 500000 accs: 113.526807ms
      +
    • +
    +
  • +
  • + +
    2.94 s
    +
    passedBenchmarkManager_CRUSD100
    +
      +
    • +50 27181788 ns/op
      --- BENCH: BenchmarkManager_CRUSD100-2
      manager_benchmarks_test.go:368: establishing manager for 100 accs: 32.842985ms
      manager_benchmarks_test.go:368: establishing manager for 100 accs: 60.173237ms
      manager_benchmarks_test.go:368: establishing manager for 100 accs: 64.633671ms
      +
    • +
    +
  • +
  • + +
    1.49 s
    +
    passedBenchmarkManager_CRUSD500
    +
      +
    • +50 56427840 ns/op
      --- BENCH: BenchmarkManager_CRUSD500-2
      manager_benchmarks_test.go:368: establishing manager for 500 accs: 33.973351ms
      manager_benchmarks_test.go:368: establishing manager for 500 accs: 57.644326ms
      +
    • +
    +
  • +
  • + +
    1.25 s
    +
    passedBenchmarkManager_CRUSD1000
    +
      +
    • +20 67916777 ns/op
      --- BENCH: BenchmarkManager_CRUSD1000-2
      manager_benchmarks_test.go:368: establishing manager for 1000 accs: 40.803863ms
      manager_benchmarks_test.go:368: establishing manager for 1000 accs: 16.295654ms
      +
    • +
    +
  • +
  • + +
    3.63 s
    +
    passedBenchmarkManager_CRUSD5000
    +
      +
    • +10 104075917 ns/op
      --- BENCH: BenchmarkManager_CRUSD5000-2
      manager_benchmarks_test.go:368: establishing manager for 5000 accs: 28.398398ms
      manager_benchmarks_test.go:368: establishing manager for 5000 accs: 65.975823ms
      +
    • +
    +
  • +
  • + +
    1.48 s
    +
    passedBenchmarkManager_CRUSD10000
    +
      +
    • +20 86868763 ns/op
      --- BENCH: BenchmarkManager_CRUSD10000-2
      manager_benchmarks_test.go:368: establishing manager for 10000 accs: 93.766465ms
      manager_benchmarks_test.go:368: establishing manager for 10000 accs: 67.604284ms
      manager_benchmarks_test.go:368: establishing manager for 10000 accs: 78.234665ms
      manager_benchmarks_test.go:368: establishing manager for 10000 accs: 15.877264ms
      +
    • +
    +
  • +
  • + +
    1.59 s
    +
    passedBenchmarkManager_CRUSD20000
    +
      +
    • +20 65038529 ns/op
      --- BENCH: BenchmarkManager_CRUSD20000-2
      manager_benchmarks_test.go:368: establishing manager for 20000 accs: 38.232096ms
      manager_benchmarks_test.go:368: establishing manager for 20000 accs: 60.857884ms
      +
    • +
    +
  • +
  • + +
    1.35 s
    +
    passedBenchmarkManager_CRUSD100000
    +
      +
    • +10 134423789 ns/op
      --- BENCH: BenchmarkManager_CRUSD100000-2
      manager_benchmarks_test.go:368: establishing manager for 100000 accs: 44.62387ms
      manager_benchmarks_test.go:368: establishing manager for 100000 accs: 83.820913ms
      +
    • +
    +
  • +
  • + +
    39 ms
    +
    passedBenchmarkManager_CRUSD500000
    +
      +
    • +10 107799087 ns/op
      --- BENCH: BenchmarkManager_CRUSD500000-2
      manager_benchmarks_test.go:368: establishing manager for 500000 accs: 18.051389ms
      manager_benchmarks_test.go:368: establishing manager for 500000 accs: 67.470907ms
      PASS
      Process finished with exit code 0
      +
    • +
    +
  • +
+
+
+ + + diff --git a/accounts/testdata/dupes/accounts.db b/accounts/testdata/dupes/accounts.db new file mode 100644 index 000000000..0ad6fd110 Binary files /dev/null and b/accounts/testdata/dupes/accounts.db differ diff --git a/accounts/testdata/keystore/UTC--2017-05-18T13-25-25.741637069Z--42697c7e014060222d30a49ee30eb1f8a1d11407~ b/accounts/testdata/keystore/UTC--2017-05-18T13-25-25.741637069Z--42697c7e014060222d30a49ee30eb1f8a1d11407~ new file mode 100644 index 000000000..92577df5e --- /dev/null +++ b/accounts/testdata/keystore/UTC--2017-05-18T13-25-25.741637069Z--42697c7e014060222d30a49ee30eb1f8a1d11407~ @@ -0,0 +1 @@ +{"id":"713677a7-e123-42af-b7b7-519442a11fb7","address":"42697c7e014060222d30a49ee30eb1f8a1d11407","crypto":{"cipher":"aes-128-ctr","ciphertext":"eda6e4a2fe1e327f9b391264d71bb37734a9f3b6beac874120cb6a4d47bec5bf","cipherparams":{"iv":"f44ca700199de3ed6bb1745189198b4f"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":2,"p":1,"r":8,"salt":"c5abffd885b37109d93d2dff79f207681dd607c5ec2b6f11089711fd39c04fb4"},"mac":"abaf0ab381de099a97361c3a9b0c6231298ffd842e3732bb3429a9ebfc196619"},"version":3} \ No newline at end of file diff --git a/accounts/testdata/keystore/accounts.db b/accounts/testdata/keystore/accounts.db new file mode 100644 index 000000000..9d2ca8a06 Binary files /dev/null and b/accounts/testdata/keystore/accounts.db differ diff --git a/accounts/testdata/keystore/keystore/accounts.db b/accounts/testdata/keystore/keystore/accounts.db new file mode 100644 index 000000000..3bf25f270 Binary files /dev/null and b/accounts/testdata/keystore/keystore/accounts.db differ diff --git a/accounts/testdata/make200 b/accounts/testdata/make200 new file mode 100755 index 000000000..33874af5c --- /dev/null +++ b/accounts/testdata/make200 @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +counter=0 +mkdir -p ./benchmark_keystore200k +for file in ./benchmark_keystore500k/*; do + if [ $counter -lt 200000 ]; then + if ! [[ "$file" == *"accounts.db" ]]; then + cp "$file" ./benchmark_keystore200k/ + fi + fi + ((counter=counter+1)) +done + +unset counter diff --git a/accounts/vendor/github.com/boltdb/bolt/LICENSE b/accounts/vendor/github.com/boltdb/bolt/LICENSE new file mode 100644 index 000000000..004e77fe5 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Ben Johnson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/accounts/vendor/github.com/boltdb/bolt/Makefile b/accounts/vendor/github.com/boltdb/bolt/Makefile new file mode 100644 index 000000000..e035e63ad --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/Makefile @@ -0,0 +1,18 @@ +BRANCH=`git rev-parse --abbrev-ref HEAD` +COMMIT=`git rev-parse --short HEAD` +GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)" + +default: build + +race: + @go test -v -race -test.run="TestSimulate_(100op|1000op)" + +# go get github.com/kisielk/errcheck +errcheck: + @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt + +test: + @go test -v -cover . + @go test -v ./cmd/bolt + +.PHONY: fmt test diff --git a/accounts/vendor/github.com/boltdb/bolt/README.md b/accounts/vendor/github.com/boltdb/bolt/README.md new file mode 100644 index 000000000..85810d9fc --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/README.md @@ -0,0 +1,912 @@ +Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg) +==== + +Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas] +[LMDB project][lmdb]. The goal of the project is to provide a simple, +fast, and reliable database for projects that don't require a full database +server such as Postgres or MySQL. + +Since Bolt 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. + +[hyc_symas]: https://twitter.com/hyc_symas +[lmdb]: http://symas.com/mdb/ + +## Project Status + +Bolt is stable, the API is fixed, and the file format is fixed. Full unit +test coverage and randomized black box testing are used to ensure database +consistency and thread safety. Bolt is currently used in high-load production +environments serving databases as large as 1TB. Many companies such as +Shopify and Heroku use Bolt-backed services every day. + +## Table of Contents + +- [Getting Started](#getting-started) + - [Installing](#installing) + - [Opening a database](#opening-a-database) + - [Transactions](#transactions) + - [Read-write transactions](#read-write-transactions) + - [Read-only transactions](#read-only-transactions) + - [Batch read-write transactions](#batch-read-write-transactions) + - [Managing transactions manually](#managing-transactions-manually) + - [Using buckets](#using-buckets) + - [Using key/value pairs](#using-keyvalue-pairs) + - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket) + - [Iterating over keys](#iterating-over-keys) + - [Prefix scans](#prefix-scans) + - [Range scans](#range-scans) + - [ForEach()](#foreach) + - [Nested buckets](#nested-buckets) + - [Database backups](#database-backups) + - [Statistics](#statistics) + - [Read-Only Mode](#read-only-mode) + - [Mobile Use (iOS/Android)](#mobile-use-iosandroid) +- [Resources](#resources) +- [Comparison with other databases](#comparison-with-other-databases) + - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases) + - [LevelDB, RocksDB](#leveldb-rocksdb) + - [LMDB](#lmdb) +- [Caveats & Limitations](#caveats--limitations) +- [Reading the Source](#reading-the-source) +- [Other Projects Using Bolt](#other-projects-using-bolt) + +## Getting Started + +### Installing + +To start using Bolt, install Go and run `go get`: + +```sh +$ go get github.com/boltdb/bolt/... +``` + +This will retrieve the library and install the `bolt` command line utility into +your `$GOBIN` path. + + +### Opening a database + +The top-level object in Bolt is a `DB`. It is represented as a single file on +your disk and represents a consistent snapshot of your data. + +To open your database, simply use the `bolt.Open()` function: + +```go +package main + +import ( + "log" + + "github.com/boltdb/bolt" +) + +func main() { + // Open the my.db data file in your current directory. + // It will be created if it doesn't exist. + db, err := bolt.Open("my.db", 0600, nil) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + ... +} +``` + +Please note that Bolt obtains a file lock on the data file so multiple processes +cannot open the same database at the same time. Opening an already open Bolt +database will cause it to hang until the other process closes it. To prevent +an indefinite wait you can pass a timeout option to the `Open()` function: + +```go +db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}) +``` + + +### Transactions + +Bolt allows only one read-write transaction at a time but allows as many +read-only transactions as you want at a time. Each transaction has a consistent +view of the data as it existed when the transaction started. + +Individual transactions and all objects created from them (e.g. buckets, keys) +are not thread safe. To work with data in multiple goroutines you must start +a transaction for each one or use locking to ensure only one goroutine accesses +a transaction at a time. Creating transaction from the `DB` is thread safe. + +Read-only transactions and read-write transactions should not depend on one +another and generally shouldn't be opened simultaneously in the same goroutine. +This can cause a deadlock as the read-write transaction needs to periodically +re-map the data file but it cannot do so while a read-only transaction is open. + + +#### Read-write transactions + +To start a read-write transaction, you can use the `DB.Update()` function: + +```go +err := db.Update(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +Inside the closure, you have a consistent view of the database. You commit the +transaction by returning `nil` at the end. You can also rollback the transaction +at any point by returning an error. All database operations are allowed inside +a read-write transaction. + +Always check the return error as it will report any disk failures that can cause +your transaction to not complete. If you return an error within your closure +it will be passed through. + + +#### Read-only transactions + +To start a read-only transaction, you can use the `DB.View()` function: + +```go +err := db.View(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +You also get a consistent view of the database within this closure, however, +no mutating operations are allowed within a read-only transaction. You can only +retrieve buckets, retrieve values, and copy the database within a read-only +transaction. + + +#### Batch read-write transactions + +Each `DB.Update()` waits for disk to commit the writes. This overhead +can be minimized by combining multiple updates with the `DB.Batch()` +function: + +```go +err := db.Batch(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +Concurrent Batch calls are opportunistically combined into larger +transactions. Batch is only useful when there are multiple goroutines +calling it. + +The trade-off is that `Batch` can call the given +function multiple times, if parts of the transaction fail. The +function must be idempotent and side effects must take effect only +after a successful return from `DB.Batch()`. + +For example: don't display messages from inside the function, instead +set variables in the enclosing scope: + +```go +var id uint64 +err := db.Batch(func(tx *bolt.Tx) error { + // Find last key in bucket, decode as bigendian uint64, increment + // by one, encode back to []byte, and add new key. + ... + id = newValue + return nil +}) +if err != nil { + return ... +} +fmt.Println("Allocated ID %d", id) +``` + + +#### Managing transactions manually + +The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()` +function. These helper functions will start the transaction, execute a function, +and then safely close your transaction if an error is returned. This is the +recommended way to use Bolt transactions. + +However, sometimes you may want to manually start and end your transactions. +You can use the `DB.Begin()` function directly but **please** be sure to close +the transaction. + +```go +// Start a writable transaction. +tx, err := db.Begin(true) +if err != nil { + return err +} +defer tx.Rollback() + +// Use the transaction... +_, err := tx.CreateBucket([]byte("MyBucket")) +if err != nil { + return err +} + +// Commit the transaction and check for error. +if err := tx.Commit(); err != nil { + return err +} +``` + +The first argument to `DB.Begin()` is a boolean stating if the transaction +should be writable. + + +### Using buckets + +Buckets are collections of key/value pairs within the database. All keys in a +bucket must be unique. You can create a bucket using the `DB.CreateBucket()` +function: + +```go +db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucket([]byte("MyBucket")) + if err != nil { + return fmt.Errorf("create bucket: %s", err) + } + return nil +}) +``` + +You can also create a bucket only if it doesn't exist by using the +`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this +function for all your top-level buckets after you open your database so you can +guarantee that they exist for future transactions. + +To delete a bucket, simply call the `Tx.DeleteBucket()` function. + + +### Using key/value pairs + +To save a key/value pair to a bucket, use the `Bucket.Put()` function: + +```go +db.Update(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("MyBucket")) + err := b.Put([]byte("answer"), []byte("42")) + return err +}) +``` + +This will set the value of the `"answer"` key to `"42"` in the `MyBucket` +bucket. To retrieve this value, we can use the `Bucket.Get()` function: + +```go +db.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("MyBucket")) + v := b.Get([]byte("answer")) + fmt.Printf("The answer is: %s\n", v) + return nil +}) +``` + +The `Get()` function does not return an error because its operation is +guaranteed to work (unless there is some kind of system failure). If the key +exists then it will return its byte slice value. If it doesn't exist then it +will return `nil`. It's important to note that you can have a zero-length value +set to a key which is different than the key not existing. + +Use the `Bucket.Delete()` function to delete a key from the bucket. + +Please note that values returned from `Get()` are only valid while the +transaction is open. If you need to use a value outside of the transaction +then you must use `copy()` to copy it to another byte slice. + + +### Autoincrementing integer for the bucket +By using the `NextSequence()` function, you can let Bolt determine a sequence +which can be used as the unique identifier for your key/value pairs. See the +example below. + +```go +// CreateUser saves u to the store. The new user ID is set on u once the data is persisted. +func (s *Store) CreateUser(u *User) error { + return s.db.Update(func(tx *bolt.Tx) error { + // Retrieve the users bucket. + // This should be created when the DB is first opened. + b := tx.Bucket([]byte("users")) + + // Generate ID for the user. + // This returns an error only if the Tx is closed or not writeable. + // That can't happen in an Update() call so I ignore the error check. + id, _ := b.NextSequence() + u.ID = int(id) + + // Marshal user data into bytes. + buf, err := json.Marshal(u) + if err != nil { + return err + } + + // Persist bytes to users bucket. + return b.Put(itob(u.ID), buf) + }) +} + +// itob returns an 8-byte big endian representation of v. +func itob(v int) []byte { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, uint64(v)) + return b +} + +type User struct { + ID int + ... +} +``` + +### Iterating over keys + +Bolt stores its keys in byte-sorted order within a bucket. This makes sequential +iteration over these keys extremely fast. To iterate over keys we'll use a +`Cursor`: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + b := tx.Bucket([]byte("MyBucket")) + + c := b.Cursor() + + for k, v := c.First(); k != nil; k, v = c.Next() { + fmt.Printf("key=%s, value=%s\n", k, v) + } + + return nil +}) +``` + +The cursor allows you to move to a specific point in the list of keys and move +forward or backward through the keys one at a time. + +The following functions are available on the cursor: + +``` +First() Move to the first key. +Last() Move to the last key. +Seek() Move to a specific key. +Next() Move to the next key. +Prev() Move to the previous key. +``` + +Each of those functions has a return signature of `(key []byte, value []byte)`. +When you have iterated to the end of the cursor then `Next()` will return a +`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()` +before calling `Next()` or `Prev()`. If you do not seek to a position then +these functions will return a `nil` key. + +During iteration, if the key is non-`nil` but the value is `nil`, that means +the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to +access the sub-bucket. + + +#### Prefix scans + +To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + c := tx.Bucket([]byte("MyBucket")).Cursor() + + prefix := []byte("1234") + for k, v := c.Seek(prefix); bytes.HasPrefix(k, prefix); k, v = c.Next() { + fmt.Printf("key=%s, value=%s\n", k, v) + } + + return nil +}) +``` + +#### Range scans + +Another common use case is scanning over a range such as a time range. If you +use a sortable time encoding such as RFC3339 then you can query a specific +date range like this: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume our events bucket exists and has RFC3339 encoded time keys. + c := tx.Bucket([]byte("Events")).Cursor() + + // Our time range spans the 90's decade. + min := []byte("1990-01-01T00:00:00Z") + max := []byte("2000-01-01T00:00:00Z") + + // Iterate over the 90's. + for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() { + fmt.Printf("%s: %s\n", k, v) + } + + return nil +}) +``` + +Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable. + + +#### ForEach() + +You can also use the function `ForEach()` if you know you'll be iterating over +all the keys in a bucket: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + b := tx.Bucket([]byte("MyBucket")) + + b.ForEach(func(k, v []byte) error { + fmt.Printf("key=%s, value=%s\n", k, v) + return nil + }) + return nil +}) +``` + +Please note that keys and values in `ForEach()` are only valid while +the transaction is open. If you need to use a key or value outside of +the transaction, you must use `copy()` to copy it to another byte +slice. + +### Nested buckets + +You can also store a bucket in a key to create nested buckets. The API is the +same as the bucket management API on the `DB` object: + +```go +func (*Bucket) CreateBucket(key []byte) (*Bucket, error) +func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) +func (*Bucket) DeleteBucket(key []byte) error +``` + +Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings. + +```go + +// createUser creates a new user in the given account. +func createUser(accountID int, u *User) error { + // Start the transaction. + tx, err := db.Begin(true) + if err != nil { + return err + } + defer tx.Rollback() + + // Retrieve the root bucket for the account. + // Assume this has already been created when the account was set up. + root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10))) + + // Setup the users bucket. + bkt, err := root.CreateBucketIfNotExists([]byte("USERS")) + if err != nil { + return err + } + + // Generate an ID for the new user. + userID, err := bkt.NextSequence() + if err != nil { + return err + } + u.ID = userID + + // Marshal and save the encoded user. + if buf, err := json.Marshal(u); err != nil { + return err + } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil { + return err + } + + // Commit the transaction. + if err := tx.Commit(); err != nil { + return err + } + + return nil +} + +``` + + + + +### Database backups + +Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()` +function to write a consistent view of the database to a writer. If you call +this from a read-only transaction, it will perform a hot backup and not block +your other database reads and writes. + +By default, it will use a regular file handle which will utilize the operating +system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx) +documentation for information about optimizing for larger-than-RAM datasets. + +One common use case is to backup over HTTP so you can use tools like `cURL` to +do database backups: + +```go +func BackupHandleFunc(w http.ResponseWriter, req *http.Request) { + err := db.View(func(tx *bolt.Tx) error { + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", `attachment; filename="my.db"`) + w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size()))) + _, err := tx.WriteTo(w) + return err + }) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} +``` + +Then you can backup using this command: + +```sh +$ curl http://localhost/backup > my.db +``` + +Or you can open your browser to `http://localhost/backup` and it will download +automatically. + +If you want to backup to another file you can use the `Tx.CopyFile()` helper +function. + + +### Statistics + +The database keeps a running count of many of the internal operations it +performs so you can better understand what's going on. By grabbing a snapshot +of these stats at two points in time we can see what operations were performed +in that time range. + +For example, we could start a goroutine to log stats every 10 seconds: + +```go +go func() { + // Grab the initial stats. + prev := db.Stats() + + for { + // Wait for 10s. + time.Sleep(10 * time.Second) + + // Grab the current stats and diff them. + stats := db.Stats() + diff := stats.Sub(&prev) + + // Encode stats to JSON and print to STDERR. + json.NewEncoder(os.Stderr).Encode(diff) + + // Save stats for the next loop. + prev = stats + } +}() +``` + +It's also useful to pipe these stats to a service such as statsd for monitoring +or to provide an HTTP endpoint that will perform a fixed-length sample. + + +### Read-Only Mode + +Sometimes it is useful to create a shared, read-only Bolt database. To this, +set the `Options.ReadOnly` flag when opening your database. Read-only mode +uses a shared lock to allow multiple processes to read from the database but +it will block any processes from opening the database in read-write mode. + +```go +db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true}) +if err != nil { + log.Fatal(err) +} +``` + +### Mobile Use (iOS/Android) + +Bolt is able to run on mobile devices by leveraging the binding feature of the +[gomobile](https://github.com/golang/mobile) tool. Create a struct that will +contain your database logic and a reference to a `*bolt.DB` with a initializing +constructor that takes in a filepath where the database file will be stored. +Neither Android nor iOS require extra permissions or cleanup from using this method. + +```go +func NewBoltDB(filepath string) *BoltDB { + db, err := bolt.Open(filepath+"/demo.db", 0600, nil) + if err != nil { + log.Fatal(err) + } + + return &BoltDB{db} +} + +type BoltDB struct { + db *bolt.DB + ... +} + +func (b *BoltDB) Path() string { + return b.db.Path() +} + +func (b *BoltDB) Close() { + b.db.Close() +} +``` + +Database logic should be defined as methods on this wrapper struct. + +To initialize this struct from the native language (both platforms now sync +their local storage to the cloud. These snippets disable that functionality for the +database file): + +#### Android + +```java +String path; +if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){ + path = getNoBackupFilesDir().getAbsolutePath(); +} else{ + path = getFilesDir().getAbsolutePath(); +} +Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path) +``` + +#### iOS + +```objc +- (void)demo { + NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, + NSUserDomainMask, + YES) objectAtIndex:0]; + GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path); + [self addSkipBackupAttributeToItemAtPath:demo.path]; + //Some DB Logic would go here + [demo close]; +} + +- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString +{ + NSURL* URL= [NSURL fileURLWithPath: filePathString]; + assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); + + NSError *error = nil; + BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] + forKey: NSURLIsExcludedFromBackupKey error: &error]; + if(!success){ + NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); + } + return success; +} + +``` + +## Resources + +For more information on getting started with Bolt, check out the following articles: + +* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch). +* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville + + +## Comparison with other databases + +### Postgres, MySQL, & other relational databases + +Relational databases structure data into rows and are only accessible through +the use of SQL. This approach provides flexibility in how you store and query +your data but also incurs overhead in parsing and planning SQL statements. Bolt +accesses all data by a byte slice key. This makes Bolt fast to read and write +data by key but provides no built-in support for joining values together. + +Most relational databases (with the exception of SQLite) are standalone servers +that run separately from your application. This gives your systems +flexibility to connect multiple application servers to a single database +server but also adds overhead in serializing and transporting data over the +network. Bolt runs as a library included in your application so all data access +has to go through your application's process. This brings data closer to your +application but limits multi-process access to the data. + + +### LevelDB, RocksDB + +LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that +they are libraries bundled into the application, however, their underlying +structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes +random writes by using a write ahead log and multi-tiered, sorted files called +SSTables. Bolt uses a B+tree internally and only a single file. Both approaches +have trade-offs. + +If you require a high random write throughput (>10,000 w/sec) or you need to use +spinning disks then LevelDB could be a good choice. If your application is +read-heavy or does a lot of range scans then Bolt could be a good choice. + +One other important consideration is that LevelDB does not have transactions. +It supports batch writing of key/values pairs and it supports read snapshots +but it will not give you the ability to do a compare-and-swap operation safely. +Bolt supports fully serializable ACID transactions. + + +### LMDB + +Bolt was originally a port of LMDB so it is architecturally similar. Both use +a B+tree, have ACID semantics with fully serializable transactions, and support +lock-free MVCC using a single writer and multiple readers. + +The two projects have somewhat diverged. LMDB heavily focuses on raw performance +while Bolt has focused on simplicity and ease of use. For example, LMDB allows +several unsafe actions such as direct writes for the sake of performance. Bolt +opts to disallow actions which can leave the database in a corrupted state. The +only exception to this in Bolt is `DB.NoSync`. + +There are also a few differences in API. LMDB requires a maximum mmap size when +opening an `mdb_env` whereas Bolt will handle incremental mmap resizing +automatically. LMDB overloads the getter and setter functions with multiple +flags whereas Bolt splits these specialized cases into their own functions. + + +## Caveats & Limitations + +It's important to pick the right tool for the job and Bolt is no exception. +Here are a few things to note when evaluating and using Bolt: + +* Bolt is good for read intensive workloads. Sequential write performance is + also fast but random writes can be slow. You can use `DB.Batch()` or add a + write-ahead log to help mitigate this issue. + +* Bolt uses a B+tree internally so there can be a lot of random page access. + SSDs provide a significant performance boost over spinning disks. + +* Try to avoid long running read transactions. Bolt uses copy-on-write so + old pages cannot be reclaimed while an old transaction is using them. + +* Byte slices returned from Bolt are only valid during a transaction. Once the + transaction has been committed or rolled back then the memory they point to + can be reused by a new page or can be unmapped from virtual memory and you'll + see an `unexpected fault address` panic when accessing it. + +* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for + buckets that have random inserts will cause your database to have very poor + page utilization. + +* Use larger buckets in general. Smaller buckets causes poor page utilization + once they become larger than the page size (typically 4KB). + +* Bulk loading a lot of random writes into a new bucket can be slow as the + page will not split until the transaction is committed. Randomly inserting + more than 100,000 key/value pairs into a single new bucket in a single + transaction is not advised. + +* Bolt uses a memory-mapped file so the underlying operating system handles the + caching of the data. Typically, the OS will cache as much of the file as it + can in memory and will release memory as needed to other processes. This means + that Bolt can show very high memory usage when working with large databases. + However, this is expected and the OS will release memory as needed. Bolt can + handle databases much larger than the available physical RAM, provided its + memory-map fits in the process virtual address space. It may be problematic + on 32-bits systems. + +* The data structures in the Bolt database are memory mapped so the data file + will be endian specific. This means that you cannot copy a Bolt file from a + little endian machine to a big endian machine and have it work. For most + users this is not a concern since most modern CPUs are little endian. + +* Because of the way pages are laid out on disk, Bolt cannot truncate data files + and return free pages back to the disk. Instead, Bolt maintains a free list + of unused pages within its data file. These free pages can be reused by later + transactions. This works well for many use cases as databases generally tend + to grow. However, it's important to note that deleting large chunks of data + will not allow you to reclaim that space on disk. + + For more information on page allocation, [see this comment][page-allocation]. + +[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638 + + +## Reading the Source + +Bolt is a relatively small code base (<3KLOC) for an embedded, serializable, +transactional key/value database so it can be a good starting point for people +interested in how databases work. + +The best places to start are the main entry points into Bolt: + +- `Open()` - Initializes the reference to the database. It's responsible for + creating the database if it doesn't exist, obtaining an exclusive lock on the + file, reading the meta pages, & memory-mapping the file. + +- `DB.Begin()` - Starts a read-only or read-write transaction depending on the + value of the `writable` argument. This requires briefly obtaining the "meta" + lock to keep track of open transactions. Only one read-write transaction can + exist at a time so the "rwlock" is acquired during the life of a read-write + transaction. + +- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the + arguments, a cursor is used to traverse the B+tree to the page and position + where they key & value will be written. Once the position is found, the bucket + materializes the underlying page and the page's parent pages into memory as + "nodes". These nodes are where mutations occur during read-write transactions. + These changes get flushed to disk during commit. + +- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor + to move to the page & position of a key/value pair. During a read-only + transaction, the key and value data is returned as a direct reference to the + underlying mmap file so there's no allocation overhead. For read-write + transactions, this data may reference the mmap file or one of the in-memory + node values. + +- `Cursor` - This object is simply for traversing the B+tree of on-disk pages + or in-memory nodes. It can seek to a specific key, move to the first or last + value, or it can move forward or backward. The cursor handles the movement up + and down the B+tree transparently to the end user. + +- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages + into pages to be written to disk. Writing to disk then occurs in two phases. + First, the dirty pages are written to disk and an `fsync()` occurs. Second, a + new meta page with an incremented transaction ID is written and another + `fsync()` occurs. This two phase write ensures that partially written data + pages are ignored in the event of a crash since the meta page pointing to them + is never written. Partially written meta pages are invalidated because they + are written with a checksum. + +If you have additional notes that could be helpful for others, please submit +them via pull request. + + +## Other Projects Using Bolt + +Below is a list of public, open source projects that use Bolt: + +* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files. +* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard. +* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside. +* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb. +* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics. +* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects. +* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday. +* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations. +* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite. +* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin". +* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka. +* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed. +* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt. +* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site. +* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage. +* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters. +* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend. +* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend. +* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server. +* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read. +* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics. +* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data. +* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system. +* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware. +* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs. +* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems. +* [stow](https://github.com/djherbis/stow) - a persistence manager for objects + backed by boltdb. +* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining + simple tx and key scans. +* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets. +* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service +* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service. +* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners. +* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores. +* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB. +* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB. +* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings. +* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend. +* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files. +* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter. +* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development. +* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains +* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal. +* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet. +* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency. +* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies +* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB + +If you are using Bolt in a project please send a pull request to add it to the list. diff --git a/accounts/vendor/github.com/boltdb/bolt/appveyor.yml b/accounts/vendor/github.com/boltdb/bolt/appveyor.yml new file mode 100644 index 000000000..6e26e941d --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/appveyor.yml @@ -0,0 +1,18 @@ +version: "{build}" + +os: Windows Server 2012 R2 + +clone_folder: c:\gopath\src\github.com\boltdb\bolt + +environment: + GOPATH: c:\gopath + +install: + - echo %PATH% + - echo %GOPATH% + - go version + - go env + - go get -v -t ./... + +build_script: + - go test -v ./... diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_386.go b/accounts/vendor/github.com/boltdb/bolt/bolt_386.go new file mode 100644 index 000000000..820d533c1 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_386.go @@ -0,0 +1,10 @@ +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_amd64.go b/accounts/vendor/github.com/boltdb/bolt/bolt_amd64.go new file mode 100644 index 000000000..98fafdb47 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_amd64.go @@ -0,0 +1,10 @@ +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_arm.go b/accounts/vendor/github.com/boltdb/bolt/bolt_arm.go new file mode 100644 index 000000000..7e5cb4b94 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_arm.go @@ -0,0 +1,28 @@ +package bolt + +import "unsafe" + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned bool + +func init() { + // Simple check to see whether this arch handles unaligned load/stores + // correctly. + + // ARM9 and older devices require load/stores to be from/to aligned + // addresses. If not, the lower 2 bits are cleared and that address is + // read in a jumbled up order. + + // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html + + raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11} + val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2)) + + brokenUnaligned = val != 0x11222211 +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_arm64.go b/accounts/vendor/github.com/boltdb/bolt/bolt_arm64.go new file mode 100644 index 000000000..b26d84f91 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_arm64.go @@ -0,0 +1,12 @@ +// +build arm64 + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_linux.go b/accounts/vendor/github.com/boltdb/bolt/bolt_linux.go new file mode 100644 index 000000000..2b6766614 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_linux.go @@ -0,0 +1,10 @@ +package bolt + +import ( + "syscall" +) + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return syscall.Fdatasync(int(db.file.Fd())) +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_openbsd.go b/accounts/vendor/github.com/boltdb/bolt/bolt_openbsd.go new file mode 100644 index 000000000..7058c3d73 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_openbsd.go @@ -0,0 +1,27 @@ +package bolt + +import ( + "syscall" + "unsafe" +) + +const ( + msAsync = 1 << iota // perform asynchronous writes + msSync // perform synchronous writes + msInvalidate // invalidate cached data +) + +func msync(db *DB) error { + _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate) + if errno != 0 { + return errno + } + return nil +} + +func fdatasync(db *DB) error { + if db.data != nil { + return msync(db) + } + return db.file.Sync() +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_ppc.go b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc.go new file mode 100644 index 000000000..645ddc3ed --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc.go @@ -0,0 +1,9 @@ +// +build ppc + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64.go b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64.go new file mode 100644 index 000000000..2dc6be02e --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64.go @@ -0,0 +1,9 @@ +// +build ppc64 + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64le.go b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64le.go new file mode 100644 index 000000000..8c143bc5d --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_ppc64le.go @@ -0,0 +1,12 @@ +// +build ppc64le + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_s390x.go b/accounts/vendor/github.com/boltdb/bolt/bolt_s390x.go new file mode 100644 index 000000000..d7c39af92 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_s390x.go @@ -0,0 +1,12 @@ +// +build s390x + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_unix.go b/accounts/vendor/github.com/boltdb/bolt/bolt_unix.go new file mode 100644 index 000000000..cad62dda1 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_unix.go @@ -0,0 +1,89 @@ +// +build !windows,!plan9,!solaris + +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" +) + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + flag := syscall.LOCK_SH + if exclusive { + flag = syscall.LOCK_EX + } + + // Otherwise attempt to obtain an exclusive lock. + err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB) + if err == nil { + return nil + } else if err != syscall.EWOULDBLOCK { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN) +} + +// mmap memory maps a DB's data file. +func mmap(db *DB, sz int) error { + // Map the data file to memory. + b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) + if err != nil { + return err + } + + // Advise the kernel that the mmap is accessed randomly. + if err := madvise(b, syscall.MADV_RANDOM); err != nil { + return fmt.Errorf("madvise: %s", err) + } + + // Save the original byte slice and convert to a byte array pointer. + db.dataref = b + db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) + db.datasz = sz + return nil +} + +// munmap unmaps a DB's data file from memory. +func munmap(db *DB) error { + // Ignore the unmap if we have no mapped data. + if db.dataref == nil { + return nil + } + + // Unmap using the original byte slice. + err := syscall.Munmap(db.dataref) + db.dataref = nil + db.data = nil + db.datasz = 0 + return err +} + +// NOTE: This function is copied from stdlib because it is not available on darwin. +func madvise(b []byte, advice int) (err error) { + _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice)) + if e1 != 0 { + err = e1 + } + return +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go b/accounts/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go new file mode 100644 index 000000000..307bf2b3e --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go @@ -0,0 +1,90 @@ +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/unix" +) + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + var lock syscall.Flock_t + lock.Start = 0 + lock.Len = 0 + lock.Pid = 0 + lock.Whence = 0 + lock.Pid = 0 + if exclusive { + lock.Type = syscall.F_WRLCK + } else { + lock.Type = syscall.F_RDLCK + } + err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock) + if err == nil { + return nil + } else if err != syscall.EAGAIN { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + var lock syscall.Flock_t + lock.Start = 0 + lock.Len = 0 + lock.Type = syscall.F_UNLCK + lock.Whence = 0 + return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock) +} + +// mmap memory maps a DB's data file. +func mmap(db *DB, sz int) error { + // Map the data file to memory. + b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) + if err != nil { + return err + } + + // Advise the kernel that the mmap is accessed randomly. + if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { + return fmt.Errorf("madvise: %s", err) + } + + // Save the original byte slice and convert to a byte array pointer. + db.dataref = b + db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) + db.datasz = sz + return nil +} + +// munmap unmaps a DB's data file from memory. +func munmap(db *DB) error { + // Ignore the unmap if we have no mapped data. + if db.dataref == nil { + return nil + } + + // Unmap using the original byte slice. + err := unix.Munmap(db.dataref) + db.dataref = nil + db.data = nil + db.datasz = 0 + return err +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bolt_windows.go b/accounts/vendor/github.com/boltdb/bolt/bolt_windows.go new file mode 100644 index 000000000..d538e6afd --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bolt_windows.go @@ -0,0 +1,144 @@ +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" +) + +// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1 +var ( + modkernel32 = syscall.NewLazyDLL("kernel32.dll") + procLockFileEx = modkernel32.NewProc("LockFileEx") + procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") +) + +const ( + lockExt = ".lock" + + // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx + flagLockExclusive = 2 + flagLockFailImmediately = 1 + + // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx + errLockViolation syscall.Errno = 0x21 +) + +func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { + r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol))) + if r == 0 { + return err + } + return nil +} + +func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { + r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0) + if r == 0 { + return err + } + return nil +} + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return db.file.Sync() +} + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + // Create a separate lock file on windows because a process + // cannot share an exclusive lock on the same file. This is + // needed during Tx.WriteTo(). + f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode) + if err != nil { + return err + } + db.lockfile = f + + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + + var flag uint32 = flagLockFailImmediately + if exclusive { + flag |= flagLockExclusive + } + + err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{}) + if err == nil { + return nil + } else if err != errLockViolation { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{}) + db.lockfile.Close() + os.Remove(db.path+lockExt) + return err +} + +// mmap memory maps a DB's data file. +// Based on: https://github.com/edsrzf/mmap-go +func mmap(db *DB, sz int) error { + if !db.readOnly { + // Truncate the database to the size of the mmap. + if err := db.file.Truncate(int64(sz)); err != nil { + return fmt.Errorf("truncate: %s", err) + } + } + + // Open a file mapping handle. + sizelo := uint32(sz >> 32) + sizehi := uint32(sz) & 0xffffffff + h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil) + if h == 0 { + return os.NewSyscallError("CreateFileMapping", errno) + } + + // Create the memory map. + addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) + if addr == 0 { + return os.NewSyscallError("MapViewOfFile", errno) + } + + // Close mapping handle. + if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { + return os.NewSyscallError("CloseHandle", err) + } + + // Convert to a byte array. + db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr))) + db.datasz = sz + + return nil +} + +// munmap unmaps a pointer from a file. +// Based on: https://github.com/edsrzf/mmap-go +func munmap(db *DB) error { + if db.data == nil { + return nil + } + + addr := (uintptr)(unsafe.Pointer(&db.data[0])) + if err := syscall.UnmapViewOfFile(addr); err != nil { + return os.NewSyscallError("UnmapViewOfFile", err) + } + return nil +} diff --git a/accounts/vendor/github.com/boltdb/bolt/boltsync_unix.go b/accounts/vendor/github.com/boltdb/bolt/boltsync_unix.go new file mode 100644 index 000000000..f50442523 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/boltsync_unix.go @@ -0,0 +1,8 @@ +// +build !windows,!plan9,!linux,!openbsd + +package bolt + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return db.file.Sync() +} diff --git a/accounts/vendor/github.com/boltdb/bolt/bucket.go b/accounts/vendor/github.com/boltdb/bolt/bucket.go new file mode 100644 index 000000000..511ce72d3 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/bucket.go @@ -0,0 +1,778 @@ +package bolt + +import ( + "bytes" + "fmt" + "unsafe" +) + +const ( + // MaxKeySize is the maximum length of a key, in bytes. + MaxKeySize = 32768 + + // MaxValueSize is the maximum length of a value, in bytes. + MaxValueSize = (1 << 31) - 2 +) + +const ( + maxUint = ^uint(0) + minUint = 0 + maxInt = int(^uint(0) >> 1) + minInt = -maxInt - 1 +) + +const bucketHeaderSize = int(unsafe.Sizeof(bucket{})) + +const ( + minFillPercent = 0.1 + maxFillPercent = 1.0 +) + +// DefaultFillPercent is the percentage that split pages are filled. +// This value can be changed by setting Bucket.FillPercent. +const DefaultFillPercent = 0.5 + +// Bucket represents a collection of key/value pairs inside the database. +type Bucket struct { + *bucket + tx *Tx // the associated transaction + buckets map[string]*Bucket // subbucket cache + page *page // inline page reference + rootNode *node // materialized node for the root page. + nodes map[pgid]*node // node cache + + // Sets the threshold for filling nodes when they split. By default, + // the bucket will fill to 50% but it can be useful to increase this + // amount if you know that your write workloads are mostly append-only. + // + // This is non-persisted across transactions so it must be set in every Tx. + FillPercent float64 +} + +// bucket represents the on-file representation of a bucket. +// This is stored as the "value" of a bucket key. If the bucket is small enough, +// then its root page can be stored inline in the "value", after the bucket +// header. In the case of inline buckets, the "root" will be 0. +type bucket struct { + root pgid // page id of the bucket's root-level page + sequence uint64 // monotonically incrementing, used by NextSequence() +} + +// newBucket returns a new bucket associated with a transaction. +func newBucket(tx *Tx) Bucket { + var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} + if tx.writable { + b.buckets = make(map[string]*Bucket) + b.nodes = make(map[pgid]*node) + } + return b +} + +// Tx returns the tx of the bucket. +func (b *Bucket) Tx() *Tx { + return b.tx +} + +// Root returns the root of the bucket. +func (b *Bucket) Root() pgid { + return b.root +} + +// Writable returns whether the bucket is writable. +func (b *Bucket) Writable() bool { + return b.tx.writable +} + +// Cursor creates a cursor associated with the bucket. +// The cursor is only valid as long as the transaction is open. +// Do not use a cursor after the transaction is closed. +func (b *Bucket) Cursor() *Cursor { + // Update transaction statistics. + b.tx.stats.CursorCount++ + + // Allocate and return a cursor. + return &Cursor{ + bucket: b, + stack: make([]elemRef, 0), + } +} + +// Bucket retrieves a nested bucket by name. +// Returns nil if the bucket does not exist. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) Bucket(name []byte) *Bucket { + if b.buckets != nil { + if child := b.buckets[string(name)]; child != nil { + return child + } + } + + // Move cursor to key. + c := b.Cursor() + k, v, flags := c.seek(name) + + // Return nil if the key doesn't exist or it is not a bucket. + if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { + return nil + } + + // Otherwise create a bucket and cache it. + var child = b.openBucket(v) + if b.buckets != nil { + b.buckets[string(name)] = child + } + + return child +} + +// Helper method that re-interprets a sub-bucket value +// from a parent into a Bucket +func (b *Bucket) openBucket(value []byte) *Bucket { + var child = newBucket(b.tx) + + // If unaligned load/stores are broken on this arch and value is + // unaligned simply clone to an aligned byte array. + unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 + + if unaligned { + value = cloneBytes(value) + } + + // If this is a writable transaction then we need to copy the bucket entry. + // Read-only transactions can point directly at the mmap entry. + if b.tx.writable && !unaligned { + child.bucket = &bucket{} + *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) + } else { + child.bucket = (*bucket)(unsafe.Pointer(&value[0])) + } + + // Save a reference to the inline page if the bucket is inline. + if child.root == 0 { + child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) + } + + return &child +} + +// CreateBucket creates a new bucket at the given key and returns the new bucket. +// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) { + if b.tx.db == nil { + return nil, ErrTxClosed + } else if !b.tx.writable { + return nil, ErrTxNotWritable + } else if len(key) == 0 { + return nil, ErrBucketNameRequired + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if there is an existing key. + if bytes.Equal(key, k) { + if (flags & bucketLeafFlag) != 0 { + return nil, ErrBucketExists + } else { + return nil, ErrIncompatibleValue + } + } + + // Create empty, inline bucket. + var bucket = Bucket{ + bucket: &bucket{}, + rootNode: &node{isLeaf: true}, + FillPercent: DefaultFillPercent, + } + var value = bucket.write() + + // Insert into node. + key = cloneBytes(key) + c.node().put(key, key, value, 0, bucketLeafFlag) + + // Since subbuckets are not allowed on inline buckets, we need to + // dereference the inline page, if it exists. This will cause the bucket + // to be treated as a regular, non-inline bucket for the rest of the tx. + b.page = nil + + return b.Bucket(key), nil +} + +// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. +// Returns an error if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { + child, err := b.CreateBucket(key) + if err == ErrBucketExists { + return b.Bucket(key), nil + } else if err != nil { + return nil, err + } + return child, nil +} + +// DeleteBucket deletes a bucket at the given key. +// Returns an error if the bucket does not exists, or if the key represents a non-bucket value. +func (b *Bucket) DeleteBucket(key []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if bucket doesn't exist or is not a bucket. + if !bytes.Equal(key, k) { + return ErrBucketNotFound + } else if (flags & bucketLeafFlag) == 0 { + return ErrIncompatibleValue + } + + // Recursively delete all child buckets. + child := b.Bucket(key) + err := child.ForEach(func(k, v []byte) error { + if v == nil { + if err := child.DeleteBucket(k); err != nil { + return fmt.Errorf("delete bucket: %s", err) + } + } + return nil + }) + if err != nil { + return err + } + + // Remove cached copy. + delete(b.buckets, string(key)) + + // Release all bucket pages to freelist. + child.nodes = nil + child.rootNode = nil + child.free() + + // Delete the node if we have a matching key. + c.node().del(key) + + return nil +} + +// Get retrieves the value for a key in the bucket. +// Returns a nil value if the key does not exist or if the key is a nested bucket. +// The returned value is only valid for the life of the transaction. +func (b *Bucket) Get(key []byte) []byte { + k, v, flags := b.Cursor().seek(key) + + // Return nil if this is a bucket. + if (flags & bucketLeafFlag) != 0 { + return nil + } + + // If our target node isn't the same key as what's passed in then return nil. + if !bytes.Equal(key, k) { + return nil + } + return v +} + +// Put sets the value for a key in the bucket. +// If the key exist then its previous value will be overwritten. +// Supplied value must remain valid for the life of the transaction. +// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. +func (b *Bucket) Put(key []byte, value []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } else if len(key) == 0 { + return ErrKeyRequired + } else if len(key) > MaxKeySize { + return ErrKeyTooLarge + } else if int64(len(value)) > MaxValueSize { + return ErrValueTooLarge + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if there is an existing key with a bucket value. + if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + + // Insert into node. + key = cloneBytes(key) + c.node().put(key, key, value, 0, 0) + + return nil +} + +// Delete removes a key from the bucket. +// If the key does not exist then nothing is done and a nil error is returned. +// Returns an error if the bucket was created from a read-only transaction. +func (b *Bucket) Delete(key []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Move cursor to correct position. + c := b.Cursor() + _, _, flags := c.seek(key) + + // Return an error if there is already existing bucket value. + if (flags & bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + + // Delete the node if we have a matching key. + c.node().del(key) + + return nil +} + +// Sequence returns the current integer for the bucket without incrementing it. +func (b *Bucket) Sequence() uint64 { return b.bucket.sequence } + +// SetSequence updates the sequence number for the bucket. +func (b *Bucket) SetSequence(v uint64) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Materialize the root node if it hasn't been already so that the + // bucket will be saved during commit. + if b.rootNode == nil { + _ = b.node(b.root, nil) + } + + // Increment and return the sequence. + b.bucket.sequence = v + return nil +} + +// NextSequence returns an autoincrementing integer for the bucket. +func (b *Bucket) NextSequence() (uint64, error) { + if b.tx.db == nil { + return 0, ErrTxClosed + } else if !b.Writable() { + return 0, ErrTxNotWritable + } + + // Materialize the root node if it hasn't been already so that the + // bucket will be saved during commit. + if b.rootNode == nil { + _ = b.node(b.root, nil) + } + + // Increment and return the sequence. + b.bucket.sequence++ + return b.bucket.sequence, nil +} + +// ForEach executes a function for each key/value pair in a bucket. +// If the provided function returns an error then the iteration is stopped and +// the error is returned to the caller. The provided function must not modify +// the bucket; this will result in undefined behavior. +func (b *Bucket) ForEach(fn func(k, v []byte) error) error { + if b.tx.db == nil { + return ErrTxClosed + } + c := b.Cursor() + for k, v := c.First(); k != nil; k, v = c.Next() { + if err := fn(k, v); err != nil { + return err + } + } + return nil +} + +// Stat returns stats on a bucket. +func (b *Bucket) Stats() BucketStats { + var s, subStats BucketStats + pageSize := b.tx.db.pageSize + s.BucketN += 1 + if b.root == 0 { + s.InlineBucketN += 1 + } + b.forEachPage(func(p *page, depth int) { + if (p.flags & leafPageFlag) != 0 { + s.KeyN += int(p.count) + + // used totals the used bytes for the page + used := pageHeaderSize + + if p.count != 0 { + // If page has any elements, add all element headers. + used += leafPageElementSize * int(p.count-1) + + // Add all element key, value sizes. + // The computation takes advantage of the fact that the position + // of the last element's key/value equals to the total of the sizes + // of all previous elements' keys and values. + // It also includes the last element's header. + lastElement := p.leafPageElement(p.count - 1) + used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) + } + + if b.root == 0 { + // For inlined bucket just update the inline stats + s.InlineBucketInuse += used + } else { + // For non-inlined bucket update all the leaf stats + s.LeafPageN++ + s.LeafInuse += used + s.LeafOverflowN += int(p.overflow) + + // Collect stats from sub-buckets. + // Do that by iterating over all element headers + // looking for the ones with the bucketLeafFlag. + for i := uint16(0); i < p.count; i++ { + e := p.leafPageElement(i) + if (e.flags & bucketLeafFlag) != 0 { + // For any bucket element, open the element value + // and recursively call Stats on the contained bucket. + subStats.Add(b.openBucket(e.value()).Stats()) + } + } + } + } else if (p.flags & branchPageFlag) != 0 { + s.BranchPageN++ + lastElement := p.branchPageElement(p.count - 1) + + // used totals the used bytes for the page + // Add header and all element headers. + used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) + + // Add size of all keys and values. + // Again, use the fact that last element's position equals to + // the total of key, value sizes of all previous elements. + used += int(lastElement.pos + lastElement.ksize) + s.BranchInuse += used + s.BranchOverflowN += int(p.overflow) + } + + // Keep track of maximum page depth. + if depth+1 > s.Depth { + s.Depth = (depth + 1) + } + }) + + // Alloc stats can be computed from page counts and pageSize. + s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize + s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize + + // Add the max depth of sub-buckets to get total nested depth. + s.Depth += subStats.Depth + // Add the stats for all sub-buckets + s.Add(subStats) + return s +} + +// forEachPage iterates over every page in a bucket, including inline pages. +func (b *Bucket) forEachPage(fn func(*page, int)) { + // If we have an inline page then just use that. + if b.page != nil { + fn(b.page, 0) + return + } + + // Otherwise traverse the page hierarchy. + b.tx.forEachPage(b.root, 0, fn) +} + +// forEachPageNode iterates over every page (or node) in a bucket. +// This also includes inline pages. +func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) { + // If we have an inline page or root node then just use that. + if b.page != nil { + fn(b.page, nil, 0) + return + } + b._forEachPageNode(b.root, 0, fn) +} + +func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) { + var p, n = b.pageNode(pgid) + + // Execute function. + fn(p, n, depth) + + // Recursively loop over children. + if p != nil { + if (p.flags & branchPageFlag) != 0 { + for i := 0; i < int(p.count); i++ { + elem := p.branchPageElement(uint16(i)) + b._forEachPageNode(elem.pgid, depth+1, fn) + } + } + } else { + if !n.isLeaf { + for _, inode := range n.inodes { + b._forEachPageNode(inode.pgid, depth+1, fn) + } + } + } +} + +// spill writes all the nodes for this bucket to dirty pages. +func (b *Bucket) spill() error { + // Spill all child buckets first. + for name, child := range b.buckets { + // If the child bucket is small enough and it has no child buckets then + // write it inline into the parent bucket's page. Otherwise spill it + // like a normal bucket and make the parent value a pointer to the page. + var value []byte + if child.inlineable() { + child.free() + value = child.write() + } else { + if err := child.spill(); err != nil { + return err + } + + // Update the child bucket header in this bucket. + value = make([]byte, unsafe.Sizeof(bucket{})) + var bucket = (*bucket)(unsafe.Pointer(&value[0])) + *bucket = *child.bucket + } + + // Skip writing the bucket if there are no materialized nodes. + if child.rootNode == nil { + continue + } + + // Update parent node. + var c = b.Cursor() + k, _, flags := c.seek([]byte(name)) + if !bytes.Equal([]byte(name), k) { + panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) + } + if flags&bucketLeafFlag == 0 { + panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) + } + c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) + } + + // Ignore if there's not a materialized root node. + if b.rootNode == nil { + return nil + } + + // Spill nodes. + if err := b.rootNode.spill(); err != nil { + return err + } + b.rootNode = b.rootNode.root() + + // Update the root node for this bucket. + if b.rootNode.pgid >= b.tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) + } + b.root = b.rootNode.pgid + + return nil +} + +// inlineable returns true if a bucket is small enough to be written inline +// and if it contains no subbuckets. Otherwise returns false. +func (b *Bucket) inlineable() bool { + var n = b.rootNode + + // Bucket must only contain a single leaf node. + if n == nil || !n.isLeaf { + return false + } + + // Bucket is not inlineable if it contains subbuckets or if it goes beyond + // our threshold for inline bucket size. + var size = pageHeaderSize + for _, inode := range n.inodes { + size += leafPageElementSize + len(inode.key) + len(inode.value) + + if inode.flags&bucketLeafFlag != 0 { + return false + } else if size > b.maxInlineBucketSize() { + return false + } + } + + return true +} + +// Returns the maximum total size of a bucket to make it a candidate for inlining. +func (b *Bucket) maxInlineBucketSize() int { + return b.tx.db.pageSize / 4 +} + +// write allocates and writes a bucket to a byte slice. +func (b *Bucket) write() []byte { + // Allocate the appropriate size. + var n = b.rootNode + var value = make([]byte, bucketHeaderSize+n.size()) + + // Write a bucket header. + var bucket = (*bucket)(unsafe.Pointer(&value[0])) + *bucket = *b.bucket + + // Convert byte slice to a fake page and write the root node. + var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) + n.write(p) + + return value +} + +// rebalance attempts to balance all nodes. +func (b *Bucket) rebalance() { + for _, n := range b.nodes { + n.rebalance() + } + for _, child := range b.buckets { + child.rebalance() + } +} + +// node creates a node from a page and associates it with a given parent. +func (b *Bucket) node(pgid pgid, parent *node) *node { + _assert(b.nodes != nil, "nodes map expected") + + // Retrieve node if it's already been created. + if n := b.nodes[pgid]; n != nil { + return n + } + + // Otherwise create a node and cache it. + n := &node{bucket: b, parent: parent} + if parent == nil { + b.rootNode = n + } else { + parent.children = append(parent.children, n) + } + + // Use the inline page if this is an inline bucket. + var p = b.page + if p == nil { + p = b.tx.page(pgid) + } + + // Read the page into the node and cache it. + n.read(p) + b.nodes[pgid] = n + + // Update statistics. + b.tx.stats.NodeCount++ + + return n +} + +// free recursively frees all pages in the bucket. +func (b *Bucket) free() { + if b.root == 0 { + return + } + + var tx = b.tx + b.forEachPageNode(func(p *page, n *node, _ int) { + if p != nil { + tx.db.freelist.free(tx.meta.txid, p) + } else { + n.free() + } + }) + b.root = 0 +} + +// dereference removes all references to the old mmap. +func (b *Bucket) dereference() { + if b.rootNode != nil { + b.rootNode.root().dereference() + } + + for _, child := range b.buckets { + child.dereference() + } +} + +// pageNode returns the in-memory node, if it exists. +// Otherwise returns the underlying page. +func (b *Bucket) pageNode(id pgid) (*page, *node) { + // Inline buckets have a fake page embedded in their value so treat them + // differently. We'll return the rootNode (if available) or the fake page. + if b.root == 0 { + if id != 0 { + panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) + } + if b.rootNode != nil { + return nil, b.rootNode + } + return b.page, nil + } + + // Check the node cache for non-inline buckets. + if b.nodes != nil { + if n := b.nodes[id]; n != nil { + return nil, n + } + } + + // Finally lookup the page from the transaction if no node is materialized. + return b.tx.page(id), nil +} + +// BucketStats records statistics about resources used by a bucket. +type BucketStats struct { + // Page count statistics. + BranchPageN int // number of logical branch pages + BranchOverflowN int // number of physical branch overflow pages + LeafPageN int // number of logical leaf pages + LeafOverflowN int // number of physical leaf overflow pages + + // Tree statistics. + KeyN int // number of keys/value pairs + Depth int // number of levels in B+tree + + // Page size utilization. + BranchAlloc int // bytes allocated for physical branch pages + BranchInuse int // bytes actually used for branch data + LeafAlloc int // bytes allocated for physical leaf pages + LeafInuse int // bytes actually used for leaf data + + // Bucket statistics + BucketN int // total number of buckets including the top bucket + InlineBucketN int // total number on inlined buckets + InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse) +} + +func (s *BucketStats) Add(other BucketStats) { + s.BranchPageN += other.BranchPageN + s.BranchOverflowN += other.BranchOverflowN + s.LeafPageN += other.LeafPageN + s.LeafOverflowN += other.LeafOverflowN + s.KeyN += other.KeyN + if s.Depth < other.Depth { + s.Depth = other.Depth + } + s.BranchAlloc += other.BranchAlloc + s.BranchInuse += other.BranchInuse + s.LeafAlloc += other.LeafAlloc + s.LeafInuse += other.LeafInuse + + s.BucketN += other.BucketN + s.InlineBucketN += other.InlineBucketN + s.InlineBucketInuse += other.InlineBucketInuse +} + +// cloneBytes returns a copy of a given slice. +func cloneBytes(v []byte) []byte { + var clone = make([]byte, len(v)) + copy(clone, v) + return clone +} diff --git a/accounts/vendor/github.com/boltdb/bolt/cmd/bolt/main.go b/accounts/vendor/github.com/boltdb/bolt/cmd/bolt/main.go new file mode 100644 index 000000000..29e393f01 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/cmd/bolt/main.go @@ -0,0 +1,1740 @@ +package main + +import ( + "bytes" + "encoding/binary" + "errors" + "flag" + "fmt" + "io" + "io/ioutil" + "math/rand" + "os" + "runtime" + "runtime/pprof" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + "unsafe" + + "github.com/boltdb/bolt" +) + +var ( + // ErrUsage is returned when a usage message was printed and the process + // should simply exit with an error. + ErrUsage = errors.New("usage") + + // ErrUnknownCommand is returned when a CLI command is not specified. + ErrUnknownCommand = errors.New("unknown command") + + // ErrPathRequired is returned when the path to a Bolt database is not specified. + ErrPathRequired = errors.New("path required") + + // ErrFileNotFound is returned when a Bolt database does not exist. + ErrFileNotFound = errors.New("file not found") + + // ErrInvalidValue is returned when a benchmark reads an unexpected value. + ErrInvalidValue = errors.New("invalid value") + + // ErrCorrupt is returned when a checking a data file finds errors. + ErrCorrupt = errors.New("invalid value") + + // ErrNonDivisibleBatchSize is returned when the batch size can't be evenly + // divided by the iteration count. + ErrNonDivisibleBatchSize = errors.New("number of iterations must be divisible by the batch size") + + // ErrPageIDRequired is returned when a required page id is not specified. + ErrPageIDRequired = errors.New("page id required") + + // ErrPageNotFound is returned when specifying a page above the high water mark. + ErrPageNotFound = errors.New("page not found") + + // ErrPageFreed is returned when reading a page that has already been freed. + ErrPageFreed = errors.New("page freed") +) + +// PageHeaderSize represents the size of the bolt.page header. +const PageHeaderSize = 16 + +func main() { + m := NewMain() + if err := m.Run(os.Args[1:]...); err == ErrUsage { + os.Exit(2) + } else if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } +} + +// Main represents the main program execution. +type Main struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewMain returns a new instance of Main connect to the standard input/output. +func NewMain() *Main { + return &Main{ + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run executes the program. +func (m *Main) Run(args ...string) error { + // Require a command at the beginning. + if len(args) == 0 || strings.HasPrefix(args[0], "-") { + fmt.Fprintln(m.Stderr, m.Usage()) + return ErrUsage + } + + // Execute command. + switch args[0] { + case "help": + fmt.Fprintln(m.Stderr, m.Usage()) + return ErrUsage + case "bench": + return newBenchCommand(m).Run(args[1:]...) + case "check": + return newCheckCommand(m).Run(args[1:]...) + case "compact": + return newCompactCommand(m).Run(args[1:]...) + case "dump": + return newDumpCommand(m).Run(args[1:]...) + case "info": + return newInfoCommand(m).Run(args[1:]...) + case "page": + return newPageCommand(m).Run(args[1:]...) + case "pages": + return newPagesCommand(m).Run(args[1:]...) + case "stats": + return newStatsCommand(m).Run(args[1:]...) + default: + return ErrUnknownCommand + } +} + +// Usage returns the help message. +func (m *Main) Usage() string { + return strings.TrimLeft(` +Bolt is a tool for inspecting bolt databases. + +Usage: + + bolt command [arguments] + +The commands are: + + bench run synthetic benchmark against bolt + check verifies integrity of bolt database + compact copies a bolt database, compacting it in the process + info print basic info + help print this screen + pages print list of pages with their types + stats iterate over all pages and generate usage stats + +Use "bolt [command] -h" for more information about a command. +`, "\n") +} + +// CheckCommand represents the "check" command execution. +type CheckCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewCheckCommand returns a CheckCommand. +func newCheckCommand(m *Main) *CheckCommand { + return &CheckCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *CheckCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path. + path := fs.Arg(0) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Open database. + db, err := bolt.Open(path, 0666, nil) + if err != nil { + return err + } + defer db.Close() + + // Perform consistency check. + return db.View(func(tx *bolt.Tx) error { + var count int + ch := tx.Check() + loop: + for { + select { + case err, ok := <-ch: + if !ok { + break loop + } + fmt.Fprintln(cmd.Stdout, err) + count++ + } + } + + // Print summary of errors. + if count > 0 { + fmt.Fprintf(cmd.Stdout, "%d errors found\n", count) + return ErrCorrupt + } + + // Notify user that database is valid. + fmt.Fprintln(cmd.Stdout, "OK") + return nil + }) +} + +// Usage returns the help message. +func (cmd *CheckCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt check PATH + +Check opens a database at PATH and runs an exhaustive check to verify that +all pages are accessible or are marked as freed. It also verifies that no +pages are double referenced. + +Verification errors will stream out as they are found and the process will +return after all pages have been checked. +`, "\n") +} + +// InfoCommand represents the "info" command execution. +type InfoCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewInfoCommand returns a InfoCommand. +func newInfoCommand(m *Main) *InfoCommand { + return &InfoCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *InfoCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path. + path := fs.Arg(0) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Open the database. + db, err := bolt.Open(path, 0666, nil) + if err != nil { + return err + } + defer db.Close() + + // Print basic database info. + info := db.Info() + fmt.Fprintf(cmd.Stdout, "Page Size: %d\n", info.PageSize) + + return nil +} + +// Usage returns the help message. +func (cmd *InfoCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt info PATH + +Info prints basic information about the Bolt database at PATH. +`, "\n") +} + +// DumpCommand represents the "dump" command execution. +type DumpCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// newDumpCommand returns a DumpCommand. +func newDumpCommand(m *Main) *DumpCommand { + return &DumpCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *DumpCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path and page id. + path := fs.Arg(0) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Read page ids. + pageIDs, err := atois(fs.Args()[1:]) + if err != nil { + return err + } else if len(pageIDs) == 0 { + return ErrPageIDRequired + } + + // Open database to retrieve page size. + pageSize, err := ReadPageSize(path) + if err != nil { + return err + } + + // Open database file handler. + f, err := os.Open(path) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + + // Print each page listed. + for i, pageID := range pageIDs { + // Print a separator. + if i > 0 { + fmt.Fprintln(cmd.Stdout, "===============================================") + } + + // Print page to stdout. + if err := cmd.PrintPage(cmd.Stdout, f, pageID, pageSize); err != nil { + return err + } + } + + return nil +} + +// PrintPage prints a given page as hexidecimal. +func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { + const bytesPerLineN = 16 + + // Read page into buffer. + buf := make([]byte, pageSize) + addr := pageID * pageSize + if n, err := r.ReadAt(buf, int64(addr)); err != nil { + return err + } else if n != pageSize { + return io.ErrUnexpectedEOF + } + + // Write out to writer in 16-byte lines. + var prev []byte + var skipped bool + for offset := 0; offset < pageSize; offset += bytesPerLineN { + // Retrieve current 16-byte line. + line := buf[offset : offset+bytesPerLineN] + isLastLine := (offset == (pageSize - bytesPerLineN)) + + // If it's the same as the previous line then print a skip. + if bytes.Equal(line, prev) && !isLastLine { + if !skipped { + fmt.Fprintf(w, "%07x *\n", addr+offset) + skipped = true + } + } else { + // Print line as hexadecimal in 2-byte groups. + fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, + line[0:2], line[2:4], line[4:6], line[6:8], + line[8:10], line[10:12], line[12:14], line[14:16], + ) + + skipped = false + } + + // Save the previous line. + prev = line + } + fmt.Fprint(w, "\n") + + return nil +} + +// Usage returns the help message. +func (cmd *DumpCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt dump -page PAGEID PATH + +Dump prints a hexidecimal dump of a single page. +`, "\n") +} + +// PageCommand represents the "page" command execution. +type PageCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// newPageCommand returns a PageCommand. +func newPageCommand(m *Main) *PageCommand { + return &PageCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *PageCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path and page id. + path := fs.Arg(0) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Read page ids. + pageIDs, err := atois(fs.Args()[1:]) + if err != nil { + return err + } else if len(pageIDs) == 0 { + return ErrPageIDRequired + } + + // Open database file handler. + f, err := os.Open(path) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + + // Print each page listed. + for i, pageID := range pageIDs { + // Print a separator. + if i > 0 { + fmt.Fprintln(cmd.Stdout, "===============================================") + } + + // Retrieve page info and page size. + p, buf, err := ReadPage(path, pageID) + if err != nil { + return err + } + + // Print basic page info. + fmt.Fprintf(cmd.Stdout, "Page ID: %d\n", p.id) + fmt.Fprintf(cmd.Stdout, "Page Type: %s\n", p.Type()) + fmt.Fprintf(cmd.Stdout, "Total Size: %d bytes\n", len(buf)) + + // Print type-specific data. + switch p.Type() { + case "meta": + err = cmd.PrintMeta(cmd.Stdout, buf) + case "leaf": + err = cmd.PrintLeaf(cmd.Stdout, buf) + case "branch": + err = cmd.PrintBranch(cmd.Stdout, buf) + case "freelist": + err = cmd.PrintFreelist(cmd.Stdout, buf) + } + if err != nil { + return err + } + } + + return nil +} + +// PrintMeta prints the data from the meta page. +func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error { + m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) + fmt.Fprintf(w, "Version: %d\n", m.version) + fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize) + fmt.Fprintf(w, "Flags: %08x\n", m.flags) + fmt.Fprintf(w, "Root: \n", m.root.root) + fmt.Fprintf(w, "Freelist: \n", m.freelist) + fmt.Fprintf(w, "HWM: \n", m.pgid) + fmt.Fprintf(w, "Txn ID: %d\n", m.txid) + fmt.Fprintf(w, "Checksum: %016x\n", m.checksum) + fmt.Fprintf(w, "\n") + return nil +} + +// PrintLeaf prints the data for a leaf page. +func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error { + p := (*page)(unsafe.Pointer(&buf[0])) + + // Print number of items. + fmt.Fprintf(w, "Item Count: %d\n", p.count) + fmt.Fprintf(w, "\n") + + // Print each key/value. + for i := uint16(0); i < p.count; i++ { + e := p.leafPageElement(i) + + // Format key as string. + var k string + if isPrintable(string(e.key())) { + k = fmt.Sprintf("%q", string(e.key())) + } else { + k = fmt.Sprintf("%x", string(e.key())) + } + + // Format value as string. + var v string + if (e.flags & uint32(bucketLeafFlag)) != 0 { + b := (*bucket)(unsafe.Pointer(&e.value()[0])) + v = fmt.Sprintf("", b.root, b.sequence) + } else if isPrintable(string(e.value())) { + v = fmt.Sprintf("%q", string(e.value())) + } else { + v = fmt.Sprintf("%x", string(e.value())) + } + + fmt.Fprintf(w, "%s: %s\n", k, v) + } + fmt.Fprintf(w, "\n") + return nil +} + +// PrintBranch prints the data for a leaf page. +func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error { + p := (*page)(unsafe.Pointer(&buf[0])) + + // Print number of items. + fmt.Fprintf(w, "Item Count: %d\n", p.count) + fmt.Fprintf(w, "\n") + + // Print each key/value. + for i := uint16(0); i < p.count; i++ { + e := p.branchPageElement(i) + + // Format key as string. + var k string + if isPrintable(string(e.key())) { + k = fmt.Sprintf("%q", string(e.key())) + } else { + k = fmt.Sprintf("%x", string(e.key())) + } + + fmt.Fprintf(w, "%s: \n", k, e.pgid) + } + fmt.Fprintf(w, "\n") + return nil +} + +// PrintFreelist prints the data for a freelist page. +func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error { + p := (*page)(unsafe.Pointer(&buf[0])) + + // Print number of items. + fmt.Fprintf(w, "Item Count: %d\n", p.count) + fmt.Fprintf(w, "\n") + + // Print each page in the freelist. + ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)) + for i := uint16(0); i < p.count; i++ { + fmt.Fprintf(w, "%d\n", ids[i]) + } + fmt.Fprintf(w, "\n") + return nil +} + +// PrintPage prints a given page as hexidecimal. +func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { + const bytesPerLineN = 16 + + // Read page into buffer. + buf := make([]byte, pageSize) + addr := pageID * pageSize + if n, err := r.ReadAt(buf, int64(addr)); err != nil { + return err + } else if n != pageSize { + return io.ErrUnexpectedEOF + } + + // Write out to writer in 16-byte lines. + var prev []byte + var skipped bool + for offset := 0; offset < pageSize; offset += bytesPerLineN { + // Retrieve current 16-byte line. + line := buf[offset : offset+bytesPerLineN] + isLastLine := (offset == (pageSize - bytesPerLineN)) + + // If it's the same as the previous line then print a skip. + if bytes.Equal(line, prev) && !isLastLine { + if !skipped { + fmt.Fprintf(w, "%07x *\n", addr+offset) + skipped = true + } + } else { + // Print line as hexadecimal in 2-byte groups. + fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, + line[0:2], line[2:4], line[4:6], line[6:8], + line[8:10], line[10:12], line[12:14], line[14:16], + ) + + skipped = false + } + + // Save the previous line. + prev = line + } + fmt.Fprint(w, "\n") + + return nil +} + +// Usage returns the help message. +func (cmd *PageCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt page -page PATH pageid [pageid...] + +Page prints one or more pages in human readable format. +`, "\n") +} + +// PagesCommand represents the "pages" command execution. +type PagesCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewPagesCommand returns a PagesCommand. +func newPagesCommand(m *Main) *PagesCommand { + return &PagesCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *PagesCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path. + path := fs.Arg(0) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Open database. + db, err := bolt.Open(path, 0666, nil) + if err != nil { + return err + } + defer func() { _ = db.Close() }() + + // Write header. + fmt.Fprintln(cmd.Stdout, "ID TYPE ITEMS OVRFLW") + fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======") + + return db.Update(func(tx *bolt.Tx) error { + var id int + for { + p, err := tx.Page(id) + if err != nil { + return &PageError{ID: id, Err: err} + } else if p == nil { + break + } + + // Only display count and overflow if this is a non-free page. + var count, overflow string + if p.Type != "free" { + count = strconv.Itoa(p.Count) + if p.OverflowCount > 0 { + overflow = strconv.Itoa(p.OverflowCount) + } + } + + // Print table row. + fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow) + + // Move to the next non-overflow page. + id += 1 + if p.Type != "free" { + id += p.OverflowCount + } + } + return nil + }) +} + +// Usage returns the help message. +func (cmd *PagesCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt pages PATH + +Pages prints a table of pages with their type (meta, leaf, branch, freelist). +Leaf and branch pages will show a key count in the "items" column while the +freelist will show the number of free pages in the "items" column. + +The "overflow" column shows the number of blocks that the page spills over +into. Normally there is no overflow but large keys and values can cause +a single page to take up multiple blocks. +`, "\n") +} + +// StatsCommand represents the "stats" command execution. +type StatsCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewStatsCommand returns a StatsCommand. +func newStatsCommand(m *Main) *StatsCommand { + return &StatsCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *StatsCommand) Run(args ...string) error { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + help := fs.Bool("h", false, "") + if err := fs.Parse(args); err != nil { + return err + } else if *help { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } + + // Require database path. + path, prefix := fs.Arg(0), fs.Arg(1) + if path == "" { + return ErrPathRequired + } else if _, err := os.Stat(path); os.IsNotExist(err) { + return ErrFileNotFound + } + + // Open database. + db, err := bolt.Open(path, 0666, nil) + if err != nil { + return err + } + defer db.Close() + + return db.View(func(tx *bolt.Tx) error { + var s bolt.BucketStats + var count int + if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { + if bytes.HasPrefix(name, []byte(prefix)) { + s.Add(b.Stats()) + count += 1 + } + return nil + }); err != nil { + return err + } + + fmt.Fprintf(cmd.Stdout, "Aggregate statistics for %d buckets\n\n", count) + + fmt.Fprintln(cmd.Stdout, "Page count statistics") + fmt.Fprintf(cmd.Stdout, "\tNumber of logical branch pages: %d\n", s.BranchPageN) + fmt.Fprintf(cmd.Stdout, "\tNumber of physical branch overflow pages: %d\n", s.BranchOverflowN) + fmt.Fprintf(cmd.Stdout, "\tNumber of logical leaf pages: %d\n", s.LeafPageN) + fmt.Fprintf(cmd.Stdout, "\tNumber of physical leaf overflow pages: %d\n", s.LeafOverflowN) + + fmt.Fprintln(cmd.Stdout, "Tree statistics") + fmt.Fprintf(cmd.Stdout, "\tNumber of keys/value pairs: %d\n", s.KeyN) + fmt.Fprintf(cmd.Stdout, "\tNumber of levels in B+tree: %d\n", s.Depth) + + fmt.Fprintln(cmd.Stdout, "Page size utilization") + fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical branch pages: %d\n", s.BranchAlloc) + var percentage int + if s.BranchAlloc != 0 { + percentage = int(float32(s.BranchInuse) * 100.0 / float32(s.BranchAlloc)) + } + fmt.Fprintf(cmd.Stdout, "\tBytes actually used for branch data: %d (%d%%)\n", s.BranchInuse, percentage) + fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical leaf pages: %d\n", s.LeafAlloc) + percentage = 0 + if s.LeafAlloc != 0 { + percentage = int(float32(s.LeafInuse) * 100.0 / float32(s.LeafAlloc)) + } + fmt.Fprintf(cmd.Stdout, "\tBytes actually used for leaf data: %d (%d%%)\n", s.LeafInuse, percentage) + + fmt.Fprintln(cmd.Stdout, "Bucket statistics") + fmt.Fprintf(cmd.Stdout, "\tTotal number of buckets: %d\n", s.BucketN) + percentage = 0 + if s.BucketN != 0 { + percentage = int(float32(s.InlineBucketN) * 100.0 / float32(s.BucketN)) + } + fmt.Fprintf(cmd.Stdout, "\tTotal number on inlined buckets: %d (%d%%)\n", s.InlineBucketN, percentage) + percentage = 0 + if s.LeafInuse != 0 { + percentage = int(float32(s.InlineBucketInuse) * 100.0 / float32(s.LeafInuse)) + } + fmt.Fprintf(cmd.Stdout, "\tBytes used for inlined buckets: %d (%d%%)\n", s.InlineBucketInuse, percentage) + + return nil + }) +} + +// Usage returns the help message. +func (cmd *StatsCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt stats PATH + +Stats performs an extensive search of the database to track every page +reference. It starts at the current meta page and recursively iterates +through every accessible bucket. + +The following errors can be reported: + + already freed + The page is referenced more than once in the freelist. + + unreachable unfreed + The page is not referenced by a bucket or in the freelist. + + reachable freed + The page is referenced by a bucket but is also in the freelist. + + out of bounds + A page is referenced that is above the high water mark. + + multiple references + A page is referenced by more than one other page. + + invalid type + The page type is not "meta", "leaf", "branch", or "freelist". + +No errors should occur in your database. However, if for some reason you +experience corruption, please submit a ticket to the Bolt project page: + + https://github.com/boltdb/bolt/issues +`, "\n") +} + +var benchBucketName = []byte("bench") + +// BenchCommand represents the "bench" command execution. +type BenchCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewBenchCommand returns a BenchCommand using the +func newBenchCommand(m *Main) *BenchCommand { + return &BenchCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the "bench" command. +func (cmd *BenchCommand) Run(args ...string) error { + // Parse CLI arguments. + options, err := cmd.ParseFlags(args) + if err != nil { + return err + } + + // Remove path if "-work" is not set. Otherwise keep path. + if options.Work { + fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path) + } else { + defer os.Remove(options.Path) + } + + // Create database. + db, err := bolt.Open(options.Path, 0666, nil) + if err != nil { + return err + } + db.NoSync = options.NoSync + defer db.Close() + + // Write to the database. + var results BenchResults + if err := cmd.runWrites(db, options, &results); err != nil { + return fmt.Errorf("write: %v", err) + } + + // Read from the database. + if err := cmd.runReads(db, options, &results); err != nil { + return fmt.Errorf("bench: read: %s", err) + } + + // Print results. + fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond()) + fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond()) + fmt.Fprintln(os.Stderr, "") + return nil +} + +// ParseFlags parses the command line flags. +func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, error) { + var options BenchOptions + + // Parse flagset. + fs := flag.NewFlagSet("", flag.ContinueOnError) + fs.StringVar(&options.ProfileMode, "profile-mode", "rw", "") + fs.StringVar(&options.WriteMode, "write-mode", "seq", "") + fs.StringVar(&options.ReadMode, "read-mode", "seq", "") + fs.IntVar(&options.Iterations, "count", 1000, "") + fs.IntVar(&options.BatchSize, "batch-size", 0, "") + fs.IntVar(&options.KeySize, "key-size", 8, "") + fs.IntVar(&options.ValueSize, "value-size", 32, "") + fs.StringVar(&options.CPUProfile, "cpuprofile", "", "") + fs.StringVar(&options.MemProfile, "memprofile", "", "") + fs.StringVar(&options.BlockProfile, "blockprofile", "", "") + fs.Float64Var(&options.FillPercent, "fill-percent", bolt.DefaultFillPercent, "") + fs.BoolVar(&options.NoSync, "no-sync", false, "") + fs.BoolVar(&options.Work, "work", false, "") + fs.StringVar(&options.Path, "path", "", "") + fs.SetOutput(cmd.Stderr) + if err := fs.Parse(args); err != nil { + return nil, err + } + + // Set batch size to iteration size if not set. + // Require that batch size can be evenly divided by the iteration count. + if options.BatchSize == 0 { + options.BatchSize = options.Iterations + } else if options.Iterations%options.BatchSize != 0 { + return nil, ErrNonDivisibleBatchSize + } + + // Generate temp path if one is not passed in. + if options.Path == "" { + f, err := ioutil.TempFile("", "bolt-bench-") + if err != nil { + return nil, fmt.Errorf("temp file: %s", err) + } + f.Close() + os.Remove(f.Name()) + options.Path = f.Name() + } + + return &options, nil +} + +// Writes to the database. +func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + // Start profiling for writes. + if options.ProfileMode == "rw" || options.ProfileMode == "w" { + cmd.startProfiling(options) + } + + t := time.Now() + + var err error + switch options.WriteMode { + case "seq": + err = cmd.runWritesSequential(db, options, results) + case "rnd": + err = cmd.runWritesRandom(db, options, results) + case "seq-nest": + err = cmd.runWritesSequentialNested(db, options, results) + case "rnd-nest": + err = cmd.runWritesRandomNested(db, options, results) + default: + return fmt.Errorf("invalid write mode: %s", options.WriteMode) + } + + // Save time to write. + results.WriteDuration = time.Since(t) + + // Stop profiling for writes only. + if options.ProfileMode == "w" { + cmd.stopProfiling() + } + + return err +} + +func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + var i = uint32(0) + return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i }) +} + +func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() }) +} + +func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + var i = uint32(0) + return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i }) +} + +func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() }) +} + +func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error { + results.WriteOps = options.Iterations + + for i := 0; i < options.Iterations; i += options.BatchSize { + if err := db.Update(func(tx *bolt.Tx) error { + b, _ := tx.CreateBucketIfNotExists(benchBucketName) + b.FillPercent = options.FillPercent + + for j := 0; j < options.BatchSize; j++ { + key := make([]byte, options.KeySize) + value := make([]byte, options.ValueSize) + + // Write key as uint32. + binary.BigEndian.PutUint32(key, keySource()) + + // Insert key/value. + if err := b.Put(key, value); err != nil { + return err + } + } + + return nil + }); err != nil { + return err + } + } + return nil +} + +func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error { + results.WriteOps = options.Iterations + + for i := 0; i < options.Iterations; i += options.BatchSize { + if err := db.Update(func(tx *bolt.Tx) error { + top, err := tx.CreateBucketIfNotExists(benchBucketName) + if err != nil { + return err + } + top.FillPercent = options.FillPercent + + // Create bucket key. + name := make([]byte, options.KeySize) + binary.BigEndian.PutUint32(name, keySource()) + + // Create bucket. + b, err := top.CreateBucketIfNotExists(name) + if err != nil { + return err + } + b.FillPercent = options.FillPercent + + for j := 0; j < options.BatchSize; j++ { + var key = make([]byte, options.KeySize) + var value = make([]byte, options.ValueSize) + + // Generate key as uint32. + binary.BigEndian.PutUint32(key, keySource()) + + // Insert value into subbucket. + if err := b.Put(key, value); err != nil { + return err + } + } + + return nil + }); err != nil { + return err + } + } + return nil +} + +// Reads from the database. +func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + // Start profiling for reads. + if options.ProfileMode == "r" { + cmd.startProfiling(options) + } + + t := time.Now() + + var err error + switch options.ReadMode { + case "seq": + switch options.WriteMode { + case "seq-nest", "rnd-nest": + err = cmd.runReadsSequentialNested(db, options, results) + default: + err = cmd.runReadsSequential(db, options, results) + } + default: + return fmt.Errorf("invalid read mode: %s", options.ReadMode) + } + + // Save read time. + results.ReadDuration = time.Since(t) + + // Stop profiling for reads. + if options.ProfileMode == "rw" || options.ProfileMode == "r" { + cmd.stopProfiling() + } + + return err +} + +func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + return db.View(func(tx *bolt.Tx) error { + t := time.Now() + + for { + var count int + + c := tx.Bucket(benchBucketName).Cursor() + for k, v := c.First(); k != nil; k, v = c.Next() { + if v == nil { + return errors.New("invalid value") + } + count++ + } + + if options.WriteMode == "seq" && count != options.Iterations { + return fmt.Errorf("read seq: iter mismatch: expected %d, got %d", options.Iterations, count) + } + + results.ReadOps += count + + // Make sure we do this for at least a second. + if time.Since(t) >= time.Second { + break + } + } + + return nil + }) +} + +func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { + return db.View(func(tx *bolt.Tx) error { + t := time.Now() + + for { + var count int + var top = tx.Bucket(benchBucketName) + if err := top.ForEach(func(name, _ []byte) error { + c := top.Bucket(name).Cursor() + for k, v := c.First(); k != nil; k, v = c.Next() { + if v == nil { + return ErrInvalidValue + } + count++ + } + return nil + }); err != nil { + return err + } + + if options.WriteMode == "seq-nest" && count != options.Iterations { + return fmt.Errorf("read seq-nest: iter mismatch: expected %d, got %d", options.Iterations, count) + } + + results.ReadOps += count + + // Make sure we do this for at least a second. + if time.Since(t) >= time.Second { + break + } + } + + return nil + }) +} + +// File handlers for the various profiles. +var cpuprofile, memprofile, blockprofile *os.File + +// Starts all profiles set on the options. +func (cmd *BenchCommand) startProfiling(options *BenchOptions) { + var err error + + // Start CPU profiling. + if options.CPUProfile != "" { + cpuprofile, err = os.Create(options.CPUProfile) + if err != nil { + fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err) + os.Exit(1) + } + pprof.StartCPUProfile(cpuprofile) + } + + // Start memory profiling. + if options.MemProfile != "" { + memprofile, err = os.Create(options.MemProfile) + if err != nil { + fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err) + os.Exit(1) + } + runtime.MemProfileRate = 4096 + } + + // Start fatal profiling. + if options.BlockProfile != "" { + blockprofile, err = os.Create(options.BlockProfile) + if err != nil { + fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err) + os.Exit(1) + } + runtime.SetBlockProfileRate(1) + } +} + +// Stops all profiles. +func (cmd *BenchCommand) stopProfiling() { + if cpuprofile != nil { + pprof.StopCPUProfile() + cpuprofile.Close() + cpuprofile = nil + } + + if memprofile != nil { + pprof.Lookup("heap").WriteTo(memprofile, 0) + memprofile.Close() + memprofile = nil + } + + if blockprofile != nil { + pprof.Lookup("block").WriteTo(blockprofile, 0) + blockprofile.Close() + blockprofile = nil + runtime.SetBlockProfileRate(0) + } +} + +// BenchOptions represents the set of options that can be passed to "bolt bench". +type BenchOptions struct { + ProfileMode string + WriteMode string + ReadMode string + Iterations int + BatchSize int + KeySize int + ValueSize int + CPUProfile string + MemProfile string + BlockProfile string + StatsInterval time.Duration + FillPercent float64 + NoSync bool + Work bool + Path string +} + +// BenchResults represents the performance results of the benchmark. +type BenchResults struct { + WriteOps int + WriteDuration time.Duration + ReadOps int + ReadDuration time.Duration +} + +// Returns the duration for a single write operation. +func (r *BenchResults) WriteOpDuration() time.Duration { + if r.WriteOps == 0 { + return 0 + } + return r.WriteDuration / time.Duration(r.WriteOps) +} + +// Returns average number of write operations that can be performed per second. +func (r *BenchResults) WriteOpsPerSecond() int { + var op = r.WriteOpDuration() + if op == 0 { + return 0 + } + return int(time.Second) / int(op) +} + +// Returns the duration for a single read operation. +func (r *BenchResults) ReadOpDuration() time.Duration { + if r.ReadOps == 0 { + return 0 + } + return r.ReadDuration / time.Duration(r.ReadOps) +} + +// Returns average number of read operations that can be performed per second. +func (r *BenchResults) ReadOpsPerSecond() int { + var op = r.ReadOpDuration() + if op == 0 { + return 0 + } + return int(time.Second) / int(op) +} + +type PageError struct { + ID int + Err error +} + +func (e *PageError) Error() string { + return fmt.Sprintf("page error: id=%d, err=%s", e.ID, e.Err) +} + +// isPrintable returns true if the string is valid unicode and contains only printable runes. +func isPrintable(s string) bool { + if !utf8.ValidString(s) { + return false + } + for _, ch := range s { + if !unicode.IsPrint(ch) { + return false + } + } + return true +} + +// ReadPage reads page info & full page data from a path. +// This is not transactionally safe. +func ReadPage(path string, pageID int) (*page, []byte, error) { + // Find page size. + pageSize, err := ReadPageSize(path) + if err != nil { + return nil, nil, fmt.Errorf("read page size: %s", err) + } + + // Open database file. + f, err := os.Open(path) + if err != nil { + return nil, nil, err + } + defer f.Close() + + // Read one block into buffer. + buf := make([]byte, pageSize) + if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { + return nil, nil, err + } else if n != len(buf) { + return nil, nil, io.ErrUnexpectedEOF + } + + // Determine total number of blocks. + p := (*page)(unsafe.Pointer(&buf[0])) + overflowN := p.overflow + + // Re-read entire page (with overflow) into buffer. + buf = make([]byte, (int(overflowN)+1)*pageSize) + if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { + return nil, nil, err + } else if n != len(buf) { + return nil, nil, io.ErrUnexpectedEOF + } + p = (*page)(unsafe.Pointer(&buf[0])) + + return p, buf, nil +} + +// ReadPageSize reads page size a path. +// This is not transactionally safe. +func ReadPageSize(path string) (int, error) { + // Open database file. + f, err := os.Open(path) + if err != nil { + return 0, err + } + defer f.Close() + + // Read 4KB chunk. + buf := make([]byte, 4096) + if _, err := io.ReadFull(f, buf); err != nil { + return 0, err + } + + // Read page size from metadata. + m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) + return int(m.pageSize), nil +} + +// atois parses a slice of strings into integers. +func atois(strs []string) ([]int, error) { + var a []int + for _, str := range strs { + i, err := strconv.Atoi(str) + if err != nil { + return nil, err + } + a = append(a, i) + } + return a, nil +} + +// DO NOT EDIT. Copied from the "bolt" package. +const maxAllocSize = 0xFFFFFFF + +// DO NOT EDIT. Copied from the "bolt" package. +const ( + branchPageFlag = 0x01 + leafPageFlag = 0x02 + metaPageFlag = 0x04 + freelistPageFlag = 0x10 +) + +// DO NOT EDIT. Copied from the "bolt" package. +const bucketLeafFlag = 0x01 + +// DO NOT EDIT. Copied from the "bolt" package. +type pgid uint64 + +// DO NOT EDIT. Copied from the "bolt" package. +type txid uint64 + +// DO NOT EDIT. Copied from the "bolt" package. +type meta struct { + magic uint32 + version uint32 + pageSize uint32 + flags uint32 + root bucket + freelist pgid + pgid pgid + txid txid + checksum uint64 +} + +// DO NOT EDIT. Copied from the "bolt" package. +type bucket struct { + root pgid + sequence uint64 +} + +// DO NOT EDIT. Copied from the "bolt" package. +type page struct { + id pgid + flags uint16 + count uint16 + overflow uint32 + ptr uintptr +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (p *page) Type() string { + if (p.flags & branchPageFlag) != 0 { + return "branch" + } else if (p.flags & leafPageFlag) != 0 { + return "leaf" + } else if (p.flags & metaPageFlag) != 0 { + return "meta" + } else if (p.flags & freelistPageFlag) != 0 { + return "freelist" + } + return fmt.Sprintf("unknown<%02x>", p.flags) +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (p *page) leafPageElement(index uint16) *leafPageElement { + n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] + return n +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (p *page) branchPageElement(index uint16) *branchPageElement { + return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] +} + +// DO NOT EDIT. Copied from the "bolt" package. +type branchPageElement struct { + pos uint32 + ksize uint32 + pgid pgid +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (n *branchPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return buf[n.pos : n.pos+n.ksize] +} + +// DO NOT EDIT. Copied from the "bolt" package. +type leafPageElement struct { + flags uint32 + pos uint32 + ksize uint32 + vsize uint32 +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (n *leafPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return buf[n.pos : n.pos+n.ksize] +} + +// DO NOT EDIT. Copied from the "bolt" package. +func (n *leafPageElement) value() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return buf[n.pos+n.ksize : n.pos+n.ksize+n.vsize] +} + +// CompactCommand represents the "compact" command execution. +type CompactCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer + + SrcPath string + DstPath string + TxMaxSize int64 +} + +// newCompactCommand returns a CompactCommand. +func newCompactCommand(m *Main) *CompactCommand { + return &CompactCommand{ + Stdin: m.Stdin, + Stdout: m.Stdout, + Stderr: m.Stderr, + } +} + +// Run executes the command. +func (cmd *CompactCommand) Run(args ...string) (err error) { + // Parse flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + fs.SetOutput(ioutil.Discard) + fs.StringVar(&cmd.DstPath, "o", "", "") + fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "") + if err := fs.Parse(args); err == flag.ErrHelp { + fmt.Fprintln(cmd.Stderr, cmd.Usage()) + return ErrUsage + } else if err != nil { + return err + } else if cmd.DstPath == "" { + return fmt.Errorf("output file required") + } + + // Require database paths. + cmd.SrcPath = fs.Arg(0) + if cmd.SrcPath == "" { + return ErrPathRequired + } + + // Ensure source file exists. + fi, err := os.Stat(cmd.SrcPath) + if os.IsNotExist(err) { + return ErrFileNotFound + } else if err != nil { + return err + } + initialSize := fi.Size() + + // Open source database. + src, err := bolt.Open(cmd.SrcPath, 0444, nil) + if err != nil { + return err + } + defer src.Close() + + // Open destination database. + dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil) + if err != nil { + return err + } + defer dst.Close() + + // Run compaction. + if err := cmd.compact(dst, src); err != nil { + return err + } + + // Report stats on new size. + fi, err = os.Stat(cmd.DstPath) + if err != nil { + return err + } else if fi.Size() == 0 { + return fmt.Errorf("zero db size") + } + fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size())) + + return nil +} + +func (cmd *CompactCommand) compact(dst, src *bolt.DB) error { + // commit regularly, or we'll run out of memory for large datasets if using one transaction. + var size int64 + tx, err := dst.Begin(true) + if err != nil { + return err + } + defer tx.Rollback() + + if err := cmd.walk(src, func(keys [][]byte, k, v []byte, seq uint64) error { + // On each key/value, check if we have exceeded tx size. + sz := int64(len(k) + len(v)) + if size+sz > cmd.TxMaxSize && cmd.TxMaxSize != 0 { + // Commit previous transaction. + if err := tx.Commit(); err != nil { + return err + } + + // Start new transaction. + tx, err = dst.Begin(true) + if err != nil { + return err + } + size = 0 + } + size += sz + + // Create bucket on the root transaction if this is the first level. + nk := len(keys) + if nk == 0 { + bkt, err := tx.CreateBucket(k) + if err != nil { + return err + } + if err := bkt.SetSequence(seq); err != nil { + return err + } + return nil + } + + // Create buckets on subsequent levels, if necessary. + b := tx.Bucket(keys[0]) + if nk > 1 { + for _, k := range keys[1:] { + b = b.Bucket(k) + } + } + + // If there is no value then this is a bucket call. + if v == nil { + bkt, err := b.CreateBucket(k) + if err != nil { + return err + } + if err := bkt.SetSequence(seq); err != nil { + return err + } + return nil + } + + // Otherwise treat it as a key/value pair. + return b.Put(k, v) + }); err != nil { + return err + } + + return tx.Commit() +} + +// walkFunc is the type of the function called for keys (buckets and "normal" +// values) discovered by Walk. keys is the list of keys to descend to the bucket +// owning the discovered key/value pair k/v. +type walkFunc func(keys [][]byte, k, v []byte, seq uint64) error + +// walk walks recursively the bolt database db, calling walkFn for each key it finds. +func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error { + return db.View(func(tx *bolt.Tx) error { + return tx.ForEach(func(name []byte, b *bolt.Bucket) error { + return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn) + }) + }) +} + +func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte, k, v []byte, seq uint64, fn walkFunc) error { + // Execute callback. + if err := fn(keypath, k, v, seq); err != nil { + return err + } + + // If this is not a bucket then stop. + if v != nil { + return nil + } + + // Iterate over each child key/value. + keypath = append(keypath, k) + return b.ForEach(func(k, v []byte) error { + if v == nil { + bkt := b.Bucket(k) + return cmd.walkBucket(bkt, keypath, k, nil, bkt.Sequence(), fn) + } + return cmd.walkBucket(b, keypath, k, v, b.Sequence(), fn) + }) +} + +// Usage returns the help message. +func (cmd *CompactCommand) Usage() string { + return strings.TrimLeft(` +usage: bolt compact [options] -o DST SRC + +Compact opens a database at SRC path and walks it recursively, copying keys +as they are found from all buckets, to a newly created database at DST path. + +The original database is left untouched. + +Additional options include: + + -tx-max-size NUM + Specifies the maximum size of individual transactions. + Defaults to 64KB. +`, "\n") +} diff --git a/accounts/vendor/github.com/boltdb/bolt/cursor.go b/accounts/vendor/github.com/boltdb/bolt/cursor.go new file mode 100644 index 000000000..1be9f35e3 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/cursor.go @@ -0,0 +1,400 @@ +package bolt + +import ( + "bytes" + "fmt" + "sort" +) + +// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order. +// Cursors see nested buckets with value == nil. +// Cursors can be obtained from a transaction and are valid as long as the transaction is open. +// +// Keys and values returned from the cursor are only valid for the life of the transaction. +// +// Changing data 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. +type Cursor struct { + bucket *Bucket + stack []elemRef +} + +// Bucket returns the bucket that this cursor was created from. +func (c *Cursor) Bucket() *Bucket { + return c.bucket +} + +// First moves the cursor to the first item in the bucket and returns its key and value. +// If the bucket is empty then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) First() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + c.stack = c.stack[:0] + p, n := c.bucket.pageNode(c.bucket.root) + c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) + c.first() + + // If we land on an empty page then move to the next value. + // https://github.com/boltdb/bolt/issues/450 + if c.stack[len(c.stack)-1].count() == 0 { + c.next() + } + + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v + +} + +// Last moves the cursor to the last item in the bucket and returns its key and value. +// If the bucket is empty then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Last() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + c.stack = c.stack[:0] + p, n := c.bucket.pageNode(c.bucket.root) + ref := elemRef{page: p, node: n} + ref.index = ref.count() - 1 + c.stack = append(c.stack, ref) + c.last() + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Next moves the cursor to the next item in the bucket and returns its key and value. +// If the cursor is at the end of the bucket then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Next() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + k, v, flags := c.next() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Prev moves the cursor to the previous item in the bucket and returns its key and value. +// If the cursor is at the beginning of the bucket then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Prev() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + + // Attempt to move back one element until we're successful. + // Move up the stack as we hit the beginning of each page in our stack. + for i := len(c.stack) - 1; i >= 0; i-- { + elem := &c.stack[i] + if elem.index > 0 { + elem.index-- + break + } + c.stack = c.stack[:i] + } + + // If we've hit the end then return nil. + if len(c.stack) == 0 { + return nil, nil + } + + // Move down the stack to find the last element of the last leaf under this branch. + c.last() + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Seek moves the cursor to a given key and returns it. +// If the key does not exist then the next key is used. If no keys +// follow, a nil key is returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { + k, v, flags := c.seek(seek) + + // If we ended up after the last element of a page then move to the next one. + if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { + k, v, flags = c.next() + } + + if k == nil { + return nil, nil + } else if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Delete removes the current key/value under the cursor from the bucket. +// Delete fails if current key/value is a bucket or if the transaction is not writable. +func (c *Cursor) Delete() error { + if c.bucket.tx.db == nil { + return ErrTxClosed + } else if !c.bucket.Writable() { + return ErrTxNotWritable + } + + key, _, flags := c.keyValue() + // Return an error if current value is a bucket. + if (flags & bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + c.node().del(key) + + return nil +} + +// seek moves the cursor to a given key and returns it. +// If the key does not exist then the next key is used. +func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { + _assert(c.bucket.tx.db != nil, "tx closed") + + // Start from root page/node and traverse to correct page. + c.stack = c.stack[:0] + c.search(seek, c.bucket.root) + ref := &c.stack[len(c.stack)-1] + + // If the cursor is pointing to the end of page/node then return nil. + if ref.index >= ref.count() { + return nil, nil, 0 + } + + // If this is a bucket then return a nil value. + return c.keyValue() +} + +// first moves the cursor to the first leaf element under the last page in the stack. +func (c *Cursor) first() { + for { + // Exit when we hit a leaf page. + var ref = &c.stack[len(c.stack)-1] + if ref.isLeaf() { + break + } + + // Keep adding pages pointing to the first element to the stack. + var pgid pgid + if ref.node != nil { + pgid = ref.node.inodes[ref.index].pgid + } else { + pgid = ref.page.branchPageElement(uint16(ref.index)).pgid + } + p, n := c.bucket.pageNode(pgid) + c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) + } +} + +// last moves the cursor to the last leaf element under the last page in the stack. +func (c *Cursor) last() { + for { + // Exit when we hit a leaf page. + ref := &c.stack[len(c.stack)-1] + if ref.isLeaf() { + break + } + + // Keep adding pages pointing to the last element in the stack. + var pgid pgid + if ref.node != nil { + pgid = ref.node.inodes[ref.index].pgid + } else { + pgid = ref.page.branchPageElement(uint16(ref.index)).pgid + } + p, n := c.bucket.pageNode(pgid) + + var nextRef = elemRef{page: p, node: n} + nextRef.index = nextRef.count() - 1 + c.stack = append(c.stack, nextRef) + } +} + +// next moves to the next leaf element and returns the key and value. +// If the cursor is at the last leaf element then it stays there and returns nil. +func (c *Cursor) next() (key []byte, value []byte, flags uint32) { + for { + // Attempt to move over one element until we're successful. + // Move up the stack as we hit the end of each page in our stack. + var i int + for i = len(c.stack) - 1; i >= 0; i-- { + elem := &c.stack[i] + if elem.index < elem.count()-1 { + elem.index++ + break + } + } + + // If we've hit the root page then stop and return. This will leave the + // cursor on the last element of the last page. + if i == -1 { + return nil, nil, 0 + } + + // Otherwise start from where we left off in the stack and find the + // first element of the first leaf page. + c.stack = c.stack[:i+1] + c.first() + + // If this is an empty page then restart and move back up the stack. + // https://github.com/boltdb/bolt/issues/450 + if c.stack[len(c.stack)-1].count() == 0 { + continue + } + + return c.keyValue() + } +} + +// search recursively performs a binary search against a given page/node until it finds a given key. +func (c *Cursor) search(key []byte, pgid pgid) { + p, n := c.bucket.pageNode(pgid) + if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 { + panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags)) + } + e := elemRef{page: p, node: n} + c.stack = append(c.stack, e) + + // If we're on a leaf page/node then find the specific node. + if e.isLeaf() { + c.nsearch(key) + return + } + + if n != nil { + c.searchNode(key, n) + return + } + c.searchPage(key, p) +} + +func (c *Cursor) searchNode(key []byte, n *node) { + var exact bool + index := sort.Search(len(n.inodes), func(i int) bool { + // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. + // sort.Search() finds the lowest index where f() != -1 but we need the highest index. + ret := bytes.Compare(n.inodes[i].key, key) + if ret == 0 { + exact = true + } + return ret != -1 + }) + if !exact && index > 0 { + index-- + } + c.stack[len(c.stack)-1].index = index + + // Recursively search to the next page. + c.search(key, n.inodes[index].pgid) +} + +func (c *Cursor) searchPage(key []byte, p *page) { + // Binary search for the correct range. + inodes := p.branchPageElements() + + var exact bool + index := sort.Search(int(p.count), func(i int) bool { + // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. + // sort.Search() finds the lowest index where f() != -1 but we need the highest index. + ret := bytes.Compare(inodes[i].key(), key) + if ret == 0 { + exact = true + } + return ret != -1 + }) + if !exact && index > 0 { + index-- + } + c.stack[len(c.stack)-1].index = index + + // Recursively search to the next page. + c.search(key, inodes[index].pgid) +} + +// nsearch searches the leaf node on the top of the stack for a key. +func (c *Cursor) nsearch(key []byte) { + e := &c.stack[len(c.stack)-1] + p, n := e.page, e.node + + // If we have a node then search its inodes. + if n != nil { + index := sort.Search(len(n.inodes), func(i int) bool { + return bytes.Compare(n.inodes[i].key, key) != -1 + }) + e.index = index + return + } + + // If we have a page then search its leaf elements. + inodes := p.leafPageElements() + index := sort.Search(int(p.count), func(i int) bool { + return bytes.Compare(inodes[i].key(), key) != -1 + }) + e.index = index +} + +// keyValue returns the key and value of the current leaf element. +func (c *Cursor) keyValue() ([]byte, []byte, uint32) { + ref := &c.stack[len(c.stack)-1] + if ref.count() == 0 || ref.index >= ref.count() { + return nil, nil, 0 + } + + // Retrieve value from node. + if ref.node != nil { + inode := &ref.node.inodes[ref.index] + return inode.key, inode.value, inode.flags + } + + // Or retrieve value from page. + elem := ref.page.leafPageElement(uint16(ref.index)) + return elem.key(), elem.value(), elem.flags +} + +// node returns the node that the cursor is currently positioned on. +func (c *Cursor) node() *node { + _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") + + // If the top of the stack is a leaf node then just return it. + if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { + return ref.node + } + + // Start from root and traverse down the hierarchy. + var n = c.stack[0].node + if n == nil { + n = c.bucket.node(c.stack[0].page.id, nil) + } + for _, ref := range c.stack[:len(c.stack)-1] { + _assert(!n.isLeaf, "expected branch node") + n = n.childAt(int(ref.index)) + } + _assert(n.isLeaf, "expected leaf node") + return n +} + +// elemRef represents a reference to an element on a given page/node. +type elemRef struct { + page *page + node *node + index int +} + +// isLeaf returns whether the ref is pointing at a leaf page/node. +func (r *elemRef) isLeaf() bool { + if r.node != nil { + return r.node.isLeaf + } + return (r.page.flags & leafPageFlag) != 0 +} + +// count returns the number of inodes or page elements. +func (r *elemRef) count() int { + if r.node != nil { + return len(r.node.inodes) + } + return int(r.page.count) +} diff --git a/accounts/vendor/github.com/boltdb/bolt/db.go b/accounts/vendor/github.com/boltdb/bolt/db.go new file mode 100644 index 000000000..48da0592d --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/db.go @@ -0,0 +1,1036 @@ +package bolt + +import ( + "errors" + "fmt" + "hash/fnv" + "log" + "os" + "runtime" + "runtime/debug" + "strings" + "sync" + "time" + "unsafe" +) + +// The largest step that can be taken when remapping the mmap. +const maxMmapStep = 1 << 30 // 1GB + +// The data file format version. +const version = 2 + +// Represents a marker value to indicate that a file is a Bolt DB. +const magic uint32 = 0xED0CDAED + +// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when +// syncing changes to a file. This is required as some operating systems, +// such as OpenBSD, do not have a unified buffer cache (UBC) and writes +// must be synchronized using the msync(2) syscall. +const IgnoreNoSync = runtime.GOOS == "openbsd" + +// Default values if not set in a DB instance. +const ( + DefaultMaxBatchSize int = 1000 + DefaultMaxBatchDelay = 10 * time.Millisecond + DefaultAllocSize = 16 * 1024 * 1024 +) + +// default page size for db is set to the OS page size. +var defaultPageSize = os.Getpagesize() + +// DB represents a collection of buckets persisted to a file on disk. +// All data access is performed through transactions which can be obtained through the DB. +// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. +type DB struct { + // When enabled, the database will perform a Check() after every commit. + // A panic is issued if the database is in an inconsistent state. This + // flag has a large performance impact so it should only be used for + // debugging purposes. + StrictMode bool + + // Setting the NoSync flag will cause the database to skip fsync() + // calls after each commit. This can be useful when bulk loading data + // into a database and you can restart the bulk load in the event of + // a system failure or database corruption. Do not set this flag for + // normal use. + // + // If the package global IgnoreNoSync constant is true, this value is + // ignored. See the comment on that constant for more details. + // + // THIS IS UNSAFE. PLEASE USE WITH CAUTION. + NoSync bool + + // When true, skips the truncate call when growing the database. + // Setting this to true is only safe on non-ext3/ext4 systems. + // Skipping truncation avoids preallocation of hard drive space and + // bypasses a truncate() and fsync() syscall on remapping. + // + // https://github.com/boltdb/bolt/issues/284 + NoGrowSync bool + + // If you want to read the entire database fast, you can set MmapFlag to + // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. + MmapFlags int + + // MaxBatchSize is the maximum size of a batch. Default value is + // copied from DefaultMaxBatchSize in Open. + // + // If <=0, disables batching. + // + // Do not change concurrently with calls to Batch. + MaxBatchSize int + + // MaxBatchDelay is the maximum delay before a batch starts. + // Default value is copied from DefaultMaxBatchDelay in Open. + // + // If <=0, effectively disables batching. + // + // Do not change concurrently with calls to Batch. + MaxBatchDelay time.Duration + + // AllocSize is the amount of space allocated when the database + // needs to create new pages. This is done to amortize the cost + // of truncate() and fsync() when growing the data file. + AllocSize int + + path string + file *os.File + lockfile *os.File // windows only + dataref []byte // mmap'ed readonly, write throws SEGV + data *[maxMapSize]byte + datasz int + filesz int // current on disk file size + meta0 *meta + meta1 *meta + pageSize int + opened bool + rwtx *Tx + txs []*Tx + freelist *freelist + stats Stats + + pagePool sync.Pool + + batchMu sync.Mutex + batch *batch + + rwlock sync.Mutex // Allows only one writer at a time. + metalock sync.Mutex // Protects meta page access. + mmaplock sync.RWMutex // Protects mmap access during remapping. + statlock sync.RWMutex // Protects stats access. + + ops struct { + writeAt func(b []byte, off int64) (n int, err error) + } + + // Read only mode. + // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. + readOnly bool +} + +// Path returns the path to currently open database file. +func (db *DB) Path() string { + return db.path +} + +// GoString returns the Go string representation of the database. +func (db *DB) GoString() string { + return fmt.Sprintf("bolt.DB{path:%q}", db.path) +} + +// String returns the string representation of the database. +func (db *DB) String() string { + return fmt.Sprintf("DB<%q>", db.path) +} + +// Open creates and opens a database at the given path. +// If the file does not exist then it will be created automatically. +// Passing in nil options will cause Bolt to open the database with the default options. +func Open(path string, mode os.FileMode, options *Options) (*DB, error) { + var db = &DB{opened: true} + + // Set default options if no options are provided. + if options == nil { + options = DefaultOptions + } + db.NoGrowSync = options.NoGrowSync + db.MmapFlags = options.MmapFlags + + // Set default values for later DB operations. + db.MaxBatchSize = DefaultMaxBatchSize + db.MaxBatchDelay = DefaultMaxBatchDelay + db.AllocSize = DefaultAllocSize + + flag := os.O_RDWR + if options.ReadOnly { + flag = os.O_RDONLY + db.readOnly = true + } + + // Open data file and separate sync handler for metadata writes. + db.path = path + var err error + if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { + _ = db.close() + return nil, err + } + + // Lock file so that other processes using Bolt in read-write mode cannot + // use the database at the same time. This would cause corruption since + // the two processes would write meta pages and free pages separately. + // The database file is locked exclusively (only one process can grab the lock) + // if !options.ReadOnly. + // The database file is locked using the shared lock (more than one process may + // hold a lock at the same time) otherwise (options.ReadOnly is set). + if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { + _ = db.close() + return nil, err + } + + // Default values for test hooks + db.ops.writeAt = db.file.WriteAt + + // Initialize the database if it doesn't exist. + if info, err := db.file.Stat(); err != nil { + return nil, err + } else if info.Size() == 0 { + // Initialize new files with meta pages. + if err := db.init(); err != nil { + return nil, err + } + } else { + // Read the first meta page to determine the page size. + var buf [0x1000]byte + if _, err := db.file.ReadAt(buf[:], 0); err == nil { + m := db.pageInBuffer(buf[:], 0).meta() + if err := m.validate(); err != nil { + // If we can't read the page size, we can assume it's the same + // as the OS -- since that's how the page size was chosen in the + // first place. + // + // If the first page is invalid and this OS uses a different + // page size than what the database was created with then we + // are out of luck and cannot access the database. + db.pageSize = os.Getpagesize() + } else { + db.pageSize = int(m.pageSize) + } + } + } + + // Initialize page pool. + db.pagePool = sync.Pool{ + New: func() interface{} { + return make([]byte, db.pageSize) + }, + } + + // Memory map the data file. + if err := db.mmap(options.InitialMmapSize); err != nil { + _ = db.close() + return nil, err + } + + // Read in the freelist. + db.freelist = newFreelist() + db.freelist.read(db.page(db.meta().freelist)) + + // Mark the database as opened and return. + return db, nil +} + +// mmap opens the underlying memory-mapped file and initializes the meta references. +// minsz is the minimum size that the new mmap can be. +func (db *DB) mmap(minsz int) error { + db.mmaplock.Lock() + defer db.mmaplock.Unlock() + + info, err := db.file.Stat() + if err != nil { + return fmt.Errorf("mmap stat error: %s", err) + } else if int(info.Size()) < db.pageSize*2 { + return fmt.Errorf("file size too small") + } + + // Ensure the size is at least the minimum size. + var size = int(info.Size()) + if size < minsz { + size = minsz + } + size, err = db.mmapSize(size) + if err != nil { + return err + } + + // Dereference all mmap references before unmapping. + if db.rwtx != nil { + db.rwtx.root.dereference() + } + + // Unmap existing data before continuing. + if err := db.munmap(); err != nil { + return err + } + + // Memory-map the data file as a byte slice. + if err := mmap(db, size); err != nil { + return err + } + + // Save references to the meta pages. + db.meta0 = db.page(0).meta() + db.meta1 = db.page(1).meta() + + // Validate the meta pages. We only return an error if both meta pages fail + // validation, since meta0 failing validation means that it wasn't saved + // properly -- but we can recover using meta1. And vice-versa. + err0 := db.meta0.validate() + err1 := db.meta1.validate() + if err0 != nil && err1 != nil { + return err0 + } + + return nil +} + +// munmap unmaps the data file from memory. +func (db *DB) munmap() error { + if err := munmap(db); err != nil { + return fmt.Errorf("unmap error: " + err.Error()) + } + return nil +} + +// mmapSize determines the appropriate size for the mmap given the current size +// of the database. The minimum size is 32KB and doubles until it reaches 1GB. +// Returns an error if the new mmap size is greater than the max allowed. +func (db *DB) mmapSize(size int) (int, error) { + // Double the size from 32KB until 1GB. + for i := uint(15); i <= 30; i++ { + if size <= 1< maxMapSize { + return 0, fmt.Errorf("mmap too large") + } + + // If larger than 1GB then grow by 1GB at a time. + sz := int64(size) + if remainder := sz % int64(maxMmapStep); remainder > 0 { + sz += int64(maxMmapStep) - remainder + } + + // Ensure that the mmap size is a multiple of the page size. + // This should always be true since we're incrementing in MBs. + pageSize := int64(db.pageSize) + if (sz % pageSize) != 0 { + sz = ((sz / pageSize) + 1) * pageSize + } + + // If we've exceeded the max size then only grow up to the max size. + if sz > maxMapSize { + sz = maxMapSize + } + + return int(sz), nil +} + +// init creates a new database file and initializes its meta pages. +func (db *DB) init() error { + // Set the page size to the OS page size. + db.pageSize = os.Getpagesize() + + // Create two meta pages on a buffer. + buf := make([]byte, db.pageSize*4) + for i := 0; i < 2; i++ { + p := db.pageInBuffer(buf[:], pgid(i)) + p.id = pgid(i) + p.flags = metaPageFlag + + // Initialize the meta page. + m := p.meta() + m.magic = magic + m.version = version + m.pageSize = uint32(db.pageSize) + m.freelist = 2 + m.root = bucket{root: 3} + m.pgid = 4 + m.txid = txid(i) + m.checksum = m.sum64() + } + + // Write an empty freelist at page 3. + p := db.pageInBuffer(buf[:], pgid(2)) + p.id = pgid(2) + p.flags = freelistPageFlag + p.count = 0 + + // Write an empty leaf page at page 4. + p = db.pageInBuffer(buf[:], pgid(3)) + p.id = pgid(3) + p.flags = leafPageFlag + p.count = 0 + + // Write the buffer to our data file. + if _, err := db.ops.writeAt(buf, 0); err != nil { + return err + } + if err := fdatasync(db); err != nil { + return err + } + + return nil +} + +// Close releases all database resources. +// All transactions must be closed before closing the database. +func (db *DB) Close() error { + db.rwlock.Lock() + defer db.rwlock.Unlock() + + db.metalock.Lock() + defer db.metalock.Unlock() + + db.mmaplock.RLock() + defer db.mmaplock.RUnlock() + + return db.close() +} + +func (db *DB) close() error { + if !db.opened { + return nil + } + + db.opened = false + + db.freelist = nil + + // Clear ops. + db.ops.writeAt = nil + + // Close the mmap. + if err := db.munmap(); err != nil { + return err + } + + // Close file handles. + if db.file != nil { + // No need to unlock read-only file. + if !db.readOnly { + // Unlock the file. + if err := funlock(db); err != nil { + log.Printf("bolt.Close(): funlock error: %s", err) + } + } + + // Close the file descriptor. + if err := db.file.Close(); err != nil { + return fmt.Errorf("db file close: %s", err) + } + db.file = nil + } + + db.path = "" + return nil +} + +// Begin starts a new transaction. +// Multiple read-only transactions can be used concurrently but only one +// write transaction can be used at a time. Starting multiple write transactions +// will cause the calls to block and be serialized until the current write +// transaction finishes. +// +// Transactions should not be dependent on one another. Opening a read +// transaction and a write transaction in the same goroutine can cause the +// writer to deadlock because the database periodically needs to re-mmap itself +// as it grows and it cannot do that while a read transaction is open. +// +// If a long running read transaction (for example, a snapshot transaction) is +// needed, you might want to set DB.InitialMmapSize to a large enough value +// to avoid potential blocking of write transaction. +// +// IMPORTANT: You must close read-only transactions after you are finished or +// else the database will not reclaim old pages. +func (db *DB) Begin(writable bool) (*Tx, error) { + if writable { + return db.beginRWTx() + } + return db.beginTx() +} + +func (db *DB) beginTx() (*Tx, error) { + // Lock the meta pages while we initialize the transaction. We obtain + // the meta lock before the mmap lock because that's the order that the + // write transaction will obtain them. + db.metalock.Lock() + + // Obtain a read-only lock on the mmap. When the mmap is remapped it will + // obtain a write lock so all transactions must finish before it can be + // remapped. + db.mmaplock.RLock() + + // Exit if the database is not open yet. + if !db.opened { + db.mmaplock.RUnlock() + db.metalock.Unlock() + return nil, ErrDatabaseNotOpen + } + + // Create a transaction associated with the database. + t := &Tx{} + t.init(db) + + // Keep track of transaction until it closes. + db.txs = append(db.txs, t) + n := len(db.txs) + + // Unlock the meta pages. + db.metalock.Unlock() + + // Update the transaction stats. + db.statlock.Lock() + db.stats.TxN++ + db.stats.OpenTxN = n + db.statlock.Unlock() + + return t, nil +} + +func (db *DB) beginRWTx() (*Tx, error) { + // If the database was opened with Options.ReadOnly, return an error. + if db.readOnly { + return nil, ErrDatabaseReadOnly + } + + // Obtain writer lock. This is released by the transaction when it closes. + // This enforces only one writer transaction at a time. + db.rwlock.Lock() + + // Once we have the writer lock then we can lock the meta pages so that + // we can set up the transaction. + db.metalock.Lock() + defer db.metalock.Unlock() + + // Exit if the database is not open yet. + if !db.opened { + db.rwlock.Unlock() + return nil, ErrDatabaseNotOpen + } + + // Create a transaction associated with the database. + t := &Tx{writable: true} + t.init(db) + db.rwtx = t + + // Free any pages associated with closed read-only transactions. + var minid txid = 0xFFFFFFFFFFFFFFFF + for _, t := range db.txs { + if t.meta.txid < minid { + minid = t.meta.txid + } + } + if minid > 0 { + db.freelist.release(minid - 1) + } + + return t, nil +} + +// removeTx removes a transaction from the database. +func (db *DB) removeTx(tx *Tx) { + // Release the read lock on the mmap. + db.mmaplock.RUnlock() + + // Use the meta lock to restrict access to the DB object. + db.metalock.Lock() + + // Remove the transaction. + for i, t := range db.txs { + if t == tx { + db.txs = append(db.txs[:i], db.txs[i+1:]...) + break + } + } + n := len(db.txs) + + // Unlock the meta pages. + db.metalock.Unlock() + + // Merge statistics. + db.statlock.Lock() + db.stats.OpenTxN = n + db.stats.TxStats.add(&tx.stats) + db.statlock.Unlock() +} + +// Update executes a function within the context of a read-write managed transaction. +// If no error is returned from the function then the transaction is committed. +// If an error is returned then the entire transaction is rolled back. +// Any error that is returned from the function or returned from the commit is +// returned from the Update() method. +// +// Attempting to manually commit or rollback within the function will cause a panic. +func (db *DB) Update(fn func(*Tx) error) error { + t, err := db.Begin(true) + if err != nil { + return err + } + + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + + // Mark as a managed tx so that the inner function cannot manually commit. + t.managed = true + + // If an error is returned from the function then rollback and return error. + err = fn(t) + t.managed = false + if err != nil { + _ = t.Rollback() + return err + } + + return t.Commit() +} + +// View executes a function within the context of a managed read-only transaction. +// Any error that is returned from the function is returned from the View() method. +// +// Attempting to manually rollback within the function will cause a panic. +func (db *DB) View(fn func(*Tx) error) error { + t, err := db.Begin(false) + if err != nil { + return err + } + + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + + // Mark as a managed tx so that the inner function cannot manually rollback. + t.managed = true + + // If an error is returned from the function then pass it through. + err = fn(t) + t.managed = false + if err != nil { + _ = t.Rollback() + return err + } + + if err := t.Rollback(); err != nil { + return err + } + + return nil +} + +// Batch calls fn as part of a batch. It behaves similar to Update, +// except: +// +// 1. concurrent Batch calls can be combined into a single Bolt +// transaction. +// +// 2. the function passed to Batch may be called multiple times, +// regardless of whether it returns error or not. +// +// This means that Batch function side effects must be idempotent and +// take permanent effect only after a successful return is seen in +// caller. +// +// The maximum batch size and delay can be adjusted with DB.MaxBatchSize +// and DB.MaxBatchDelay, respectively. +// +// Batch is only useful when there are multiple goroutines calling it. +func (db *DB) Batch(fn func(*Tx) error) error { + errCh := make(chan error, 1) + + db.batchMu.Lock() + if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { + // There is no existing batch, or the existing batch is full; start a new one. + db.batch = &batch{ + db: db, + } + db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) + } + db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) + if len(db.batch.calls) >= db.MaxBatchSize { + // wake up batch, it's ready to run + go db.batch.trigger() + } + db.batchMu.Unlock() + + err := <-errCh + if err == trySolo { + err = db.Update(fn) + } + return err +} + +type call struct { + fn func(*Tx) error + err chan<- error +} + +type batch struct { + db *DB + timer *time.Timer + start sync.Once + calls []call +} + +// trigger runs the batch if it hasn't already been run. +func (b *batch) trigger() { + b.start.Do(b.run) +} + +// run performs the transactions in the batch and communicates results +// back to DB.Batch. +func (b *batch) run() { + b.db.batchMu.Lock() + b.timer.Stop() + // Make sure no new work is added to this batch, but don't break + // other batches. + if b.db.batch == b { + b.db.batch = nil + } + b.db.batchMu.Unlock() + +retry: + for len(b.calls) > 0 { + var failIdx = -1 + err := b.db.Update(func(tx *Tx) error { + for i, c := range b.calls { + if err := safelyCall(c.fn, tx); err != nil { + failIdx = i + return err + } + } + return nil + }) + + if failIdx >= 0 { + // take the failing transaction out of the batch. it's + // safe to shorten b.calls here because db.batch no longer + // points to us, and we hold the mutex anyway. + c := b.calls[failIdx] + b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] + // tell the submitter re-run it solo, continue with the rest of the batch + c.err <- trySolo + continue retry + } + + // pass success, or bolt internal errors, to all callers + for _, c := range b.calls { + if c.err != nil { + c.err <- err + } + } + break retry + } +} + +// trySolo is a special sentinel error value used for signaling that a +// transaction function should be re-run. It should never be seen by +// callers. +var trySolo = errors.New("batch function returned an error and should be re-run solo") + +type panicked struct { + reason interface{} +} + +func (p panicked) Error() string { + if err, ok := p.reason.(error); ok { + return err.Error() + } + return fmt.Sprintf("panic: %v", p.reason) +} + +func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { + defer func() { + if p := recover(); p != nil { + err = panicked{p} + } + }() + return fn(tx) +} + +// Sync executes fdatasync() against the database file handle. +// +// This is not necessary under normal operation, however, if you use NoSync +// then it allows you to force the database file to sync against the disk. +func (db *DB) Sync() error { return fdatasync(db) } + +// Stats retrieves ongoing performance stats for the database. +// This is only updated when a transaction closes. +func (db *DB) Stats() Stats { + db.statlock.RLock() + defer db.statlock.RUnlock() + return db.stats +} + +// This is for internal access to the raw data bytes from the C cursor, use +// carefully, or not at all. +func (db *DB) Info() *Info { + return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} +} + +// page retrieves a page reference from the mmap based on the current page size. +func (db *DB) page(id pgid) *page { + pos := id * pgid(db.pageSize) + return (*page)(unsafe.Pointer(&db.data[pos])) +} + +// pageInBuffer retrieves a page reference from a given byte array based on the current page size. +func (db *DB) pageInBuffer(b []byte, id pgid) *page { + return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) +} + +// meta retrieves the current meta page reference. +func (db *DB) meta() *meta { + // We have to return the meta with the highest txid which doesn't fail + // validation. Otherwise, we can cause errors when in fact the database is + // in a consistent state. metaA is the one with the higher txid. + metaA := db.meta0 + metaB := db.meta1 + if db.meta1.txid > db.meta0.txid { + metaA = db.meta1 + metaB = db.meta0 + } + + // Use higher meta page if valid. Otherwise fallback to previous, if valid. + if err := metaA.validate(); err == nil { + return metaA + } else if err := metaB.validate(); err == nil { + return metaB + } + + // This should never be reached, because both meta1 and meta0 were validated + // on mmap() and we do fsync() on every write. + panic("bolt.DB.meta(): invalid meta pages") +} + +// allocate returns a contiguous block of memory starting at a given page. +func (db *DB) allocate(count int) (*page, error) { + // Allocate a temporary buffer for the page. + var buf []byte + if count == 1 { + buf = db.pagePool.Get().([]byte) + } else { + buf = make([]byte, count*db.pageSize) + } + p := (*page)(unsafe.Pointer(&buf[0])) + p.overflow = uint32(count - 1) + + // Use pages from the freelist if they are available. + if p.id = db.freelist.allocate(count); p.id != 0 { + return p, nil + } + + // Resize mmap() if we're at the end. + p.id = db.rwtx.meta.pgid + var minsz = int((p.id+pgid(count))+1) * db.pageSize + if minsz >= db.datasz { + if err := db.mmap(minsz); err != nil { + return nil, fmt.Errorf("mmap allocate error: %s", err) + } + } + + // Move the page id high water mark. + db.rwtx.meta.pgid += pgid(count) + + return p, nil +} + +// grow grows the size of the database to the given sz. +func (db *DB) grow(sz int) error { + // Ignore if the new size is less than available file size. + if sz <= db.filesz { + return nil + } + + // If the data is smaller than the alloc size then only allocate what's needed. + // Once it goes over the allocation size then allocate in chunks. + if db.datasz < db.AllocSize { + sz = db.datasz + } else { + sz += db.AllocSize + } + + // Truncate and fsync to ensure file size metadata is flushed. + // https://github.com/boltdb/bolt/issues/284 + if !db.NoGrowSync && !db.readOnly { + if runtime.GOOS != "windows" { + if err := db.file.Truncate(int64(sz)); err != nil { + return fmt.Errorf("file resize error: %s", err) + } + } + if err := db.file.Sync(); err != nil { + return fmt.Errorf("file sync error: %s", err) + } + } + + db.filesz = sz + return nil +} + +func (db *DB) IsReadOnly() bool { + return db.readOnly +} + +// Options represents the options that can be set when opening a database. +type Options struct { + // Timeout is the amount of time to wait to obtain a file lock. + // When set to zero it will wait indefinitely. This option is only + // available on Darwin and Linux. + Timeout time.Duration + + // Sets the DB.NoGrowSync flag before memory mapping the file. + NoGrowSync bool + + // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to + // grab a shared lock (UNIX). + ReadOnly bool + + // Sets the DB.MmapFlags flag before memory mapping the file. + MmapFlags int + + // InitialMmapSize is the initial mmap size of the database + // in bytes. Read transactions won't block write transaction + // if the InitialMmapSize is large enough to hold database mmap + // size. (See DB.Begin for more information) + // + // If <=0, the initial map size is 0. + // If initialMmapSize is smaller than the previous database size, + // it takes no effect. + InitialMmapSize int +} + +// DefaultOptions represent the options used if nil options are passed into Open(). +// No timeout is used which will cause Bolt to wait indefinitely for a lock. +var DefaultOptions = &Options{ + Timeout: 0, + NoGrowSync: false, +} + +// Stats represents statistics about the database. +type Stats struct { + // Freelist stats + FreePageN int // total number of free pages on the freelist + PendingPageN int // total number of pending pages on the freelist + FreeAlloc int // total bytes allocated in free pages + FreelistInuse int // total bytes used by the freelist + + // Transaction stats + TxN int // total number of started read transactions + OpenTxN int // number of currently open read transactions + + TxStats TxStats // global, ongoing stats. +} + +// Sub calculates and returns the difference between two sets of database stats. +// This is useful when obtaining stats at two different points and time and +// you need the performance counters that occurred within that time span. +func (s *Stats) Sub(other *Stats) Stats { + if other == nil { + return *s + } + var diff Stats + diff.FreePageN = s.FreePageN + diff.PendingPageN = s.PendingPageN + diff.FreeAlloc = s.FreeAlloc + diff.FreelistInuse = s.FreelistInuse + diff.TxN = s.TxN - other.TxN + diff.TxStats = s.TxStats.Sub(&other.TxStats) + return diff +} + +func (s *Stats) add(other *Stats) { + s.TxStats.add(&other.TxStats) +} + +type Info struct { + Data uintptr + PageSize int +} + +type meta struct { + magic uint32 + version uint32 + pageSize uint32 + flags uint32 + root bucket + freelist pgid + pgid pgid + txid txid + checksum uint64 +} + +// validate checks the marker bytes and version of the meta page to ensure it matches this binary. +func (m *meta) validate() error { + if m.magic != magic { + return ErrInvalid + } else if m.version != version { + return ErrVersionMismatch + } else if m.checksum != 0 && m.checksum != m.sum64() { + return ErrChecksum + } + return nil +} + +// copy copies one meta object to another. +func (m *meta) copy(dest *meta) { + *dest = *m +} + +// write writes the meta onto a page. +func (m *meta) write(p *page) { + if m.root.root >= m.pgid { + panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) + } else if m.freelist >= m.pgid { + panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) + } + + // Page id is either going to be 0 or 1 which we can determine by the transaction ID. + p.id = pgid(m.txid % 2) + p.flags |= metaPageFlag + + // Calculate the checksum. + m.checksum = m.sum64() + + m.copy(p.meta()) +} + +// generates the checksum for the meta. +func (m *meta) sum64() uint64 { + var h = fnv.New64a() + _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) + return h.Sum64() +} + +// _assert will panic with a given formatted message if the given condition is false. +func _assert(condition bool, msg string, v ...interface{}) { + if !condition { + panic(fmt.Sprintf("assertion failed: "+msg, v...)) + } +} + +func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } +func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } + +func printstack() { + stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n") + fmt.Fprintln(os.Stderr, stack) +} diff --git a/accounts/vendor/github.com/boltdb/bolt/doc.go b/accounts/vendor/github.com/boltdb/bolt/doc.go new file mode 100644 index 000000000..cc937845d --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/doc.go @@ -0,0 +1,44 @@ +/* +Package bolt implements a low-level key/value store in pure Go. It supports +fully serializable transactions, ACID semantics, and lock-free MVCC with +multiple readers and a single writer. Bolt can be used for projects that +want a simple data store without the need to add large dependencies such as +Postgres or MySQL. + +Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is +optimized for fast read access and does not require recovery in the event of a +system crash. Transactions which have not finished committing will simply be +rolled back in the event of a crash. + +The design of Bolt is based on Howard Chu's LMDB database project. + +Bolt currently works on Windows, Mac OS X, and Linux. + + +Basics + +There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is +a collection of buckets and is represented by a single file on disk. A bucket is +a collection of unique keys that are associated with values. + +Transactions provide either read-only or read-write access to the database. +Read-only transactions can retrieve key/value pairs and can use Cursors to +iterate over the dataset sequentially. Read-write transactions can create and +delete buckets and can insert and remove keys. Only one read-write transaction +is allowed at a time. + + +Caveats + +The database uses a read-only, memory-mapped data file to ensure that +applications cannot corrupt the database, however, this means that keys and +values returned from Bolt cannot be changed. Writing to a read-only byte slice +will cause Go to panic. + +Keys and values retrieved from the database are only valid for the life of +the transaction. When used outside the transaction, these byte slices can +point to different data or can point to invalid memory which will cause a panic. + + +*/ +package bolt diff --git a/accounts/vendor/github.com/boltdb/bolt/errors.go b/accounts/vendor/github.com/boltdb/bolt/errors.go new file mode 100644 index 000000000..a3620a3eb --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/errors.go @@ -0,0 +1,71 @@ +package bolt + +import "errors" + +// These errors can be returned when opening or calling methods on a DB. +var ( + // ErrDatabaseNotOpen is returned when a DB instance is accessed before it + // is opened or after it is closed. + ErrDatabaseNotOpen = errors.New("database not open") + + // ErrDatabaseOpen is returned when opening a database that is + // already open. + ErrDatabaseOpen = errors.New("database already open") + + // ErrInvalid is returned when both meta pages on a database are invalid. + // This typically occurs when a file is not a bolt database. + ErrInvalid = errors.New("invalid database") + + // ErrVersionMismatch is returned when the data file was created with a + // different version of Bolt. + ErrVersionMismatch = errors.New("version mismatch") + + // ErrChecksum is returned when either meta page checksum does not match. + ErrChecksum = errors.New("checksum error") + + // ErrTimeout is returned when a database cannot obtain an exclusive lock + // on the data file after the timeout passed to Open(). + ErrTimeout = errors.New("timeout") +) + +// These errors can occur when beginning or committing a Tx. +var ( + // ErrTxNotWritable is returned when performing a write operation on a + // read-only transaction. + ErrTxNotWritable = errors.New("tx not writable") + + // ErrTxClosed is returned when committing or rolling back a transaction + // that has already been committed or rolled back. + ErrTxClosed = errors.New("tx closed") + + // ErrDatabaseReadOnly is returned when a mutating transaction is started on a + // read-only database. + ErrDatabaseReadOnly = errors.New("database is in read-only mode") +) + +// These errors can occur when putting or deleting a value or a bucket. +var ( + // ErrBucketNotFound is returned when trying to access a bucket that has + // not been created yet. + ErrBucketNotFound = errors.New("bucket not found") + + // ErrBucketExists is returned when creating a bucket that already exists. + ErrBucketExists = errors.New("bucket already exists") + + // ErrBucketNameRequired is returned when creating a bucket with a blank name. + ErrBucketNameRequired = errors.New("bucket name required") + + // ErrKeyRequired is returned when inserting a zero-length key. + ErrKeyRequired = errors.New("key required") + + // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize. + ErrKeyTooLarge = errors.New("key too large") + + // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize. + ErrValueTooLarge = errors.New("value too large") + + // ErrIncompatibleValue is returned when trying create or delete a bucket + // on an existing non-bucket key or when trying to create or delete a + // non-bucket key on an existing bucket key. + ErrIncompatibleValue = errors.New("incompatible value") +) diff --git a/accounts/vendor/github.com/boltdb/bolt/freelist.go b/accounts/vendor/github.com/boltdb/bolt/freelist.go new file mode 100644 index 000000000..d32f6cd93 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/freelist.go @@ -0,0 +1,248 @@ +package bolt + +import ( + "fmt" + "sort" + "unsafe" +) + +// freelist represents a list of all pages that are available for allocation. +// It also tracks pages that have been freed but are still in use by open transactions. +type freelist struct { + ids []pgid // all free and available free page ids. + pending map[txid][]pgid // mapping of soon-to-be free page ids by tx. + cache map[pgid]bool // fast lookup of all free and pending page ids. +} + +// newFreelist returns an empty, initialized freelist. +func newFreelist() *freelist { + return &freelist{ + pending: make(map[txid][]pgid), + cache: make(map[pgid]bool), + } +} + +// size returns the size of the page after serialization. +func (f *freelist) size() int { + return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * f.count()) +} + +// count returns count of pages on the freelist +func (f *freelist) count() int { + return f.free_count() + f.pending_count() +} + +// free_count returns count of free pages +func (f *freelist) free_count() int { + return len(f.ids) +} + +// pending_count returns count of pending pages +func (f *freelist) pending_count() int { + var count int + for _, list := range f.pending { + count += len(list) + } + return count +} + +// all returns a list of all free ids and all pending ids in one sorted list. +func (f *freelist) all() []pgid { + m := make(pgids, 0) + + for _, list := range f.pending { + m = append(m, list...) + } + + sort.Sort(m) + return pgids(f.ids).merge(m) +} + +// allocate returns the starting page id of a contiguous list of pages of a given size. +// If a contiguous block cannot be found then 0 is returned. +func (f *freelist) allocate(n int) pgid { + if len(f.ids) == 0 { + return 0 + } + + var initial, previd pgid + for i, id := range f.ids { + if id <= 1 { + panic(fmt.Sprintf("invalid page allocation: %d", id)) + } + + // Reset initial page if this is not contiguous. + if previd == 0 || id-previd != 1 { + initial = id + } + + // If we found a contiguous block then remove it and return it. + if (id-initial)+1 == pgid(n) { + // If we're allocating off the beginning then take the fast path + // and just adjust the existing slice. This will use extra memory + // temporarily but the append() in free() will realloc the slice + // as is necessary. + if (i + 1) == n { + f.ids = f.ids[i+1:] + } else { + copy(f.ids[i-n+1:], f.ids[i+1:]) + f.ids = f.ids[:len(f.ids)-n] + } + + // Remove from the free cache. + for i := pgid(0); i < pgid(n); i++ { + delete(f.cache, initial+i) + } + + return initial + } + + previd = id + } + return 0 +} + +// free releases a page and its overflow for a given transaction id. +// If the page is already free then a panic will occur. +func (f *freelist) free(txid txid, p *page) { + if p.id <= 1 { + panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) + } + + // Free page and all its overflow pages. + var ids = f.pending[txid] + for id := p.id; id <= p.id+pgid(p.overflow); id++ { + // Verify that page is not already free. + if f.cache[id] { + panic(fmt.Sprintf("page %d already freed", id)) + } + + // Add to the freelist and cache. + ids = append(ids, id) + f.cache[id] = true + } + f.pending[txid] = ids +} + +// release moves all page ids for a transaction id (or older) to the freelist. +func (f *freelist) release(txid txid) { + m := make(pgids, 0) + for tid, ids := range f.pending { + if tid <= txid { + // Move transaction's pending pages to the available freelist. + // Don't remove from the cache since the page is still free. + m = append(m, ids...) + delete(f.pending, tid) + } + } + sort.Sort(m) + f.ids = pgids(f.ids).merge(m) +} + +// rollback removes the pages from a given pending tx. +func (f *freelist) rollback(txid txid) { + // Remove page ids from cache. + for _, id := range f.pending[txid] { + delete(f.cache, id) + } + + // Remove pages from pending list. + delete(f.pending, txid) +} + +// freed returns whether a given page is in the free list. +func (f *freelist) freed(pgid pgid) bool { + return f.cache[pgid] +} + +// read initializes the freelist from a freelist page. +func (f *freelist) read(p *page) { + // If the page.count is at the max uint16 value (64k) then it's considered + // an overflow and the size of the freelist is stored as the first element. + idx, count := 0, int(p.count) + if count == 0xFFFF { + idx = 1 + count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) + } + + // Copy the list of page ids from the freelist. + if count == 0 { + f.ids = nil + } else { + ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count] + f.ids = make([]pgid, len(ids)) + copy(f.ids, ids) + + // Make sure they're sorted. + sort.Sort(pgids(f.ids)) + } + + // Rebuild the page cache. + f.reindex() +} + +// write writes the page ids onto a freelist page. All free and pending ids are +// saved to disk since in the event of a program crash, all pending ids will +// become free. +func (f *freelist) write(p *page) error { + // Combine the old free pgids and pgids waiting on an open transaction. + ids := f.all() + + // Update the header flag. + p.flags |= freelistPageFlag + + // The page.count can only hold up to 64k elements so if we overflow that + // number then we handle it by putting the size in the first element. + if len(ids) == 0 { + p.count = uint16(len(ids)) + } else if len(ids) < 0xFFFF { + p.count = uint16(len(ids)) + copy(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:], ids) + } else { + p.count = 0xFFFF + ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(len(ids)) + copy(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:], ids) + } + + return nil +} + +// reload reads the freelist from a page and filters out pending items. +func (f *freelist) reload(p *page) { + f.read(p) + + // Build a cache of only pending pages. + pcache := make(map[pgid]bool) + for _, pendingIDs := range f.pending { + for _, pendingID := range pendingIDs { + pcache[pendingID] = true + } + } + + // Check each page in the freelist and build a new available freelist + // with any pages not in the pending lists. + var a []pgid + for _, id := range f.ids { + if !pcache[id] { + a = append(a, id) + } + } + f.ids = a + + // Once the available list is rebuilt then rebuild the free cache so that + // it includes the available and pending free pages. + f.reindex() +} + +// reindex rebuilds the free cache based on available and pending free lists. +func (f *freelist) reindex() { + f.cache = make(map[pgid]bool, len(f.ids)) + for _, id := range f.ids { + f.cache[id] = true + } + for _, pendingIDs := range f.pending { + for _, pendingID := range pendingIDs { + f.cache[pendingID] = true + } + } +} diff --git a/accounts/vendor/github.com/boltdb/bolt/node.go b/accounts/vendor/github.com/boltdb/bolt/node.go new file mode 100644 index 000000000..159318b22 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/node.go @@ -0,0 +1,604 @@ +package bolt + +import ( + "bytes" + "fmt" + "sort" + "unsafe" +) + +// node represents an in-memory, deserialized page. +type node struct { + bucket *Bucket + isLeaf bool + unbalanced bool + spilled bool + key []byte + pgid pgid + parent *node + children nodes + inodes inodes +} + +// root returns the top-level node this node is attached to. +func (n *node) root() *node { + if n.parent == nil { + return n + } + return n.parent.root() +} + +// minKeys returns the minimum number of inodes this node should have. +func (n *node) minKeys() int { + if n.isLeaf { + return 1 + } + return 2 +} + +// size returns the size of the node after serialization. +func (n *node) size() int { + sz, elsz := pageHeaderSize, n.pageElementSize() + for i := 0; i < len(n.inodes); i++ { + item := &n.inodes[i] + sz += elsz + len(item.key) + len(item.value) + } + return sz +} + +// sizeLessThan returns true if the node is less than a given size. +// This is an optimization to avoid calculating a large node when we only need +// to know if it fits inside a certain page size. +func (n *node) sizeLessThan(v int) bool { + sz, elsz := pageHeaderSize, n.pageElementSize() + for i := 0; i < len(n.inodes); i++ { + item := &n.inodes[i] + sz += elsz + len(item.key) + len(item.value) + if sz >= v { + return false + } + } + return true +} + +// pageElementSize returns the size of each page element based on the type of node. +func (n *node) pageElementSize() int { + if n.isLeaf { + return leafPageElementSize + } + return branchPageElementSize +} + +// childAt returns the child node at a given index. +func (n *node) childAt(index int) *node { + if n.isLeaf { + panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) + } + return n.bucket.node(n.inodes[index].pgid, n) +} + +// childIndex returns the index of a given child node. +func (n *node) childIndex(child *node) int { + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) + return index +} + +// numChildren returns the number of children. +func (n *node) numChildren() int { + return len(n.inodes) +} + +// nextSibling returns the next node with the same parent. +func (n *node) nextSibling() *node { + if n.parent == nil { + return nil + } + index := n.parent.childIndex(n) + if index >= n.parent.numChildren()-1 { + return nil + } + return n.parent.childAt(index + 1) +} + +// prevSibling returns the previous node with the same parent. +func (n *node) prevSibling() *node { + if n.parent == nil { + return nil + } + index := n.parent.childIndex(n) + if index == 0 { + return nil + } + return n.parent.childAt(index - 1) +} + +// put inserts a key/value. +func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) { + if pgid >= n.bucket.tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid)) + } else if len(oldKey) <= 0 { + panic("put: zero-length old key") + } else if len(newKey) <= 0 { + panic("put: zero-length new key") + } + + // Find insertion index. + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 }) + + // Add capacity and shift nodes if we don't have an exact match and need to insert. + exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey)) + if !exact { + n.inodes = append(n.inodes, inode{}) + copy(n.inodes[index+1:], n.inodes[index:]) + } + + inode := &n.inodes[index] + inode.flags = flags + inode.key = newKey + inode.value = value + inode.pgid = pgid + _assert(len(inode.key) > 0, "put: zero-length inode key") +} + +// del removes a key from the node. +func (n *node) del(key []byte) { + // Find index of key. + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) + + // Exit if the key isn't found. + if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { + return + } + + // Delete inode from the node. + n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) + + // Mark the node as needing rebalancing. + n.unbalanced = true +} + +// read initializes the node from a page. +func (n *node) read(p *page) { + n.pgid = p.id + n.isLeaf = ((p.flags & leafPageFlag) != 0) + n.inodes = make(inodes, int(p.count)) + + for i := 0; i < int(p.count); i++ { + inode := &n.inodes[i] + if n.isLeaf { + elem := p.leafPageElement(uint16(i)) + inode.flags = elem.flags + inode.key = elem.key() + inode.value = elem.value() + } else { + elem := p.branchPageElement(uint16(i)) + inode.pgid = elem.pgid + inode.key = elem.key() + } + _assert(len(inode.key) > 0, "read: zero-length inode key") + } + + // Save first key so we can find the node in the parent when we spill. + if len(n.inodes) > 0 { + n.key = n.inodes[0].key + _assert(len(n.key) > 0, "read: zero-length node key") + } else { + n.key = nil + } +} + +// write writes the items onto one or more pages. +func (n *node) write(p *page) { + // Initialize page. + if n.isLeaf { + p.flags |= leafPageFlag + } else { + p.flags |= branchPageFlag + } + + if len(n.inodes) >= 0xFFFF { + panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) + } + p.count = uint16(len(n.inodes)) + + // Stop here if there are no items to write. + if p.count == 0 { + return + } + + // Loop over each item and write it to the page. + b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] + for i, item := range n.inodes { + _assert(len(item.key) > 0, "write: zero-length inode key") + + // Write the page element. + if n.isLeaf { + elem := p.leafPageElement(uint16(i)) + elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) + elem.flags = item.flags + elem.ksize = uint32(len(item.key)) + elem.vsize = uint32(len(item.value)) + } else { + elem := p.branchPageElement(uint16(i)) + elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) + elem.ksize = uint32(len(item.key)) + elem.pgid = item.pgid + _assert(elem.pgid != p.id, "write: circular dependency occurred") + } + + // If the length of key+value is larger than the max allocation size + // then we need to reallocate the byte array pointer. + // + // See: https://github.com/boltdb/bolt/pull/335 + klen, vlen := len(item.key), len(item.value) + if len(b) < klen+vlen { + b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] + } + + // Write data for the element to the end of the page. + copy(b[0:], item.key) + b = b[klen:] + copy(b[0:], item.value) + b = b[vlen:] + } + + // DEBUG ONLY: n.dump() +} + +// split breaks up a node into multiple smaller nodes, if appropriate. +// This should only be called from the spill() function. +func (n *node) split(pageSize int) []*node { + var nodes []*node + + node := n + for { + // Split node into two. + a, b := node.splitTwo(pageSize) + nodes = append(nodes, a) + + // If we can't split then exit the loop. + if b == nil { + break + } + + // Set node to b so it gets split on the next iteration. + node = b + } + + return nodes +} + +// splitTwo breaks up a node into two smaller nodes, if appropriate. +// This should only be called from the split() function. +func (n *node) splitTwo(pageSize int) (*node, *node) { + // Ignore the split if the page doesn't have at least enough nodes for + // two pages or if the nodes can fit in a single page. + if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) { + return n, nil + } + + // Determine the threshold before starting a new node. + var fillPercent = n.bucket.FillPercent + if fillPercent < minFillPercent { + fillPercent = minFillPercent + } else if fillPercent > maxFillPercent { + fillPercent = maxFillPercent + } + threshold := int(float64(pageSize) * fillPercent) + + // Determine split position and sizes of the two pages. + splitIndex, _ := n.splitIndex(threshold) + + // Split node into two separate nodes. + // If there's no parent then we'll need to create one. + if n.parent == nil { + n.parent = &node{bucket: n.bucket, children: []*node{n}} + } + + // Create a new node and add it to the parent. + next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent} + n.parent.children = append(n.parent.children, next) + + // Split inodes across two nodes. + next.inodes = n.inodes[splitIndex:] + n.inodes = n.inodes[:splitIndex] + + // Update the statistics. + n.bucket.tx.stats.Split++ + + return n, next +} + +// splitIndex finds the position where a page will fill a given threshold. +// It returns the index as well as the size of the first page. +// This is only be called from split(). +func (n *node) splitIndex(threshold int) (index, sz int) { + sz = pageHeaderSize + + // Loop until we only have the minimum number of keys required for the second page. + for i := 0; i < len(n.inodes)-minKeysPerPage; i++ { + index = i + inode := n.inodes[i] + elsize := n.pageElementSize() + len(inode.key) + len(inode.value) + + // If we have at least the minimum number of keys and adding another + // node would put us over the threshold then exit and return. + if i >= minKeysPerPage && sz+elsize > threshold { + break + } + + // Add the element size to the total size. + sz += elsize + } + + return +} + +// spill writes the nodes to dirty pages and splits nodes as it goes. +// Returns an error if dirty pages cannot be allocated. +func (n *node) spill() error { + var tx = n.bucket.tx + if n.spilled { + return nil + } + + // Spill child nodes first. Child nodes can materialize sibling nodes in + // the case of split-merge so we cannot use a range loop. We have to check + // the children size on every loop iteration. + sort.Sort(n.children) + for i := 0; i < len(n.children); i++ { + if err := n.children[i].spill(); err != nil { + return err + } + } + + // We no longer need the child list because it's only used for spill tracking. + n.children = nil + + // Split nodes into appropriate sizes. The first node will always be n. + var nodes = n.split(tx.db.pageSize) + for _, node := range nodes { + // Add node's page to the freelist if it's not new. + if node.pgid > 0 { + tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) + node.pgid = 0 + } + + // Allocate contiguous space for the node. + p, err := tx.allocate((node.size() / tx.db.pageSize) + 1) + if err != nil { + return err + } + + // Write the node. + if p.id >= tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) + } + node.pgid = p.id + node.write(p) + node.spilled = true + + // Insert into parent inodes. + if node.parent != nil { + var key = node.key + if key == nil { + key = node.inodes[0].key + } + + node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) + node.key = node.inodes[0].key + _assert(len(node.key) > 0, "spill: zero-length node key") + } + + // Update the statistics. + tx.stats.Spill++ + } + + // If the root node split and created a new root then we need to spill that + // as well. We'll clear out the children to make sure it doesn't try to respill. + if n.parent != nil && n.parent.pgid == 0 { + n.children = nil + return n.parent.spill() + } + + return nil +} + +// rebalance attempts to combine the node with sibling nodes if the node fill +// size is below a threshold or if there are not enough keys. +func (n *node) rebalance() { + if !n.unbalanced { + return + } + n.unbalanced = false + + // Update statistics. + n.bucket.tx.stats.Rebalance++ + + // Ignore if node is above threshold (25%) and has enough keys. + var threshold = n.bucket.tx.db.pageSize / 4 + if n.size() > threshold && len(n.inodes) > n.minKeys() { + return + } + + // Root node has special handling. + if n.parent == nil { + // If root node is a branch and only has one node then collapse it. + if !n.isLeaf && len(n.inodes) == 1 { + // Move root's child up. + child := n.bucket.node(n.inodes[0].pgid, n) + n.isLeaf = child.isLeaf + n.inodes = child.inodes[:] + n.children = child.children + + // Reparent all child nodes being moved. + for _, inode := range n.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent = n + } + } + + // Remove old child. + child.parent = nil + delete(n.bucket.nodes, child.pgid) + child.free() + } + + return + } + + // If node has no keys then just remove it. + if n.numChildren() == 0 { + n.parent.del(n.key) + n.parent.removeChild(n) + delete(n.bucket.nodes, n.pgid) + n.free() + n.parent.rebalance() + return + } + + _assert(n.parent.numChildren() > 1, "parent must have at least 2 children") + + // Destination node is right sibling if idx == 0, otherwise left sibling. + var target *node + var useNextSibling = (n.parent.childIndex(n) == 0) + if useNextSibling { + target = n.nextSibling() + } else { + target = n.prevSibling() + } + + // If both this node and the target node are too small then merge them. + if useNextSibling { + // Reparent all child nodes being moved. + for _, inode := range target.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent.removeChild(child) + child.parent = n + child.parent.children = append(child.parent.children, child) + } + } + + // Copy over inodes from target and remove target. + n.inodes = append(n.inodes, target.inodes...) + n.parent.del(target.key) + n.parent.removeChild(target) + delete(n.bucket.nodes, target.pgid) + target.free() + } else { + // Reparent all child nodes being moved. + for _, inode := range n.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent.removeChild(child) + child.parent = target + child.parent.children = append(child.parent.children, child) + } + } + + // Copy over inodes to target and remove node. + target.inodes = append(target.inodes, n.inodes...) + n.parent.del(n.key) + n.parent.removeChild(n) + delete(n.bucket.nodes, n.pgid) + n.free() + } + + // Either this node or the target node was deleted from the parent so rebalance it. + n.parent.rebalance() +} + +// removes a node from the list of in-memory children. +// This does not affect the inodes. +func (n *node) removeChild(target *node) { + for i, child := range n.children { + if child == target { + n.children = append(n.children[:i], n.children[i+1:]...) + return + } + } +} + +// dereference causes the node to copy all its inode key/value references to heap memory. +// This is required when the mmap is reallocated so inodes are not pointing to stale data. +func (n *node) dereference() { + if n.key != nil { + key := make([]byte, len(n.key)) + copy(key, n.key) + n.key = key + _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node") + } + + for i := range n.inodes { + inode := &n.inodes[i] + + key := make([]byte, len(inode.key)) + copy(key, inode.key) + inode.key = key + _assert(len(inode.key) > 0, "dereference: zero-length inode key") + + value := make([]byte, len(inode.value)) + copy(value, inode.value) + inode.value = value + } + + // Recursively dereference children. + for _, child := range n.children { + child.dereference() + } + + // Update statistics. + n.bucket.tx.stats.NodeDeref++ +} + +// free adds the node's underlying page to the freelist. +func (n *node) free() { + if n.pgid != 0 { + n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) + n.pgid = 0 + } +} + +// dump writes the contents of the node to STDERR for debugging purposes. +/* +func (n *node) dump() { + // Write node header. + var typ = "branch" + if n.isLeaf { + typ = "leaf" + } + warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes)) + + // Write out abbreviated version of each item. + for _, item := range n.inodes { + if n.isLeaf { + if item.flags&bucketLeafFlag != 0 { + bucket := (*bucket)(unsafe.Pointer(&item.value[0])) + warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root) + } else { + warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4)) + } + } else { + warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid) + } + } + warn("") +} +*/ + +type nodes []*node + +func (s nodes) Len() int { return len(s) } +func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 } + +// inode represents an internal node inside of a node. +// It can be used to point to elements in a page or point +// to an element which hasn't been added to a page yet. +type inode struct { + flags uint32 + pgid pgid + key []byte + value []byte +} + +type inodes []inode diff --git a/accounts/vendor/github.com/boltdb/bolt/page.go b/accounts/vendor/github.com/boltdb/bolt/page.go new file mode 100644 index 000000000..7651a6bf7 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/page.go @@ -0,0 +1,178 @@ +package bolt + +import ( + "fmt" + "os" + "sort" + "unsafe" +) + +const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr)) + +const minKeysPerPage = 2 + +const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{})) +const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{})) + +const ( + branchPageFlag = 0x01 + leafPageFlag = 0x02 + metaPageFlag = 0x04 + freelistPageFlag = 0x10 +) + +const ( + bucketLeafFlag = 0x01 +) + +type pgid uint64 + +type page struct { + id pgid + flags uint16 + count uint16 + overflow uint32 + ptr uintptr +} + +// typ returns a human readable page type string used for debugging. +func (p *page) typ() string { + if (p.flags & branchPageFlag) != 0 { + return "branch" + } else if (p.flags & leafPageFlag) != 0 { + return "leaf" + } else if (p.flags & metaPageFlag) != 0 { + return "meta" + } else if (p.flags & freelistPageFlag) != 0 { + return "freelist" + } + return fmt.Sprintf("unknown<%02x>", p.flags) +} + +// meta returns a pointer to the metadata section of the page. +func (p *page) meta() *meta { + return (*meta)(unsafe.Pointer(&p.ptr)) +} + +// leafPageElement retrieves the leaf node by index +func (p *page) leafPageElement(index uint16) *leafPageElement { + n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] + return n +} + +// leafPageElements retrieves a list of leaf nodes. +func (p *page) leafPageElements() []leafPageElement { + if p.count == 0 { + return nil + } + return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] +} + +// branchPageElement retrieves the branch node by index +func (p *page) branchPageElement(index uint16) *branchPageElement { + return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] +} + +// branchPageElements retrieves a list of branch nodes. +func (p *page) branchPageElements() []branchPageElement { + if p.count == 0 { + return nil + } + return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] +} + +// dump writes n bytes of the page to STDERR as hex output. +func (p *page) hexdump(n int) { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] + fmt.Fprintf(os.Stderr, "%x\n", buf) +} + +type pages []*page + +func (s pages) Len() int { return len(s) } +func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s pages) Less(i, j int) bool { return s[i].id < s[j].id } + +// branchPageElement represents a node on a branch page. +type branchPageElement struct { + pos uint32 + ksize uint32 + pgid pgid +} + +// key returns a byte slice of the node key. +func (n *branchPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize] +} + +// leafPageElement represents a node on a leaf page. +type leafPageElement struct { + flags uint32 + pos uint32 + ksize uint32 + vsize uint32 +} + +// key returns a byte slice of the node key. +func (n *leafPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize] +} + +// value returns a byte slice of the node value. +func (n *leafPageElement) value() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] +} + +// PageInfo represents human readable information about a page. +type PageInfo struct { + ID int + Type string + Count int + OverflowCount int +} + +type pgids []pgid + +func (s pgids) Len() int { return len(s) } +func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s pgids) Less(i, j int) bool { return s[i] < s[j] } + +// merge returns the sorted union of a and b. +func (a pgids) merge(b pgids) pgids { + // Return the opposite slice if one is nil. + if len(a) == 0 { + return b + } else if len(b) == 0 { + return a + } + + // Create a list to hold all elements from both lists. + merged := make(pgids, 0, len(a)+len(b)) + + // Assign lead to the slice with a lower starting value, follow to the higher value. + lead, follow := a, b + if b[0] < a[0] { + lead, follow = b, a + } + + // Continue while there are elements in the lead. + for len(lead) > 0 { + // Merge largest prefix of lead that is ahead of follow[0]. + n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) + merged = append(merged, lead[:n]...) + if n >= len(lead) { + break + } + + // Swap lead and follow. + lead, follow = follow, lead[n:] + } + + // Append what's left in follow. + merged = append(merged, follow...) + + return merged +} diff --git a/accounts/vendor/github.com/boltdb/bolt/tx.go b/accounts/vendor/github.com/boltdb/bolt/tx.go new file mode 100644 index 000000000..1cfb4cde8 --- /dev/null +++ b/accounts/vendor/github.com/boltdb/bolt/tx.go @@ -0,0 +1,682 @@ +package bolt + +import ( + "fmt" + "io" + "os" + "sort" + "strings" + "time" + "unsafe" +) + +// txid represents the internal transaction identifier. +type txid uint64 + +// Tx represents a read-only or read/write transaction on the database. +// Read-only transactions can be used for retrieving values for keys and creating cursors. +// Read/write transactions can create and remove buckets and create and remove keys. +// +// IMPORTANT: You must commit or rollback transactions when you are done with +// them. Pages can not be reclaimed by the writer until no more transactions +// are using them. A long running read transaction can cause the database to +// quickly grow. +type Tx struct { + writable bool + managed bool + db *DB + meta *meta + root Bucket + pages map[pgid]*page + stats TxStats + commitHandlers []func() + + // WriteFlag specifies the flag for write-related methods like WriteTo(). + // Tx opens the database file with the specified flag to copy the data. + // + // By default, the flag is unset, which works well for mostly in-memory + // workloads. For databases that are much larger than available RAM, + // set the flag to syscall.O_DIRECT to avoid trashing the page cache. + WriteFlag int +} + +// init initializes the transaction. +func (tx *Tx) init(db *DB) { + tx.db = db + tx.pages = nil + + // Copy the meta page since it can be changed by the writer. + tx.meta = &meta{} + db.meta().copy(tx.meta) + + // Copy over the root bucket. + tx.root = newBucket(tx) + tx.root.bucket = &bucket{} + *tx.root.bucket = tx.meta.root + + // Increment the transaction id and add a page cache for writable transactions. + if tx.writable { + tx.pages = make(map[pgid]*page) + tx.meta.txid += txid(1) + } +} + +// ID returns the transaction id. +func (tx *Tx) ID() int { + return int(tx.meta.txid) +} + +// DB returns a reference to the database that created the transaction. +func (tx *Tx) DB() *DB { + return tx.db +} + +// Size returns current database size in bytes as seen by this transaction. +func (tx *Tx) Size() int64 { + return int64(tx.meta.pgid) * int64(tx.db.pageSize) +} + +// Writable returns whether the transaction can perform write operations. +func (tx *Tx) Writable() bool { + return tx.writable +} + +// Cursor creates a cursor associated with the root bucket. +// All items in the cursor will return a nil value because all root bucket keys point to buckets. +// The cursor is only valid as long as the transaction is open. +// Do not use a cursor after the transaction is closed. +func (tx *Tx) Cursor() *Cursor { + return tx.root.Cursor() +} + +// Stats retrieves a copy of the current transaction statistics. +func (tx *Tx) Stats() TxStats { + return tx.stats +} + +// Bucket retrieves a bucket by name. +// Returns nil if the bucket does not exist. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) Bucket(name []byte) *Bucket { + return tx.root.Bucket(name) +} + +// CreateBucket creates a new bucket. +// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { + return tx.root.CreateBucket(name) +} + +// CreateBucketIfNotExists creates a new bucket if it doesn't already exist. +// Returns an error if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { + return tx.root.CreateBucketIfNotExists(name) +} + +// DeleteBucket deletes a bucket. +// Returns an error if the bucket cannot be found or if the key represents a non-bucket value. +func (tx *Tx) DeleteBucket(name []byte) error { + return tx.root.DeleteBucket(name) +} + +// ForEach executes a function for each bucket in the root. +// If the provided function returns an error then the iteration is stopped and +// the error is returned to the caller. +func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { + return tx.root.ForEach(func(k, v []byte) error { + if err := fn(k, tx.root.Bucket(k)); err != nil { + return err + } + return nil + }) +} + +// OnCommit adds a handler function to be executed after the transaction successfully commits. +func (tx *Tx) OnCommit(fn func()) { + tx.commitHandlers = append(tx.commitHandlers, fn) +} + +// Commit writes all changes to disk and updates the meta page. +// Returns an error if a disk write error occurs, or if Commit is +// called on a read-only transaction. +func (tx *Tx) Commit() error { + _assert(!tx.managed, "managed tx commit not allowed") + if tx.db == nil { + return ErrTxClosed + } else if !tx.writable { + return ErrTxNotWritable + } + + // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. + + // Rebalance nodes which have had deletions. + var startTime = time.Now() + tx.root.rebalance() + if tx.stats.Rebalance > 0 { + tx.stats.RebalanceTime += time.Since(startTime) + } + + // spill data onto dirty pages. + startTime = time.Now() + if err := tx.root.spill(); err != nil { + tx.rollback() + return err + } + tx.stats.SpillTime += time.Since(startTime) + + // Free the old root bucket. + tx.meta.root.root = tx.root.root + + opgid := tx.meta.pgid + + // Free the freelist and allocate new pages for it. This will overestimate + // the size of the freelist but not underestimate the size (which would be bad). + tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) + p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) + if err != nil { + tx.rollback() + return err + } + if err := tx.db.freelist.write(p); err != nil { + tx.rollback() + return err + } + tx.meta.freelist = p.id + + // If the high water mark has moved up then attempt to grow the database. + if tx.meta.pgid > opgid { + if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { + tx.rollback() + return err + } + } + + // Write dirty pages to disk. + startTime = time.Now() + if err := tx.write(); err != nil { + tx.rollback() + return err + } + + // If strict mode is enabled then perform a consistency check. + // Only the first consistency error is reported in the panic. + if tx.db.StrictMode { + ch := tx.Check() + var errs []string + for { + err, ok := <-ch + if !ok { + break + } + errs = append(errs, err.Error()) + } + if len(errs) > 0 { + panic("check fail: " + strings.Join(errs, "\n")) + } + } + + // Write meta to disk. + if err := tx.writeMeta(); err != nil { + tx.rollback() + return err + } + tx.stats.WriteTime += time.Since(startTime) + + // Finalize the transaction. + tx.close() + + // Execute commit handlers now that the locks have been removed. + for _, fn := range tx.commitHandlers { + fn() + } + + return nil +} + +// Rollback closes the transaction and ignores all previous updates. Read-only +// transactions must be rolled back and not committed. +func (tx *Tx) Rollback() error { + _assert(!tx.managed, "managed tx rollback not allowed") + if tx.db == nil { + return ErrTxClosed + } + tx.rollback() + return nil +} + +func (tx *Tx) rollback() { + if tx.db == nil { + return + } + if tx.writable { + tx.db.freelist.rollback(tx.meta.txid) + tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist)) + } + tx.close() +} + +func (tx *Tx) close() { + if tx.db == nil { + return + } + if tx.writable { + // Grab freelist stats. + var freelistFreeN = tx.db.freelist.free_count() + var freelistPendingN = tx.db.freelist.pending_count() + var freelistAlloc = tx.db.freelist.size() + + // Remove transaction ref & writer lock. + tx.db.rwtx = nil + tx.db.rwlock.Unlock() + + // Merge statistics. + tx.db.statlock.Lock() + tx.db.stats.FreePageN = freelistFreeN + tx.db.stats.PendingPageN = freelistPendingN + tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize + tx.db.stats.FreelistInuse = freelistAlloc + tx.db.stats.TxStats.add(&tx.stats) + tx.db.statlock.Unlock() + } else { + tx.db.removeTx(tx) + } + + // Clear all references. + tx.db = nil + tx.meta = nil + tx.root = Bucket{tx: tx} + tx.pages = nil +} + +// Copy writes the entire database to a writer. +// This function exists for backwards compatibility. Use WriteTo() instead. +func (tx *Tx) Copy(w io.Writer) error { + _, err := tx.WriteTo(w) + return err +} + +// WriteTo writes the entire database to a writer. +// If err == nil then exactly tx.Size() bytes will be written into the writer. +func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) { + // Attempt to open reader with WriteFlag + f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0) + if err != nil { + return 0, err + } + defer func() { _ = f.Close() }() + + // Generate a meta page. We use the same page data for both meta pages. + buf := make([]byte, tx.db.pageSize) + page := (*page)(unsafe.Pointer(&buf[0])) + page.flags = metaPageFlag + *page.meta() = *tx.meta + + // Write meta 0. + page.id = 0 + page.meta().checksum = page.meta().sum64() + nn, err := w.Write(buf) + n += int64(nn) + if err != nil { + return n, fmt.Errorf("meta 0 copy: %s", err) + } + + // Write meta 1 with a lower transaction id. + page.id = 1 + page.meta().txid -= 1 + page.meta().checksum = page.meta().sum64() + nn, err = w.Write(buf) + n += int64(nn) + if err != nil { + return n, fmt.Errorf("meta 1 copy: %s", err) + } + + // Move past the meta pages in the file. + if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil { + return n, fmt.Errorf("seek: %s", err) + } + + // Copy data pages. + wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2)) + n += wn + if err != nil { + return n, err + } + + return n, f.Close() +} + +// CopyFile copies the entire database to file at the given path. +// A reader transaction is maintained during the copy so it is safe to continue +// using the database while a copy is in progress. +func (tx *Tx) CopyFile(path string, mode os.FileMode) error { + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) + if err != nil { + return err + } + + err = tx.Copy(f) + if err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// Check performs several consistency checks on the database for this transaction. +// An error is returned if any inconsistency is found. +// +// It can be safely run concurrently on a writable transaction. However, this +// incurs a high cost for large databases and databases with a lot of subbuckets +// because of caching. This overhead can be removed if running on a read-only +// transaction, however, it is not safe to execute other writer transactions at +// the same time. +func (tx *Tx) Check() <-chan error { + ch := make(chan error) + go tx.check(ch) + return ch +} + +func (tx *Tx) check(ch chan error) { + // Check if any pages are double freed. + freed := make(map[pgid]bool) + for _, id := range tx.db.freelist.all() { + if freed[id] { + ch <- fmt.Errorf("page %d: already freed", id) + } + freed[id] = true + } + + // Track every reachable page. + reachable := make(map[pgid]*page) + reachable[0] = tx.page(0) // meta0 + reachable[1] = tx.page(1) // meta1 + for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ { + reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist) + } + + // Recursively check buckets. + tx.checkBucket(&tx.root, reachable, freed, ch) + + // Ensure all pages below high water mark are either reachable or freed. + for i := pgid(0); i < tx.meta.pgid; i++ { + _, isReachable := reachable[i] + if !isReachable && !freed[i] { + ch <- fmt.Errorf("page %d: unreachable unfreed", int(i)) + } + } + + // Close the channel to signal completion. + close(ch) +} + +func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) { + // Ignore inline buckets. + if b.root == 0 { + return + } + + // Check every page used by this bucket. + b.tx.forEachPage(b.root, 0, func(p *page, _ int) { + if p.id > tx.meta.pgid { + ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid)) + } + + // Ensure each page is only referenced once. + for i := pgid(0); i <= pgid(p.overflow); i++ { + var id = p.id + i + if _, ok := reachable[id]; ok { + ch <- fmt.Errorf("page %d: multiple references", int(id)) + } + reachable[id] = p + } + + // We should only encounter un-freed leaf and branch pages. + if freed[p.id] { + ch <- fmt.Errorf("page %d: reachable freed", int(p.id)) + } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 { + ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ()) + } + }) + + // Check each bucket within this bucket. + _ = b.ForEach(func(k, v []byte) error { + if child := b.Bucket(k); child != nil { + tx.checkBucket(child, reachable, freed, ch) + } + return nil + }) +} + +// allocate returns a contiguous block of memory starting at a given page. +func (tx *Tx) allocate(count int) (*page, error) { + p, err := tx.db.allocate(count) + if err != nil { + return nil, err + } + + // Save to our page cache. + tx.pages[p.id] = p + + // Update statistics. + tx.stats.PageCount++ + tx.stats.PageAlloc += count * tx.db.pageSize + + return p, nil +} + +// write writes any dirty pages to disk. +func (tx *Tx) write() error { + // Sort pages by id. + pages := make(pages, 0, len(tx.pages)) + for _, p := range tx.pages { + pages = append(pages, p) + } + // Clear out page cache early. + tx.pages = make(map[pgid]*page) + sort.Sort(pages) + + // Write pages to disk in order. + for _, p := range pages { + size := (int(p.overflow) + 1) * tx.db.pageSize + offset := int64(p.id) * int64(tx.db.pageSize) + + // Write out page in "max allocation" sized chunks. + ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) + for { + // Limit our write to our max allocation size. + sz := size + if sz > maxAllocSize-1 { + sz = maxAllocSize - 1 + } + + // Write chunk to disk. + buf := ptr[:sz] + if _, err := tx.db.ops.writeAt(buf, offset); err != nil { + return err + } + + // Update statistics. + tx.stats.Write++ + + // Exit inner for loop if we've written all the chunks. + size -= sz + if size == 0 { + break + } + + // Otherwise move offset forward and move pointer to next chunk. + offset += int64(sz) + ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) + } + } + + // Ignore file sync if flag is set on DB. + if !tx.db.NoSync || IgnoreNoSync { + if err := fdatasync(tx.db); err != nil { + return err + } + } + + // Put small pages back to page pool. + for _, p := range pages { + // Ignore page sizes over 1 page. + // These are allocated using make() instead of the page pool. + if int(p.overflow) != 0 { + continue + } + + buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] + + // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 + for i := range buf { + buf[i] = 0 + } + tx.db.pagePool.Put(buf) + } + + return nil +} + +// writeMeta writes the meta to the disk. +func (tx *Tx) writeMeta() error { + // Create a temporary buffer for the meta page. + buf := make([]byte, tx.db.pageSize) + p := tx.db.pageInBuffer(buf, 0) + tx.meta.write(p) + + // Write the meta page to file. + if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { + return err + } + if !tx.db.NoSync || IgnoreNoSync { + if err := fdatasync(tx.db); err != nil { + return err + } + } + + // Update statistics. + tx.stats.Write++ + + return nil +} + +// page returns a reference to the page with a given id. +// If page has been written to then a temporary buffered page is returned. +func (tx *Tx) page(id pgid) *page { + // Check the dirty pages first. + if tx.pages != nil { + if p, ok := tx.pages[id]; ok { + return p + } + } + + // Otherwise return directly from the mmap. + return tx.db.page(id) +} + +// forEachPage iterates over every page within a given page and executes a function. +func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { + p := tx.page(pgid) + + // Execute function. + fn(p, depth) + + // Recursively loop over children. + if (p.flags & branchPageFlag) != 0 { + for i := 0; i < int(p.count); i++ { + elem := p.branchPageElement(uint16(i)) + tx.forEachPage(elem.pgid, depth+1, fn) + } + } +} + +// Page returns page information for a given page number. +// This is only safe for concurrent use when used by a writable transaction. +func (tx *Tx) Page(id int) (*PageInfo, error) { + if tx.db == nil { + return nil, ErrTxClosed + } else if pgid(id) >= tx.meta.pgid { + return nil, nil + } + + // Build the page info. + p := tx.db.page(pgid(id)) + info := &PageInfo{ + ID: id, + Count: int(p.count), + OverflowCount: int(p.overflow), + } + + // Determine the type (or if it's free). + if tx.db.freelist.freed(pgid(id)) { + info.Type = "free" + } else { + info.Type = p.typ() + } + + return info, nil +} + +// TxStats represents statistics about the actions performed by the transaction. +type TxStats struct { + // Page statistics. + PageCount int // number of page allocations + PageAlloc int // total bytes allocated + + // Cursor statistics. + CursorCount int // number of cursors created + + // Node statistics + NodeCount int // number of node allocations + NodeDeref int // number of node dereferences + + // Rebalance statistics. + Rebalance int // number of node rebalances + RebalanceTime time.Duration // total time spent rebalancing + + // Split/Spill statistics. + Split int // number of nodes split + Spill int // number of nodes spilled + SpillTime time.Duration // total time spent spilling + + // Write statistics. + Write int // number of writes performed + WriteTime time.Duration // total time spent writing to disk +} + +func (s *TxStats) add(other *TxStats) { + s.PageCount += other.PageCount + s.PageAlloc += other.PageAlloc + s.CursorCount += other.CursorCount + s.NodeCount += other.NodeCount + s.NodeDeref += other.NodeDeref + s.Rebalance += other.Rebalance + s.RebalanceTime += other.RebalanceTime + s.Split += other.Split + s.Spill += other.Spill + s.SpillTime += other.SpillTime + s.Write += other.Write + s.WriteTime += other.WriteTime +} + +// Sub calculates and returns the difference between two sets of transaction stats. +// This is useful when obtaining stats at two different points and time and +// you need the performance counters that occurred within that time span. +func (s *TxStats) Sub(other *TxStats) TxStats { + var diff TxStats + diff.PageCount = s.PageCount - other.PageCount + diff.PageAlloc = s.PageAlloc - other.PageAlloc + diff.CursorCount = s.CursorCount - other.CursorCount + diff.NodeCount = s.NodeCount - other.NodeCount + diff.NodeDeref = s.NodeDeref - other.NodeDeref + diff.Rebalance = s.Rebalance - other.Rebalance + diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime + diff.Split = s.Split - other.Split + diff.Spill = s.Spill - other.Spill + diff.SpillTime = s.SpillTime - other.SpillTime + diff.Write = s.Write - other.Write + diff.WriteTime = s.WriteTime - other.WriteTime + return diff +} diff --git a/accounts/vendor/github.com/mailru/easyjson/LICENSE b/accounts/vendor/github.com/mailru/easyjson/LICENSE new file mode 100644 index 000000000..fbff658f7 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2016 Mail.Ru Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/accounts/vendor/github.com/mailru/easyjson/Makefile b/accounts/vendor/github.com/mailru/easyjson/Makefile new file mode 100644 index 000000000..8e720a084 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/Makefile @@ -0,0 +1,54 @@ +PKG=github.com/mailru/easyjson +GOPATH:=$(PWD)/.root:$(GOPATH) +export GOPATH + +all: test + +.root/src/$(PKG): + mkdir -p $@ + for i in $$PWD/* ; do ln -s $$i $@/`basename $$i` ; done + +root: .root/src/$(PKG) + +clean: + rm -rf .root + +build: + go build -i -o .root/bin/easyjson $(PKG)/easyjson + +generate: root build + .root/bin/easyjson -stubs \ + .root/src/$(PKG)/tests/snake.go \ + .root/src/$(PKG)/tests/data.go \ + .root/src/$(PKG)/tests/omitempty.go \ + .root/src/$(PKG)/tests/nothing.go \ + .root/src/$(PKG)/tests/named_type.go + + .root/bin/easyjson -all .root/src/$(PKG)/tests/data.go + .root/bin/easyjson -all .root/src/$(PKG)/tests/nothing.go + .root/bin/easyjson -all .root/src/$(PKG)/tests/errors.go + .root/bin/easyjson -snake_case .root/src/$(PKG)/tests/snake.go + .root/bin/easyjson -omit_empty .root/src/$(PKG)/tests/omitempty.go + .root/bin/easyjson -build_tags=use_easyjson .root/src/$(PKG)/benchmark/data.go + .root/bin/easyjson .root/src/$(PKG)/tests/nested_easy.go + .root/bin/easyjson .root/src/$(PKG)/tests/named_type.go + +test: generate root + go test \ + $(PKG)/tests \ + $(PKG)/jlexer \ + $(PKG)/gen \ + $(PKG)/buffer + go test -benchmem -tags use_easyjson -bench . $(PKG)/benchmark + golint -set_exit_status .root/src/$(PKG)/tests/*_easyjson.go + +bench-other: generate root + @go test -benchmem -bench . $(PKG)/benchmark + @go test -benchmem -tags use_ffjson -bench . $(PKG)/benchmark + @go test -benchmem -tags use_codec -bench . $(PKG)/benchmark + +bench-python: + benchmark/ujson.sh + + +.PHONY: root clean generate test build diff --git a/accounts/vendor/github.com/mailru/easyjson/README.md b/accounts/vendor/github.com/mailru/easyjson/README.md new file mode 100644 index 000000000..9cb88455f --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/README.md @@ -0,0 +1,329 @@ +# easyjson [![Build Status](https://travis-ci.org/mailru/easyjson.svg?branch=master)](https://travis-ci.org/mailru/easyjson) [![Go Report Card](https://goreportcard.com/badge/github.com/mailru/easyjson)](https://goreportcard.com/report/github.com/mailru/easyjson) + +Package easyjson provides a fast and easy way to marshal/unmarshal Go structs +to/from JSON without the use of reflection. In performance tests, easyjson +outperforms the standard `encoding/json` package by a factor of 4-5x, and other +JSON encoding packages by a factor of 2-3x. + +easyjson aims to keep generated Go code simple enough so that it can be easily +optimized or fixed. Another goal is to provide users with the ability to +customize the generated code by providing options not available with the +standard `encoding/json` package, such as generating "snake_case" names or +enabling `omitempty` behavior by default. + +## Usage +```sh +# install +go get -u github.com/mailru/easyjson/... + +# run +easyjson -all .go +``` + +The above will generate `_easyjson.go` containing the appropriate marshaler and +unmarshaler funcs for all structs contained in `.go`. + +Please note that easyjson requires a full Go build environment and the `GOPATH` +environment variable to be set. This is because easyjson code generation +invokes `go run` on a temporary file (an approach to code generation borrowed +from [ffjson](https://github.com/pquerna/ffjson)). + +## Options +```txt +Usage of easyjson: + -all + generate marshaler/unmarshalers for all structs in a file + -build_tags string + build tags to add to generated file + -leave_temps + do not delete temporary files + -no_std_marshalers + don't generate MarshalJSON/UnmarshalJSON funcs + -noformat + do not run 'gofmt -w' on output file + -omit_empty + omit empty fields by default + -output_filename string + specify the filename of the output + -pkg + process the whole package instead of just the given file + -snake_case + use snake_case names instead of CamelCase by default + -stubs + only generate stubs for marshaler/unmarshaler funcs +``` + +Using `-all` will generate marshalers/unmarshalers for all Go structs in the +file. If `-all` is not provided, then only those structs whose preceeding +comment starts with `easyjson:json` will have marshalers/unmarshalers +generated. For example: + +```go +//easyjson:json +struct A{} +``` + +Additional option notes: + +* `-snake_case` tells easyjson to generate snake\_case field names by default + (unless overridden by a field tag). The CamelCase to snake\_case conversion + algorithm should work in most cases (ie, HTTPVersion will be converted to + "http_version"). + +* `-build_tags` will add the specified build tags to generated Go sources. + +## Generated Marshaler/Unmarshaler Funcs + +For Go struct types, easyjson generates the funcs `MarshalEasyJSON` / +`UnmarshalEasyJSON` for marshaling/unmarshaling JSON. In turn, these satisify +the `easyjson.Marshaler` and `easyjson.Unmarshaler` interfaces and when used in +conjunction with `easyjson.Marshal` / `easyjson.Unmarshal` avoid unnecessary +reflection / type assertions during marshaling/unmarshaling to/from JSON for Go +structs. + +easyjson also generates `MarshalJSON` and `UnmarshalJSON` funcs for Go struct +types compatible with the standard `json.Marshaler` and `json.Unmarshaler` +interfaces. Please be aware that using the standard `json.Marshal` / +`json.Unmarshal` for marshaling/unmarshaling will incur a significant +performance penalty when compared to using `easyjson.Marshal` / +`easyjson.Unmarshal`. + +Additionally, easyjson exposes utility funcs that use the `MarshalEasyJSON` and +`UnmarshalEasyJSON` for marshaling/unmarshaling to and from standard readers +and writers. For example, easyjson provides `easyjson.MarshalToHTTPResponseWriter` +which marshals to the standard `http.ResponseWriter`. Please see the [GoDoc +listing](https://godoc.org/github.com/mailru/easyjson) for the full listing of +utility funcs that are available. + +## Controlling easyjson Marshaling and Unmarshaling Behavior + +Go types can provide their own `MarshalEasyJSON` and `UnmarshalEasyJSON` funcs +that satisify the `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces. +These will be used by `easyjson.Marshal` and `easyjson.Unmarshal` when defined +for a Go type. + +Go types can also satisify the `easyjson.Optional` interface, which allows the +type to define its own `omitempty` logic. + +## Type Wrappers + +easyjson provides additional type wrappers defined in the `easyjson/opt` +package. These wrap the standard Go primitives and in turn satisify the +easyjson interfaces. + +The `easyjson/opt` type wrappers are useful when needing to distinguish between +a missing value and/or when needing to specifying a default value. Type +wrappers allow easyjson to avoid additional pointers and heap allocations and +can significantly increase performance when used properly. + +## Memory Pooling + +easyjson uses a buffer pool that allocates data in increasing chunks from 128 +to 32768 bytes. Chunks of 512 bytes and larger will be reused with the help of +`sync.Pool`. The maximum size of a chunk is bounded to reduce redundant memory +allocation and to allow larger reusable buffers. + +easyjson's custom allocation buffer pool is defined in the `easyjson/buffer` +package, and the default behavior pool behavior can be modified (if necessary) +through a call to `buffer.Init()` prior to any marshaling or unmarshaling. +Please see the [GoDoc listing](https://godoc.org/github.com/mailru/easyjson/buffer) +for more information. + +## Issues, Notes, and Limitations + +* easyjson is still early in its development. As such, there are likely to be + bugs and missing features when compared to `encoding/json`. In the case of a + missing feature or bug, please create a GitHub issue. Pull requests are + welcome! + +* Unlike `encoding/json`, object keys are case-sensitive. Case-insensitive + matching is not currently provided due to the significant performance hit + when doing case-insensitive key matching. In the future, case-insensitive + object key matching may be provided via an option to the generator. + +* easyjson makes use of `unsafe`, which simplifies the code and + provides significant performance benefits by allowing no-copy + conversion from `[]byte` to `string`. That said, `unsafe` is used + only when unmarshaling and parsing JSON, and any `unsafe` operations + / memory allocations done will be safely deallocated by + easyjson. Set the build tag `easyjson_nounsafe` to compile it + without `unsafe`. + +* easyjson is compatible with Google App Engine. The `appengine` build + tag (set by App Engine's environment) will automatically disable the + use of `unsafe`, which is not allowed in App Engine's Standard + Environment. Note that the use with App Engine is still experimental. + +* Floats are formatted using the default precision from Go's `strconv` package. + As such, easyjson will not correctly handle high precision floats when + marshaling/unmarshaling JSON. Note, however, that there are very few/limited + uses where this behavior is not sufficient for general use. That said, a + different package may be needed if precise marshaling/unmarshaling of high + precision floats to/from JSON is required. + +* While unmarshaling, the JSON parser does the minimal amount of work needed to + skip over unmatching parens, and as such full validation is not done for the + entire JSON value being unmarshaled/parsed. + +* Currently there is no true streaming support for encoding/decoding as + typically for many uses/protocols the final, marshaled length of the JSON + needs to be known prior to sending the data. Currently this is not possible + with easyjson's architecture. + +## Benchmarks + +Most benchmarks were done using the example +[13kB example JSON](https://dev.twitter.com/rest/reference/get/search/tweets) +(9k after eliminating whitespace). This example is similar to real-world data, +is well-structured, and contains a healthy variety of different types, making +it ideal for JSON serialization benchmarks. + +Note: + +* For small request benchmarks, an 80 byte portion of the above example was + used. + +* For large request marshaling benchmarks, a struct containing 50 regular + samples was used, making a ~500kB output JSON. + +* Benchmarks are showing the results of easyjson's default behaviour, + which makes use of `unsafe`. + +Benchmarks are available in the repository and can be run by invoking `make`. + +### easyjson vs. encoding/json + +easyjson is roughly 5-6 times faster than the standard `encoding/json` for +unmarshaling, and 3-4 times faster for non-concurrent marshaling. Concurrent +marshaling is 6-7x faster if marshaling to a writer. + +### easyjson vs. ffjson + +easyjson uses the same approach for JSON marshaling as +[ffjson](https://github.com/pquerna/ffjson), but takes a significantly +different approach to lexing and parsing JSON during unmarshaling. This means +easyjson is roughly 2-3x faster for unmarshaling and 1.5-2x faster for +non-concurrent unmarshaling. + +As of this writing, `ffjson` seems to have issues when used concurrently: +specifically, large request pooling hurts `ffjson`'s performance and causes +scalability issues. These issues with `ffjson` can likely be fixed, but as of +writing remain outstanding/known issues with `ffjson`. + +easyjson and `ffjson` have similar performance for small requests, however +easyjson outperforms `ffjson` by roughly 2-5x times for large requests when +used with a writer. + +### easyjson vs. go/codec + +[go/codec](https://github.com/ugorji/go) provides +compile-time helpers for JSON generation. In this case, helpers do not work +like marshalers as they are encoding-independent. + +easyjson is generally 2x faster than `go/codec` for non-concurrent benchmarks +and about 3x faster for concurrent encoding (without marshaling to a writer). + +In an attempt to measure marshaling performance of `go/codec` (as opposed to +allocations/memcpy/writer interface invocations), a benchmark was done with +resetting length of a byte slice rather than resetting the whole slice to nil. +However, the optimization in this exact form may not be applicable in practice, +since the memory is not freed between marshaling operations. + +### easyjson vs 'ujson' python module + +[ujson](https://github.com/esnme/ultrajson) is using C code for parsing, so it +is interesting to see how plain golang compares to that. It is imporant to note +that the resulting object for python is slower to access, since the library +parses JSON object into dictionaries. + +easyjson is slightly faster for unmarshaling and 2-3x faster than `ujson` for +marshaling. + +### Benchmark Results + +`ffjson` results are from February 4th, 2016, using the latest `ffjson` and go1.6. +`go/codec` results are from March 4th, 2016, using the latest `go/codec` and go1.6. + +#### Unmarshaling + +| lib | json size | MB/s | allocs/op | B/op | +|:---------|:----------|-----:|----------:|------:| +| standard | regular | 22 | 218 | 10229 | +| standard | small | 9.7 | 14 | 720 | +| | | | | | +| easyjson | regular | 125 | 128 | 9794 | +| easyjson | small | 67 | 3 | 128 | +| | | | | | +| ffjson | regular | 66 | 141 | 9985 | +| ffjson | small | 17.6 | 10 | 488 | +| | | | | | +| codec | regular | 55 | 434 | 19299 | +| codec | small | 29 | 7 | 336 | +| | | | | | +| ujson | regular | 103 | N/A | N/A | + +#### Marshaling, one goroutine. + +| lib | json size | MB/s | allocs/op | B/op | +|:----------|:----------|-----:|----------:|------:| +| standard | regular | 75 | 9 | 23256 | +| standard | small | 32 | 3 | 328 | +| standard | large | 80 | 17 | 1.2M | +| | | | | | +| easyjson | regular | 213 | 9 | 10260 | +| easyjson* | regular | 263 | 8 | 742 | +| easyjson | small | 125 | 1 | 128 | +| easyjson | large | 212 | 33 | 490k | +| easyjson* | large | 262 | 25 | 2879 | +| | | | | | +| ffjson | regular | 122 | 153 | 21340 | +| ffjson** | regular | 146 | 152 | 4897 | +| ffjson | small | 36 | 5 | 384 | +| ffjson** | small | 64 | 4 | 128 | +| ffjson | large | 134 | 7317 | 818k | +| ffjson** | large | 125 | 7320 | 827k | +| | | | | | +| codec | regular | 80 | 17 | 33601 | +| codec*** | regular | 108 | 9 | 1153 | +| codec | small | 42 | 3 | 304 | +| codec*** | small | 56 | 1 | 48 | +| codec | large | 73 | 483 | 2.5M | +| codec*** | large | 103 | 451 | 66007 | +| | | | | | +| ujson | regular | 92 | N/A | N/A | + +\* marshaling to a writer, +\*\* using `ffjson.Pool()`, +\*\*\* reusing output slice instead of resetting it to nil + +#### Marshaling, concurrent. + +| lib | json size | MB/s | allocs/op | B/op | +|:----------|:----------|-----:|----------:|------:| +| standard | regular | 252 | 9 | 23257 | +| standard | small | 124 | 3 | 328 | +| standard | large | 289 | 17 | 1.2M | +| | | | | | +| easyjson | regular | 792 | 9 | 10597 | +| easyjson* | regular | 1748 | 8 | 779 | +| easyjson | small | 333 | 1 | 128 | +| easyjson | large | 718 | 36 | 548k | +| easyjson* | large | 2134 | 25 | 4957 | +| | | | | | +| ffjson | regular | 301 | 153 | 21629 | +| ffjson** | regular | 707 | 152 | 5148 | +| ffjson | small | 62 | 5 | 384 | +| ffjson** | small | 282 | 4 | 128 | +| ffjson | large | 438 | 7330 | 1.0M | +| ffjson** | large | 131 | 7319 | 820k | +| | | | | | +| codec | regular | 183 | 17 | 33603 | +| codec*** | regular | 671 | 9 | 1157 | +| codec | small | 147 | 3 | 304 | +| codec*** | small | 299 | 1 | 48 | +| codec | large | 190 | 483 | 2.5M | +| codec*** | large | 752 | 451 | 77574 | + +\* marshaling to a writer, +\*\* using `ffjson.Pool()`, +\*\*\* reusing output slice instead of resetting it to nil diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/codec_test.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/codec_test.go new file mode 100644 index 000000000..5c77072ee --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/codec_test.go @@ -0,0 +1,279 @@ +// +build use_codec + +package benchmark + +import ( + "testing" + + "github.com/ugorji/go/codec" +) + +func BenchmarkCodec_Unmarshal_M(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + dec := codec.NewDecoderBytes(nil, h) + + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + dec.ResetBytes(largeStructText) + if err := dec.Decode(&s); err != nil { + b.Error(err) + } + } +} + +func BenchmarkCodec_Unmarshal_S(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + dec := codec.NewDecoderBytes(nil, h) + + b.SetBytes(int64(len(smallStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + dec.ResetBytes(smallStructText) + if err := dec.Decode(&s); err != nil { + b.Error(err) + } + } +} + +func BenchmarkCodec_Marshal_S(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var out []byte + + var h codec.Handle = new(codec.JsonHandle) + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var out []byte + + var h codec.Handle = new(codec.JsonHandle) + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + b.SetBytes(l) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/data.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/data.go new file mode 100644 index 000000000..d2c689cd6 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/data.go @@ -0,0 +1,148 @@ +// Package benchmark provides a simple benchmark for easyjson against default serialization and ffjson. +// The data example is taken from https://dev.twitter.com/rest/reference/get/search/tweets +package benchmark + +import ( + "io/ioutil" +) + +var largeStructText, _ = ioutil.ReadFile("example.json") +var xlStructData XLStruct + +func init() { + for i := 0; i < 50; i++ { + xlStructData.Data = append(xlStructData.Data, largeStructData) + } +} + +var smallStructText = []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`) +var smallStructData = Entities{ + Hashtags: []Hashtag{{Indices: []int{5, 10}, Text: "some-text"}}, + Urls: []*string{}, + UserMentions: []*string{}, +} + +type SearchMetadata struct { + CompletedIn float64 `json:"completed_in"` + Count int `json:"count"` + MaxID int `json:"max_id"` + MaxIDStr string `json:"max_id_str"` + NextResults string `json:"next_results"` + Query string `json:"query"` + RefreshURL string `json:"refresh_url"` + SinceID int `json:"since_id"` + SinceIDStr string `json:"since_id_str"` +} + +type Hashtag struct { + Indices []int `json:"indices"` + Text string `json:"text"` +} + +//easyjson:json +type Entities struct { + Hashtags []Hashtag `json:"hashtags"` + Urls []*string `json:"urls"` + UserMentions []*string `json:"user_mentions"` +} + +type UserEntityDescription struct { + Urls []*string `json:"urls"` +} + +type URL struct { + ExpandedURL *string `json:"expanded_url"` + Indices []int `json:"indices"` + URL string `json:"url"` +} + +type UserEntityURL struct { + Urls []URL `json:"urls"` +} + +type UserEntities struct { + Description UserEntityDescription `json:"description"` + URL UserEntityURL `json:"url"` +} + +type User struct { + ContributorsEnabled bool `json:"contributors_enabled"` + CreatedAt string `json:"created_at"` + DefaultProfile bool `json:"default_profile"` + DefaultProfileImage bool `json:"default_profile_image"` + Description string `json:"description"` + Entities UserEntities `json:"entities"` + FavouritesCount int `json:"favourites_count"` + FollowRequestSent *string `json:"follow_request_sent"` + FollowersCount int `json:"followers_count"` + Following *string `json:"following"` + FriendsCount int `json:"friends_count"` + GeoEnabled bool `json:"geo_enabled"` + ID int `json:"id"` + IDStr string `json:"id_str"` + IsTranslator bool `json:"is_translator"` + Lang string `json:"lang"` + ListedCount int `json:"listed_count"` + Location string `json:"location"` + Name string `json:"name"` + Notifications *string `json:"notifications"` + ProfileBackgroundColor string `json:"profile_background_color"` + ProfileBackgroundImageURL string `json:"profile_background_image_url"` + ProfileBackgroundImageURLHTTPS string `json:"profile_background_image_url_https"` + ProfileBackgroundTile bool `json:"profile_background_tile"` + ProfileImageURL string `json:"profile_image_url"` + ProfileImageURLHTTPS string `json:"profile_image_url_https"` + ProfileLinkColor string `json:"profile_link_color"` + ProfileSidebarBorderColor string `json:"profile_sidebar_border_color"` + ProfileSidebarFillColor string `json:"profile_sidebar_fill_color"` + ProfileTextColor string `json:"profile_text_color"` + ProfileUseBackgroundImage bool `json:"profile_use_background_image"` + Protected bool `json:"protected"` + ScreenName string `json:"screen_name"` + ShowAllInlineMedia bool `json:"show_all_inline_media"` + StatusesCount int `json:"statuses_count"` + TimeZone string `json:"time_zone"` + URL *string `json:"url"` + UtcOffset int `json:"utc_offset"` + Verified bool `json:"verified"` +} + +type StatusMetadata struct { + IsoLanguageCode string `json:"iso_language_code"` + ResultType string `json:"result_type"` +} + +type Status struct { + Contributors *string `json:"contributors"` + Coordinates *string `json:"coordinates"` + CreatedAt string `json:"created_at"` + Entities Entities `json:"entities"` + Favorited bool `json:"favorited"` + Geo *string `json:"geo"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + InReplyToScreenName *string `json:"in_reply_to_screen_name"` + InReplyToStatusID *string `json:"in_reply_to_status_id"` + InReplyToStatusIDStr *string `json:"in_reply_to_status_id_str"` + InReplyToUserID *string `json:"in_reply_to_user_id"` + InReplyToUserIDStr *string `json:"in_reply_to_user_id_str"` + Metadata StatusMetadata `json:"metadata"` + Place *string `json:"place"` + RetweetCount int `json:"retweet_count"` + Retweeted bool `json:"retweeted"` + Source string `json:"source"` + Text string `json:"text"` + Truncated bool `json:"truncated"` + User User `json:"user"` +} + +//easyjson:json +type LargeStruct struct { + SearchMetadata SearchMetadata `json:"search_metadata"` + Statuses []Status `json:"statuses"` +} + +//easyjson:json +type XLStruct struct { + Data []LargeStruct +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/data_codec.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_codec.go new file mode 100644 index 000000000..d2d83fac6 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_codec.go @@ -0,0 +1,6914 @@ +//+build use_codec +//+build !easyjson_nounsafe +//+build !appengine + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package benchmark + +import ( + "errors" + "fmt" + "reflect" + "runtime" + "unsafe" + + codec1978 "github.com/ugorji/go/codec" +) + +const ( + // ----- content types ---- + codecSelferC_UTF89225 = 1 + codecSelferC_RAW9225 = 0 + // ----- value types used ---- + codecSelferValueTypeArray9225 = 10 + codecSelferValueTypeMap9225 = 9 + // ----- containerStateValues ---- + codecSelfer_containerMapKey9225 = 2 + codecSelfer_containerMapValue9225 = 3 + codecSelfer_containerMapEnd9225 = 4 + codecSelfer_containerArrayElem9225 = 6 + codecSelfer_containerArrayEnd9225 = 7 +) + +var ( + codecSelferBitsize9225 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr9225 = errors.New(`only encoded map or array can be decoded into a struct`) +) + +type codecSelferUnsafeString9225 struct { + Data uintptr + Len int +} + +type codecSelfer9225 struct{} + +func init() { + if codec1978.GenVersion != 5 { + _, file, _, _ := runtime.Caller(0) + err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", + 5, codec1978.GenVersion, file) + panic(err) + } + if false { // reference the types, but skip this branch at build/run time + var v0 unsafe.Pointer + _ = v0 + } +} + +func (x *SearchMetadata) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [9]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(9) + } else { + yynn2 = 9 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeFloat64(float64(x.CompletedIn)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("completed_in")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeFloat64(float64(x.CompletedIn)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeInt(int64(x.Count)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeInt(int64(x.Count)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.MaxID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("max_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeInt(int64(x.MaxID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.MaxIDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("max_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.MaxIDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.NextResults)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("next_results")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.NextResults)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Query)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("query")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Query)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.RefreshURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("refresh_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.RefreshURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeInt(int64(x.SinceID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("since_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym26 := z.EncBinary() + _ = yym26 + if false { + } else { + r.EncodeInt(int64(x.SinceID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.SinceIDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("since_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym29 := z.EncBinary() + _ = yym29 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.SinceIDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *SearchMetadata) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *SearchMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "completed_in": + if r.TryDecodeAsNil() { + x.CompletedIn = 0 + } else { + yyv4 := &x.CompletedIn + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*float64)(yyv4)) = float64(r.DecodeFloat(false)) + } + } + case "count": + if r.TryDecodeAsNil() { + x.Count = 0 + } else { + yyv6 := &x.Count + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*int)(yyv6)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "max_id": + if r.TryDecodeAsNil() { + x.MaxID = 0 + } else { + yyv8 := &x.MaxID + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*int)(yyv8)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "max_id_str": + if r.TryDecodeAsNil() { + x.MaxIDStr = "" + } else { + yyv10 := &x.MaxIDStr + yym11 := z.DecBinary() + _ = yym11 + if false { + } else { + *((*string)(yyv10)) = r.DecodeString() + } + } + case "next_results": + if r.TryDecodeAsNil() { + x.NextResults = "" + } else { + yyv12 := &x.NextResults + yym13 := z.DecBinary() + _ = yym13 + if false { + } else { + *((*string)(yyv12)) = r.DecodeString() + } + } + case "query": + if r.TryDecodeAsNil() { + x.Query = "" + } else { + yyv14 := &x.Query + yym15 := z.DecBinary() + _ = yym15 + if false { + } else { + *((*string)(yyv14)) = r.DecodeString() + } + } + case "refresh_url": + if r.TryDecodeAsNil() { + x.RefreshURL = "" + } else { + yyv16 := &x.RefreshURL + yym17 := z.DecBinary() + _ = yym17 + if false { + } else { + *((*string)(yyv16)) = r.DecodeString() + } + } + case "since_id": + if r.TryDecodeAsNil() { + x.SinceID = 0 + } else { + yyv18 := &x.SinceID + yym19 := z.DecBinary() + _ = yym19 + if false { + } else { + *((*int)(yyv18)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "since_id_str": + if r.TryDecodeAsNil() { + x.SinceIDStr = "" + } else { + yyv20 := &x.SinceIDStr + yym21 := z.DecBinary() + _ = yym21 + if false { + } else { + *((*string)(yyv20)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *SearchMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj22 int + var yyb22 bool + var yyhl22 bool = l >= 0 + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CompletedIn = 0 + } else { + yyv23 := &x.CompletedIn + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*float64)(yyv23)) = float64(r.DecodeFloat(false)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Count = 0 + } else { + yyv25 := &x.Count + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*int)(yyv25)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.MaxID = 0 + } else { + yyv27 := &x.MaxID + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*int)(yyv27)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.MaxIDStr = "" + } else { + yyv29 := &x.MaxIDStr + yym30 := z.DecBinary() + _ = yym30 + if false { + } else { + *((*string)(yyv29)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.NextResults = "" + } else { + yyv31 := &x.NextResults + yym32 := z.DecBinary() + _ = yym32 + if false { + } else { + *((*string)(yyv31)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Query = "" + } else { + yyv33 := &x.Query + yym34 := z.DecBinary() + _ = yym34 + if false { + } else { + *((*string)(yyv33)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.RefreshURL = "" + } else { + yyv35 := &x.RefreshURL + yym36 := z.DecBinary() + _ = yym36 + if false { + } else { + *((*string)(yyv35)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SinceID = 0 + } else { + yyv37 := &x.SinceID + yym38 := z.DecBinary() + _ = yym38 + if false { + } else { + *((*int)(yyv37)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SinceIDStr = "" + } else { + yyv39 := &x.SinceIDStr + yym40 := z.DecBinary() + _ = yym40 + if false { + } else { + *((*string)(yyv39)) = r.DecodeString() + } + } + for { + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj22-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Hashtag) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("indices")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("text")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Hashtag) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Hashtag) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "indices": + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv4 := &x.Indices + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + z.F.DecSliceIntX(yyv4, false, d) + } + } + case "text": + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv6 := &x.Text + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Hashtag) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv9 := &x.Indices + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + z.F.DecSliceIntX(yyv9, false, d) + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv11 := &x.Text + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(yyv11)) = r.DecodeString() + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Entities) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [3]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(3) + } else { + yynn2 = 3 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Hashtags == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("hashtags")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Hashtags == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.UserMentions == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.UserMentions), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("user_mentions")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.UserMentions == nil { + r.EncodeNil() + } else { + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.UserMentions), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Entities) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Entities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "hashtags": + if r.TryDecodeAsNil() { + x.Hashtags = nil + } else { + yyv4 := &x.Hashtags + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceHashtag((*[]Hashtag)(yyv4), d) + } + } + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv6 := &x.Urls + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv6), d) + } + } + case "user_mentions": + if r.TryDecodeAsNil() { + x.UserMentions = nil + } else { + yyv8 := &x.UserMentions + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv8), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Entities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Hashtags = nil + } else { + yyv11 := &x.Hashtags + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + h.decSliceHashtag((*[]Hashtag)(yyv11), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv13 := &x.Urls + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.UserMentions = nil + } else { + yyv15 := &x.UserMentions + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv15), d) + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntityDescription) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntityDescription) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntityDescription) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv4 := &x.Urls + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntityDescription) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv7 := &x.Urls + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *URL) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [3]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(3) + } else { + yynn2 = 3 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.ExpandedURL == nil { + r.EncodeNil() + } else { + yy4 := *x.ExpandedURL + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy4)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("expanded_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.ExpandedURL == nil { + r.EncodeNil() + } else { + yy6 := *x.ExpandedURL + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy6)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("indices")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.URL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.URL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *URL) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *URL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "expanded_url": + if r.TryDecodeAsNil() { + if x.ExpandedURL != nil { + x.ExpandedURL = nil + } + } else { + if x.ExpandedURL == nil { + x.ExpandedURL = new(string) + } + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(x.ExpandedURL)) = r.DecodeString() + } + } + case "indices": + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv6 := &x.Indices + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + z.F.DecSliceIntX(yyv6, false, d) + } + } + case "url": + if r.TryDecodeAsNil() { + x.URL = "" + } else { + yyv8 := &x.URL + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*string)(yyv8)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *URL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.ExpandedURL != nil { + x.ExpandedURL = nil + } + } else { + if x.ExpandedURL == nil { + x.ExpandedURL = new(string) + } + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(x.ExpandedURL)) = r.DecodeString() + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv13 := &x.Indices + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + z.F.DecSliceIntX(yyv13, false, d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.URL = "" + } else { + yyv15 := &x.URL + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*string)(yyv15)) = r.DecodeString() + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntityURL) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceURL(([]URL)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceURL(([]URL)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntityURL) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntityURL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv4 := &x.Urls + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceURL((*[]URL)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntityURL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv7 := &x.Urls + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSliceURL((*[]URL)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntities) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy4 := &x.Description + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("description")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy6 := &x.Description + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy9 := &x.URL + yy9.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy11 := &x.URL + yy11.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntities) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "description": + if r.TryDecodeAsNil() { + x.Description = UserEntityDescription{} + } else { + yyv4 := &x.Description + yyv4.CodecDecodeSelf(d) + } + case "url": + if r.TryDecodeAsNil() { + x.URL = UserEntityURL{} + } else { + yyv5 := &x.URL + yyv5.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Description = UserEntityDescription{} + } else { + yyv7 := &x.Description + yyv7.CodecDecodeSelf(d) + } + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.URL = UserEntityURL{} + } else { + yyv8 := &x.URL + yyv8.CodecDecodeSelf(d) + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *User) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [39]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(39) + } else { + yynn2 = 39 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeBool(bool(x.ContributorsEnabled)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("contributors_enabled")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeBool(bool(x.ContributorsEnabled)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("created_at")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("default_profile")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfileImage)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("default_profile_image")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfileImage)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Description)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("description")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Description)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy19 := &x.Entities + yy19.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("entities")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy21 := &x.Entities + yy21.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym24 := z.EncBinary() + _ = yym24 + if false { + } else { + r.EncodeInt(int64(x.FavouritesCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("favourites_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeInt(int64(x.FavouritesCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.FollowRequestSent == nil { + r.EncodeNil() + } else { + yy27 := *x.FollowRequestSent + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy27)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("follow_request_sent")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.FollowRequestSent == nil { + r.EncodeNil() + } else { + yy29 := *x.FollowRequestSent + yym30 := z.EncBinary() + _ = yym30 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy29)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym32 := z.EncBinary() + _ = yym32 + if false { + } else { + r.EncodeInt(int64(x.FollowersCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("followers_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym33 := z.EncBinary() + _ = yym33 + if false { + } else { + r.EncodeInt(int64(x.FollowersCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Following == nil { + r.EncodeNil() + } else { + yy35 := *x.Following + yym36 := z.EncBinary() + _ = yym36 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy35)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("following")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Following == nil { + r.EncodeNil() + } else { + yy37 := *x.Following + yym38 := z.EncBinary() + _ = yym38 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy37)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym40 := z.EncBinary() + _ = yym40 + if false { + } else { + r.EncodeInt(int64(x.FriendsCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("friends_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym41 := z.EncBinary() + _ = yym41 + if false { + } else { + r.EncodeInt(int64(x.FriendsCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym43 := z.EncBinary() + _ = yym43 + if false { + } else { + r.EncodeBool(bool(x.GeoEnabled)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("geo_enabled")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym44 := z.EncBinary() + _ = yym44 + if false { + } else { + r.EncodeBool(bool(x.GeoEnabled)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym46 := z.EncBinary() + _ = yym46 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym47 := z.EncBinary() + _ = yym47 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym49 := z.EncBinary() + _ = yym49 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym50 := z.EncBinary() + _ = yym50 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym52 := z.EncBinary() + _ = yym52 + if false { + } else { + r.EncodeBool(bool(x.IsTranslator)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("is_translator")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym53 := z.EncBinary() + _ = yym53 + if false { + } else { + r.EncodeBool(bool(x.IsTranslator)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym55 := z.EncBinary() + _ = yym55 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Lang)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("lang")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym56 := z.EncBinary() + _ = yym56 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Lang)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym58 := z.EncBinary() + _ = yym58 + if false { + } else { + r.EncodeInt(int64(x.ListedCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("listed_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym59 := z.EncBinary() + _ = yym59 + if false { + } else { + r.EncodeInt(int64(x.ListedCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym61 := z.EncBinary() + _ = yym61 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Location)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("location")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym62 := z.EncBinary() + _ = yym62 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Location)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym64 := z.EncBinary() + _ = yym64 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Name)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym65 := z.EncBinary() + _ = yym65 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Name)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Notifications == nil { + r.EncodeNil() + } else { + yy67 := *x.Notifications + yym68 := z.EncBinary() + _ = yym68 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy67)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("notifications")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Notifications == nil { + r.EncodeNil() + } else { + yy69 := *x.Notifications + yym70 := z.EncBinary() + _ = yym70 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy69)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym72 := z.EncBinary() + _ = yym72 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym73 := z.EncBinary() + _ = yym73 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym75 := z.EncBinary() + _ = yym75 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_image_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym76 := z.EncBinary() + _ = yym76 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym78 := z.EncBinary() + _ = yym78 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURLHTTPS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_image_url_https")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym79 := z.EncBinary() + _ = yym79 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURLHTTPS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym81 := z.EncBinary() + _ = yym81 + if false { + } else { + r.EncodeBool(bool(x.ProfileBackgroundTile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_tile")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym82 := z.EncBinary() + _ = yym82 + if false { + } else { + r.EncodeBool(bool(x.ProfileBackgroundTile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym84 := z.EncBinary() + _ = yym84 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_image_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym85 := z.EncBinary() + _ = yym85 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym87 := z.EncBinary() + _ = yym87 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURLHTTPS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_image_url_https")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym88 := z.EncBinary() + _ = yym88 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURLHTTPS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym90 := z.EncBinary() + _ = yym90 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileLinkColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_link_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym91 := z.EncBinary() + _ = yym91 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileLinkColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym93 := z.EncBinary() + _ = yym93 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarBorderColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_sidebar_border_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym94 := z.EncBinary() + _ = yym94 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarBorderColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym96 := z.EncBinary() + _ = yym96 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarFillColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_sidebar_fill_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym97 := z.EncBinary() + _ = yym97 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarFillColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym99 := z.EncBinary() + _ = yym99 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileTextColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_text_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym100 := z.EncBinary() + _ = yym100 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileTextColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym102 := z.EncBinary() + _ = yym102 + if false { + } else { + r.EncodeBool(bool(x.ProfileUseBackgroundImage)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_use_background_image")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym103 := z.EncBinary() + _ = yym103 + if false { + } else { + r.EncodeBool(bool(x.ProfileUseBackgroundImage)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym105 := z.EncBinary() + _ = yym105 + if false { + } else { + r.EncodeBool(bool(x.Protected)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("protected")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym106 := z.EncBinary() + _ = yym106 + if false { + } else { + r.EncodeBool(bool(x.Protected)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym108 := z.EncBinary() + _ = yym108 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ScreenName)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("screen_name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym109 := z.EncBinary() + _ = yym109 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ScreenName)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym111 := z.EncBinary() + _ = yym111 + if false { + } else { + r.EncodeBool(bool(x.ShowAllInlineMedia)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("show_all_inline_media")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym112 := z.EncBinary() + _ = yym112 + if false { + } else { + r.EncodeBool(bool(x.ShowAllInlineMedia)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym114 := z.EncBinary() + _ = yym114 + if false { + } else { + r.EncodeInt(int64(x.StatusesCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("statuses_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym115 := z.EncBinary() + _ = yym115 + if false { + } else { + r.EncodeInt(int64(x.StatusesCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym117 := z.EncBinary() + _ = yym117 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.TimeZone)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("time_zone")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym118 := z.EncBinary() + _ = yym118 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.TimeZone)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.URL == nil { + r.EncodeNil() + } else { + yy120 := *x.URL + yym121 := z.EncBinary() + _ = yym121 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy120)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.URL == nil { + r.EncodeNil() + } else { + yy122 := *x.URL + yym123 := z.EncBinary() + _ = yym123 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy122)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym125 := z.EncBinary() + _ = yym125 + if false { + } else { + r.EncodeInt(int64(x.UtcOffset)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("utc_offset")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym126 := z.EncBinary() + _ = yym126 + if false { + } else { + r.EncodeInt(int64(x.UtcOffset)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym128 := z.EncBinary() + _ = yym128 + if false { + } else { + r.EncodeBool(bool(x.Verified)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("verified")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym129 := z.EncBinary() + _ = yym129 + if false { + } else { + r.EncodeBool(bool(x.Verified)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *User) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *User) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "contributors_enabled": + if r.TryDecodeAsNil() { + x.ContributorsEnabled = false + } else { + yyv4 := &x.ContributorsEnabled + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*bool)(yyv4)) = r.DecodeBool() + } + } + case "created_at": + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv6 := &x.CreatedAt + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + case "default_profile": + if r.TryDecodeAsNil() { + x.DefaultProfile = false + } else { + yyv8 := &x.DefaultProfile + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*bool)(yyv8)) = r.DecodeBool() + } + } + case "default_profile_image": + if r.TryDecodeAsNil() { + x.DefaultProfileImage = false + } else { + yyv10 := &x.DefaultProfileImage + yym11 := z.DecBinary() + _ = yym11 + if false { + } else { + *((*bool)(yyv10)) = r.DecodeBool() + } + } + case "description": + if r.TryDecodeAsNil() { + x.Description = "" + } else { + yyv12 := &x.Description + yym13 := z.DecBinary() + _ = yym13 + if false { + } else { + *((*string)(yyv12)) = r.DecodeString() + } + } + case "entities": + if r.TryDecodeAsNil() { + x.Entities = UserEntities{} + } else { + yyv14 := &x.Entities + yyv14.CodecDecodeSelf(d) + } + case "favourites_count": + if r.TryDecodeAsNil() { + x.FavouritesCount = 0 + } else { + yyv15 := &x.FavouritesCount + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*int)(yyv15)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "follow_request_sent": + if r.TryDecodeAsNil() { + if x.FollowRequestSent != nil { + x.FollowRequestSent = nil + } + } else { + if x.FollowRequestSent == nil { + x.FollowRequestSent = new(string) + } + yym18 := z.DecBinary() + _ = yym18 + if false { + } else { + *((*string)(x.FollowRequestSent)) = r.DecodeString() + } + } + case "followers_count": + if r.TryDecodeAsNil() { + x.FollowersCount = 0 + } else { + yyv19 := &x.FollowersCount + yym20 := z.DecBinary() + _ = yym20 + if false { + } else { + *((*int)(yyv19)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "following": + if r.TryDecodeAsNil() { + if x.Following != nil { + x.Following = nil + } + } else { + if x.Following == nil { + x.Following = new(string) + } + yym22 := z.DecBinary() + _ = yym22 + if false { + } else { + *((*string)(x.Following)) = r.DecodeString() + } + } + case "friends_count": + if r.TryDecodeAsNil() { + x.FriendsCount = 0 + } else { + yyv23 := &x.FriendsCount + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*int)(yyv23)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "geo_enabled": + if r.TryDecodeAsNil() { + x.GeoEnabled = false + } else { + yyv25 := &x.GeoEnabled + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*bool)(yyv25)) = r.DecodeBool() + } + } + case "id": + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv27 := &x.ID + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*int)(yyv27)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "id_str": + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv29 := &x.IDStr + yym30 := z.DecBinary() + _ = yym30 + if false { + } else { + *((*string)(yyv29)) = r.DecodeString() + } + } + case "is_translator": + if r.TryDecodeAsNil() { + x.IsTranslator = false + } else { + yyv31 := &x.IsTranslator + yym32 := z.DecBinary() + _ = yym32 + if false { + } else { + *((*bool)(yyv31)) = r.DecodeBool() + } + } + case "lang": + if r.TryDecodeAsNil() { + x.Lang = "" + } else { + yyv33 := &x.Lang + yym34 := z.DecBinary() + _ = yym34 + if false { + } else { + *((*string)(yyv33)) = r.DecodeString() + } + } + case "listed_count": + if r.TryDecodeAsNil() { + x.ListedCount = 0 + } else { + yyv35 := &x.ListedCount + yym36 := z.DecBinary() + _ = yym36 + if false { + } else { + *((*int)(yyv35)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "location": + if r.TryDecodeAsNil() { + x.Location = "" + } else { + yyv37 := &x.Location + yym38 := z.DecBinary() + _ = yym38 + if false { + } else { + *((*string)(yyv37)) = r.DecodeString() + } + } + case "name": + if r.TryDecodeAsNil() { + x.Name = "" + } else { + yyv39 := &x.Name + yym40 := z.DecBinary() + _ = yym40 + if false { + } else { + *((*string)(yyv39)) = r.DecodeString() + } + } + case "notifications": + if r.TryDecodeAsNil() { + if x.Notifications != nil { + x.Notifications = nil + } + } else { + if x.Notifications == nil { + x.Notifications = new(string) + } + yym42 := z.DecBinary() + _ = yym42 + if false { + } else { + *((*string)(x.Notifications)) = r.DecodeString() + } + } + case "profile_background_color": + if r.TryDecodeAsNil() { + x.ProfileBackgroundColor = "" + } else { + yyv43 := &x.ProfileBackgroundColor + yym44 := z.DecBinary() + _ = yym44 + if false { + } else { + *((*string)(yyv43)) = r.DecodeString() + } + } + case "profile_background_image_url": + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURL = "" + } else { + yyv45 := &x.ProfileBackgroundImageURL + yym46 := z.DecBinary() + _ = yym46 + if false { + } else { + *((*string)(yyv45)) = r.DecodeString() + } + } + case "profile_background_image_url_https": + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURLHTTPS = "" + } else { + yyv47 := &x.ProfileBackgroundImageURLHTTPS + yym48 := z.DecBinary() + _ = yym48 + if false { + } else { + *((*string)(yyv47)) = r.DecodeString() + } + } + case "profile_background_tile": + if r.TryDecodeAsNil() { + x.ProfileBackgroundTile = false + } else { + yyv49 := &x.ProfileBackgroundTile + yym50 := z.DecBinary() + _ = yym50 + if false { + } else { + *((*bool)(yyv49)) = r.DecodeBool() + } + } + case "profile_image_url": + if r.TryDecodeAsNil() { + x.ProfileImageURL = "" + } else { + yyv51 := &x.ProfileImageURL + yym52 := z.DecBinary() + _ = yym52 + if false { + } else { + *((*string)(yyv51)) = r.DecodeString() + } + } + case "profile_image_url_https": + if r.TryDecodeAsNil() { + x.ProfileImageURLHTTPS = "" + } else { + yyv53 := &x.ProfileImageURLHTTPS + yym54 := z.DecBinary() + _ = yym54 + if false { + } else { + *((*string)(yyv53)) = r.DecodeString() + } + } + case "profile_link_color": + if r.TryDecodeAsNil() { + x.ProfileLinkColor = "" + } else { + yyv55 := &x.ProfileLinkColor + yym56 := z.DecBinary() + _ = yym56 + if false { + } else { + *((*string)(yyv55)) = r.DecodeString() + } + } + case "profile_sidebar_border_color": + if r.TryDecodeAsNil() { + x.ProfileSidebarBorderColor = "" + } else { + yyv57 := &x.ProfileSidebarBorderColor + yym58 := z.DecBinary() + _ = yym58 + if false { + } else { + *((*string)(yyv57)) = r.DecodeString() + } + } + case "profile_sidebar_fill_color": + if r.TryDecodeAsNil() { + x.ProfileSidebarFillColor = "" + } else { + yyv59 := &x.ProfileSidebarFillColor + yym60 := z.DecBinary() + _ = yym60 + if false { + } else { + *((*string)(yyv59)) = r.DecodeString() + } + } + case "profile_text_color": + if r.TryDecodeAsNil() { + x.ProfileTextColor = "" + } else { + yyv61 := &x.ProfileTextColor + yym62 := z.DecBinary() + _ = yym62 + if false { + } else { + *((*string)(yyv61)) = r.DecodeString() + } + } + case "profile_use_background_image": + if r.TryDecodeAsNil() { + x.ProfileUseBackgroundImage = false + } else { + yyv63 := &x.ProfileUseBackgroundImage + yym64 := z.DecBinary() + _ = yym64 + if false { + } else { + *((*bool)(yyv63)) = r.DecodeBool() + } + } + case "protected": + if r.TryDecodeAsNil() { + x.Protected = false + } else { + yyv65 := &x.Protected + yym66 := z.DecBinary() + _ = yym66 + if false { + } else { + *((*bool)(yyv65)) = r.DecodeBool() + } + } + case "screen_name": + if r.TryDecodeAsNil() { + x.ScreenName = "" + } else { + yyv67 := &x.ScreenName + yym68 := z.DecBinary() + _ = yym68 + if false { + } else { + *((*string)(yyv67)) = r.DecodeString() + } + } + case "show_all_inline_media": + if r.TryDecodeAsNil() { + x.ShowAllInlineMedia = false + } else { + yyv69 := &x.ShowAllInlineMedia + yym70 := z.DecBinary() + _ = yym70 + if false { + } else { + *((*bool)(yyv69)) = r.DecodeBool() + } + } + case "statuses_count": + if r.TryDecodeAsNil() { + x.StatusesCount = 0 + } else { + yyv71 := &x.StatusesCount + yym72 := z.DecBinary() + _ = yym72 + if false { + } else { + *((*int)(yyv71)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "time_zone": + if r.TryDecodeAsNil() { + x.TimeZone = "" + } else { + yyv73 := &x.TimeZone + yym74 := z.DecBinary() + _ = yym74 + if false { + } else { + *((*string)(yyv73)) = r.DecodeString() + } + } + case "url": + if r.TryDecodeAsNil() { + if x.URL != nil { + x.URL = nil + } + } else { + if x.URL == nil { + x.URL = new(string) + } + yym76 := z.DecBinary() + _ = yym76 + if false { + } else { + *((*string)(x.URL)) = r.DecodeString() + } + } + case "utc_offset": + if r.TryDecodeAsNil() { + x.UtcOffset = 0 + } else { + yyv77 := &x.UtcOffset + yym78 := z.DecBinary() + _ = yym78 + if false { + } else { + *((*int)(yyv77)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "verified": + if r.TryDecodeAsNil() { + x.Verified = false + } else { + yyv79 := &x.Verified + yym80 := z.DecBinary() + _ = yym80 + if false { + } else { + *((*bool)(yyv79)) = r.DecodeBool() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *User) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj81 int + var yyb81 bool + var yyhl81 bool = l >= 0 + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ContributorsEnabled = false + } else { + yyv82 := &x.ContributorsEnabled + yym83 := z.DecBinary() + _ = yym83 + if false { + } else { + *((*bool)(yyv82)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv84 := &x.CreatedAt + yym85 := z.DecBinary() + _ = yym85 + if false { + } else { + *((*string)(yyv84)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.DefaultProfile = false + } else { + yyv86 := &x.DefaultProfile + yym87 := z.DecBinary() + _ = yym87 + if false { + } else { + *((*bool)(yyv86)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.DefaultProfileImage = false + } else { + yyv88 := &x.DefaultProfileImage + yym89 := z.DecBinary() + _ = yym89 + if false { + } else { + *((*bool)(yyv88)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Description = "" + } else { + yyv90 := &x.Description + yym91 := z.DecBinary() + _ = yym91 + if false { + } else { + *((*string)(yyv90)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Entities = UserEntities{} + } else { + yyv92 := &x.Entities + yyv92.CodecDecodeSelf(d) + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FavouritesCount = 0 + } else { + yyv93 := &x.FavouritesCount + yym94 := z.DecBinary() + _ = yym94 + if false { + } else { + *((*int)(yyv93)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.FollowRequestSent != nil { + x.FollowRequestSent = nil + } + } else { + if x.FollowRequestSent == nil { + x.FollowRequestSent = new(string) + } + yym96 := z.DecBinary() + _ = yym96 + if false { + } else { + *((*string)(x.FollowRequestSent)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FollowersCount = 0 + } else { + yyv97 := &x.FollowersCount + yym98 := z.DecBinary() + _ = yym98 + if false { + } else { + *((*int)(yyv97)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Following != nil { + x.Following = nil + } + } else { + if x.Following == nil { + x.Following = new(string) + } + yym100 := z.DecBinary() + _ = yym100 + if false { + } else { + *((*string)(x.Following)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FriendsCount = 0 + } else { + yyv101 := &x.FriendsCount + yym102 := z.DecBinary() + _ = yym102 + if false { + } else { + *((*int)(yyv101)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.GeoEnabled = false + } else { + yyv103 := &x.GeoEnabled + yym104 := z.DecBinary() + _ = yym104 + if false { + } else { + *((*bool)(yyv103)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv105 := &x.ID + yym106 := z.DecBinary() + _ = yym106 + if false { + } else { + *((*int)(yyv105)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv107 := &x.IDStr + yym108 := z.DecBinary() + _ = yym108 + if false { + } else { + *((*string)(yyv107)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IsTranslator = false + } else { + yyv109 := &x.IsTranslator + yym110 := z.DecBinary() + _ = yym110 + if false { + } else { + *((*bool)(yyv109)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Lang = "" + } else { + yyv111 := &x.Lang + yym112 := z.DecBinary() + _ = yym112 + if false { + } else { + *((*string)(yyv111)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ListedCount = 0 + } else { + yyv113 := &x.ListedCount + yym114 := z.DecBinary() + _ = yym114 + if false { + } else { + *((*int)(yyv113)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Location = "" + } else { + yyv115 := &x.Location + yym116 := z.DecBinary() + _ = yym116 + if false { + } else { + *((*string)(yyv115)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Name = "" + } else { + yyv117 := &x.Name + yym118 := z.DecBinary() + _ = yym118 + if false { + } else { + *((*string)(yyv117)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Notifications != nil { + x.Notifications = nil + } + } else { + if x.Notifications == nil { + x.Notifications = new(string) + } + yym120 := z.DecBinary() + _ = yym120 + if false { + } else { + *((*string)(x.Notifications)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundColor = "" + } else { + yyv121 := &x.ProfileBackgroundColor + yym122 := z.DecBinary() + _ = yym122 + if false { + } else { + *((*string)(yyv121)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURL = "" + } else { + yyv123 := &x.ProfileBackgroundImageURL + yym124 := z.DecBinary() + _ = yym124 + if false { + } else { + *((*string)(yyv123)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURLHTTPS = "" + } else { + yyv125 := &x.ProfileBackgroundImageURLHTTPS + yym126 := z.DecBinary() + _ = yym126 + if false { + } else { + *((*string)(yyv125)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundTile = false + } else { + yyv127 := &x.ProfileBackgroundTile + yym128 := z.DecBinary() + _ = yym128 + if false { + } else { + *((*bool)(yyv127)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileImageURL = "" + } else { + yyv129 := &x.ProfileImageURL + yym130 := z.DecBinary() + _ = yym130 + if false { + } else { + *((*string)(yyv129)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileImageURLHTTPS = "" + } else { + yyv131 := &x.ProfileImageURLHTTPS + yym132 := z.DecBinary() + _ = yym132 + if false { + } else { + *((*string)(yyv131)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileLinkColor = "" + } else { + yyv133 := &x.ProfileLinkColor + yym134 := z.DecBinary() + _ = yym134 + if false { + } else { + *((*string)(yyv133)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileSidebarBorderColor = "" + } else { + yyv135 := &x.ProfileSidebarBorderColor + yym136 := z.DecBinary() + _ = yym136 + if false { + } else { + *((*string)(yyv135)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileSidebarFillColor = "" + } else { + yyv137 := &x.ProfileSidebarFillColor + yym138 := z.DecBinary() + _ = yym138 + if false { + } else { + *((*string)(yyv137)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileTextColor = "" + } else { + yyv139 := &x.ProfileTextColor + yym140 := z.DecBinary() + _ = yym140 + if false { + } else { + *((*string)(yyv139)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileUseBackgroundImage = false + } else { + yyv141 := &x.ProfileUseBackgroundImage + yym142 := z.DecBinary() + _ = yym142 + if false { + } else { + *((*bool)(yyv141)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Protected = false + } else { + yyv143 := &x.Protected + yym144 := z.DecBinary() + _ = yym144 + if false { + } else { + *((*bool)(yyv143)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ScreenName = "" + } else { + yyv145 := &x.ScreenName + yym146 := z.DecBinary() + _ = yym146 + if false { + } else { + *((*string)(yyv145)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ShowAllInlineMedia = false + } else { + yyv147 := &x.ShowAllInlineMedia + yym148 := z.DecBinary() + _ = yym148 + if false { + } else { + *((*bool)(yyv147)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.StatusesCount = 0 + } else { + yyv149 := &x.StatusesCount + yym150 := z.DecBinary() + _ = yym150 + if false { + } else { + *((*int)(yyv149)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.TimeZone = "" + } else { + yyv151 := &x.TimeZone + yym152 := z.DecBinary() + _ = yym152 + if false { + } else { + *((*string)(yyv151)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.URL != nil { + x.URL = nil + } + } else { + if x.URL == nil { + x.URL = new(string) + } + yym154 := z.DecBinary() + _ = yym154 + if false { + } else { + *((*string)(x.URL)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.UtcOffset = 0 + } else { + yyv155 := &x.UtcOffset + yym156 := z.DecBinary() + _ = yym156 + if false { + } else { + *((*int)(yyv155)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Verified = false + } else { + yyv157 := &x.Verified + yym158 := z.DecBinary() + _ = yym158 + if false { + } else { + *((*bool)(yyv157)) = r.DecodeBool() + } + } + for { + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj81-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *StatusMetadata) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IsoLanguageCode)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("iso_language_code")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IsoLanguageCode)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ResultType)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("result_type")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ResultType)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *StatusMetadata) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *StatusMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "iso_language_code": + if r.TryDecodeAsNil() { + x.IsoLanguageCode = "" + } else { + yyv4 := &x.IsoLanguageCode + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(yyv4)) = r.DecodeString() + } + } + case "result_type": + if r.TryDecodeAsNil() { + x.ResultType = "" + } else { + yyv6 := &x.ResultType + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *StatusMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IsoLanguageCode = "" + } else { + yyv9 := &x.IsoLanguageCode + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + *((*string)(yyv9)) = r.DecodeString() + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ResultType = "" + } else { + yyv11 := &x.ResultType + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(yyv11)) = r.DecodeString() + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Status) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [21]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(21) + } else { + yynn2 = 21 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Contributors == nil { + r.EncodeNil() + } else { + yy4 := *x.Contributors + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy4)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("contributors")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Contributors == nil { + r.EncodeNil() + } else { + yy6 := *x.Contributors + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy6)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Coordinates == nil { + r.EncodeNil() + } else { + yy9 := *x.Coordinates + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy9)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("coordinates")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Coordinates == nil { + r.EncodeNil() + } else { + yy11 := *x.Coordinates + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy11)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("created_at")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy17 := &x.Entities + yy17.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("entities")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy19 := &x.Entities + yy19.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeBool(bool(x.Favorited)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("favorited")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeBool(bool(x.Favorited)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Geo == nil { + r.EncodeNil() + } else { + yy25 := *x.Geo + yym26 := z.EncBinary() + _ = yym26 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy25)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("geo")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Geo == nil { + r.EncodeNil() + } else { + yy27 := *x.Geo + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy27)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym30 := z.EncBinary() + _ = yym30 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym31 := z.EncBinary() + _ = yym31 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym33 := z.EncBinary() + _ = yym33 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym34 := z.EncBinary() + _ = yym34 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToScreenName == nil { + r.EncodeNil() + } else { + yy36 := *x.InReplyToScreenName + yym37 := z.EncBinary() + _ = yym37 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy36)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_screen_name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToScreenName == nil { + r.EncodeNil() + } else { + yy38 := *x.InReplyToScreenName + yym39 := z.EncBinary() + _ = yym39 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy38)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToStatusID == nil { + r.EncodeNil() + } else { + yy41 := *x.InReplyToStatusID + yym42 := z.EncBinary() + _ = yym42 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy41)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_status_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToStatusID == nil { + r.EncodeNil() + } else { + yy43 := *x.InReplyToStatusID + yym44 := z.EncBinary() + _ = yym44 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy43)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToStatusIDStr == nil { + r.EncodeNil() + } else { + yy46 := *x.InReplyToStatusIDStr + yym47 := z.EncBinary() + _ = yym47 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy46)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_status_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToStatusIDStr == nil { + r.EncodeNil() + } else { + yy48 := *x.InReplyToStatusIDStr + yym49 := z.EncBinary() + _ = yym49 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy48)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToUserID == nil { + r.EncodeNil() + } else { + yy51 := *x.InReplyToUserID + yym52 := z.EncBinary() + _ = yym52 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy51)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_user_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToUserID == nil { + r.EncodeNil() + } else { + yy53 := *x.InReplyToUserID + yym54 := z.EncBinary() + _ = yym54 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy53)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToUserIDStr == nil { + r.EncodeNil() + } else { + yy56 := *x.InReplyToUserIDStr + yym57 := z.EncBinary() + _ = yym57 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy56)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_user_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToUserIDStr == nil { + r.EncodeNil() + } else { + yy58 := *x.InReplyToUserIDStr + yym59 := z.EncBinary() + _ = yym59 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy58)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy61 := &x.Metadata + yy61.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy63 := &x.Metadata + yy63.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Place == nil { + r.EncodeNil() + } else { + yy66 := *x.Place + yym67 := z.EncBinary() + _ = yym67 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy66)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("place")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Place == nil { + r.EncodeNil() + } else { + yy68 := *x.Place + yym69 := z.EncBinary() + _ = yym69 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy68)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym71 := z.EncBinary() + _ = yym71 + if false { + } else { + r.EncodeInt(int64(x.RetweetCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("retweet_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym72 := z.EncBinary() + _ = yym72 + if false { + } else { + r.EncodeInt(int64(x.RetweetCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym74 := z.EncBinary() + _ = yym74 + if false { + } else { + r.EncodeBool(bool(x.Retweeted)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("retweeted")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym75 := z.EncBinary() + _ = yym75 + if false { + } else { + r.EncodeBool(bool(x.Retweeted)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym77 := z.EncBinary() + _ = yym77 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Source)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("source")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym78 := z.EncBinary() + _ = yym78 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Source)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym80 := z.EncBinary() + _ = yym80 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("text")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym81 := z.EncBinary() + _ = yym81 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym83 := z.EncBinary() + _ = yym83 + if false { + } else { + r.EncodeBool(bool(x.Truncated)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("truncated")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym84 := z.EncBinary() + _ = yym84 + if false { + } else { + r.EncodeBool(bool(x.Truncated)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy86 := &x.User + yy86.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("user")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy88 := &x.User + yy88.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Status) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Status) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "contributors": + if r.TryDecodeAsNil() { + if x.Contributors != nil { + x.Contributors = nil + } + } else { + if x.Contributors == nil { + x.Contributors = new(string) + } + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(x.Contributors)) = r.DecodeString() + } + } + case "coordinates": + if r.TryDecodeAsNil() { + if x.Coordinates != nil { + x.Coordinates = nil + } + } else { + if x.Coordinates == nil { + x.Coordinates = new(string) + } + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(x.Coordinates)) = r.DecodeString() + } + } + case "created_at": + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv8 := &x.CreatedAt + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*string)(yyv8)) = r.DecodeString() + } + } + case "entities": + if r.TryDecodeAsNil() { + x.Entities = Entities{} + } else { + yyv10 := &x.Entities + yyv10.CodecDecodeSelf(d) + } + case "favorited": + if r.TryDecodeAsNil() { + x.Favorited = false + } else { + yyv11 := &x.Favorited + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*bool)(yyv11)) = r.DecodeBool() + } + } + case "geo": + if r.TryDecodeAsNil() { + if x.Geo != nil { + x.Geo = nil + } + } else { + if x.Geo == nil { + x.Geo = new(string) + } + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + *((*string)(x.Geo)) = r.DecodeString() + } + } + case "id": + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv15 := &x.ID + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*int64)(yyv15)) = int64(r.DecodeInt(64)) + } + } + case "id_str": + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv17 := &x.IDStr + yym18 := z.DecBinary() + _ = yym18 + if false { + } else { + *((*string)(yyv17)) = r.DecodeString() + } + } + case "in_reply_to_screen_name": + if r.TryDecodeAsNil() { + if x.InReplyToScreenName != nil { + x.InReplyToScreenName = nil + } + } else { + if x.InReplyToScreenName == nil { + x.InReplyToScreenName = new(string) + } + yym20 := z.DecBinary() + _ = yym20 + if false { + } else { + *((*string)(x.InReplyToScreenName)) = r.DecodeString() + } + } + case "in_reply_to_status_id": + if r.TryDecodeAsNil() { + if x.InReplyToStatusID != nil { + x.InReplyToStatusID = nil + } + } else { + if x.InReplyToStatusID == nil { + x.InReplyToStatusID = new(string) + } + yym22 := z.DecBinary() + _ = yym22 + if false { + } else { + *((*string)(x.InReplyToStatusID)) = r.DecodeString() + } + } + case "in_reply_to_status_id_str": + if r.TryDecodeAsNil() { + if x.InReplyToStatusIDStr != nil { + x.InReplyToStatusIDStr = nil + } + } else { + if x.InReplyToStatusIDStr == nil { + x.InReplyToStatusIDStr = new(string) + } + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*string)(x.InReplyToStatusIDStr)) = r.DecodeString() + } + } + case "in_reply_to_user_id": + if r.TryDecodeAsNil() { + if x.InReplyToUserID != nil { + x.InReplyToUserID = nil + } + } else { + if x.InReplyToUserID == nil { + x.InReplyToUserID = new(string) + } + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*string)(x.InReplyToUserID)) = r.DecodeString() + } + } + case "in_reply_to_user_id_str": + if r.TryDecodeAsNil() { + if x.InReplyToUserIDStr != nil { + x.InReplyToUserIDStr = nil + } + } else { + if x.InReplyToUserIDStr == nil { + x.InReplyToUserIDStr = new(string) + } + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*string)(x.InReplyToUserIDStr)) = r.DecodeString() + } + } + case "metadata": + if r.TryDecodeAsNil() { + x.Metadata = StatusMetadata{} + } else { + yyv29 := &x.Metadata + yyv29.CodecDecodeSelf(d) + } + case "place": + if r.TryDecodeAsNil() { + if x.Place != nil { + x.Place = nil + } + } else { + if x.Place == nil { + x.Place = new(string) + } + yym31 := z.DecBinary() + _ = yym31 + if false { + } else { + *((*string)(x.Place)) = r.DecodeString() + } + } + case "retweet_count": + if r.TryDecodeAsNil() { + x.RetweetCount = 0 + } else { + yyv32 := &x.RetweetCount + yym33 := z.DecBinary() + _ = yym33 + if false { + } else { + *((*int)(yyv32)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "retweeted": + if r.TryDecodeAsNil() { + x.Retweeted = false + } else { + yyv34 := &x.Retweeted + yym35 := z.DecBinary() + _ = yym35 + if false { + } else { + *((*bool)(yyv34)) = r.DecodeBool() + } + } + case "source": + if r.TryDecodeAsNil() { + x.Source = "" + } else { + yyv36 := &x.Source + yym37 := z.DecBinary() + _ = yym37 + if false { + } else { + *((*string)(yyv36)) = r.DecodeString() + } + } + case "text": + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv38 := &x.Text + yym39 := z.DecBinary() + _ = yym39 + if false { + } else { + *((*string)(yyv38)) = r.DecodeString() + } + } + case "truncated": + if r.TryDecodeAsNil() { + x.Truncated = false + } else { + yyv40 := &x.Truncated + yym41 := z.DecBinary() + _ = yym41 + if false { + } else { + *((*bool)(yyv40)) = r.DecodeBool() + } + } + case "user": + if r.TryDecodeAsNil() { + x.User = User{} + } else { + yyv42 := &x.User + yyv42.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Status) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj43 int + var yyb43 bool + var yyhl43 bool = l >= 0 + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Contributors != nil { + x.Contributors = nil + } + } else { + if x.Contributors == nil { + x.Contributors = new(string) + } + yym45 := z.DecBinary() + _ = yym45 + if false { + } else { + *((*string)(x.Contributors)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Coordinates != nil { + x.Coordinates = nil + } + } else { + if x.Coordinates == nil { + x.Coordinates = new(string) + } + yym47 := z.DecBinary() + _ = yym47 + if false { + } else { + *((*string)(x.Coordinates)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv48 := &x.CreatedAt + yym49 := z.DecBinary() + _ = yym49 + if false { + } else { + *((*string)(yyv48)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Entities = Entities{} + } else { + yyv50 := &x.Entities + yyv50.CodecDecodeSelf(d) + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Favorited = false + } else { + yyv51 := &x.Favorited + yym52 := z.DecBinary() + _ = yym52 + if false { + } else { + *((*bool)(yyv51)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Geo != nil { + x.Geo = nil + } + } else { + if x.Geo == nil { + x.Geo = new(string) + } + yym54 := z.DecBinary() + _ = yym54 + if false { + } else { + *((*string)(x.Geo)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv55 := &x.ID + yym56 := z.DecBinary() + _ = yym56 + if false { + } else { + *((*int64)(yyv55)) = int64(r.DecodeInt(64)) + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv57 := &x.IDStr + yym58 := z.DecBinary() + _ = yym58 + if false { + } else { + *((*string)(yyv57)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToScreenName != nil { + x.InReplyToScreenName = nil + } + } else { + if x.InReplyToScreenName == nil { + x.InReplyToScreenName = new(string) + } + yym60 := z.DecBinary() + _ = yym60 + if false { + } else { + *((*string)(x.InReplyToScreenName)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToStatusID != nil { + x.InReplyToStatusID = nil + } + } else { + if x.InReplyToStatusID == nil { + x.InReplyToStatusID = new(string) + } + yym62 := z.DecBinary() + _ = yym62 + if false { + } else { + *((*string)(x.InReplyToStatusID)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToStatusIDStr != nil { + x.InReplyToStatusIDStr = nil + } + } else { + if x.InReplyToStatusIDStr == nil { + x.InReplyToStatusIDStr = new(string) + } + yym64 := z.DecBinary() + _ = yym64 + if false { + } else { + *((*string)(x.InReplyToStatusIDStr)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToUserID != nil { + x.InReplyToUserID = nil + } + } else { + if x.InReplyToUserID == nil { + x.InReplyToUserID = new(string) + } + yym66 := z.DecBinary() + _ = yym66 + if false { + } else { + *((*string)(x.InReplyToUserID)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToUserIDStr != nil { + x.InReplyToUserIDStr = nil + } + } else { + if x.InReplyToUserIDStr == nil { + x.InReplyToUserIDStr = new(string) + } + yym68 := z.DecBinary() + _ = yym68 + if false { + } else { + *((*string)(x.InReplyToUserIDStr)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Metadata = StatusMetadata{} + } else { + yyv69 := &x.Metadata + yyv69.CodecDecodeSelf(d) + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Place != nil { + x.Place = nil + } + } else { + if x.Place == nil { + x.Place = new(string) + } + yym71 := z.DecBinary() + _ = yym71 + if false { + } else { + *((*string)(x.Place)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.RetweetCount = 0 + } else { + yyv72 := &x.RetweetCount + yym73 := z.DecBinary() + _ = yym73 + if false { + } else { + *((*int)(yyv72)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Retweeted = false + } else { + yyv74 := &x.Retweeted + yym75 := z.DecBinary() + _ = yym75 + if false { + } else { + *((*bool)(yyv74)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Source = "" + } else { + yyv76 := &x.Source + yym77 := z.DecBinary() + _ = yym77 + if false { + } else { + *((*string)(yyv76)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv78 := &x.Text + yym79 := z.DecBinary() + _ = yym79 + if false { + } else { + *((*string)(yyv78)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Truncated = false + } else { + yyv80 := &x.Truncated + yym81 := z.DecBinary() + _ = yym81 + if false { + } else { + *((*bool)(yyv80)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.User = User{} + } else { + yyv82 := &x.User + yyv82.CodecDecodeSelf(d) + } + for { + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj43-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *LargeStruct) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy4 := &x.SearchMetadata + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("search_metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy6 := &x.SearchMetadata + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Statuses == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceStatus(([]Status)(x.Statuses), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("statuses")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Statuses == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceStatus(([]Status)(x.Statuses), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *LargeStruct) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *LargeStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "search_metadata": + if r.TryDecodeAsNil() { + x.SearchMetadata = SearchMetadata{} + } else { + yyv4 := &x.SearchMetadata + yyv4.CodecDecodeSelf(d) + } + case "statuses": + if r.TryDecodeAsNil() { + x.Statuses = nil + } else { + yyv5 := &x.Statuses + yym6 := z.DecBinary() + _ = yym6 + if false { + } else { + h.decSliceStatus((*[]Status)(yyv5), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *LargeStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SearchMetadata = SearchMetadata{} + } else { + yyv8 := &x.SearchMetadata + yyv8.CodecDecodeSelf(d) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Statuses = nil + } else { + yyv9 := &x.Statuses + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceStatus((*[]Status)(yyv9), d) + } + } + for { + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj7-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *XLStruct) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Data == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("Data")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Data == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *XLStruct) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *XLStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "Data": + if r.TryDecodeAsNil() { + x.Data = nil + } else { + yyv4 := &x.Data + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceLargeStruct((*[]LargeStruct)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *XLStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Data = nil + } else { + yyv7 := &x.Data + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSliceLargeStruct((*[]LargeStruct)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) encSliceHashtag(v []Hashtag, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceHashtag(v *[]Hashtag, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []Hashtag{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]Hashtag, yyrl1) + } + } else { + yyv1 = make([]Hashtag, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, Hashtag{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, Hashtag{}) // var yyz1 Hashtag + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []Hashtag{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSlicePtrtostring(v []*string, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if yyv1 == nil { + r.EncodeNil() + } else { + yy2 := *yyv1 + yym3 := z.EncBinary() + _ = yym3 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy2)) + } + } + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSlicePtrtostring(v *[]*string, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []*string{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]*string, yyrl1) + } + } else { + yyv1 = make([]*string, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw2 := yyv1[yyj1] + yym3 := z.DecBinary() + _ = yym3 + if false { + } else { + *((*string)(yyw2)) = r.DecodeString() + } + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, nil) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw4 := yyv1[yyj1] + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(yyw4)) = r.DecodeString() + } + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, nil) // var yyz1 *string + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw6 := yyv1[yyj1] + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyw6)) = r.DecodeString() + } + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []*string{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceURL(v []URL, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceURL(v *[]URL, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []URL{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 48) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]URL, yyrl1) + } + } else { + yyv1 = make([]URL, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, URL{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, URL{}) // var yyz1 URL + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []URL{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceStatus(v []Status, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceStatus(v *[]Status, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []Status{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 752) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]Status, yyrl1) + } + } else { + yyv1 = make([]Status, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, Status{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, Status{}) // var yyz1 Status + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []Status{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceLargeStruct(v []LargeStruct, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceLargeStruct(v *[]LargeStruct, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []LargeStruct{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 136) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]LargeStruct, yyrl1) + } + } else { + yyv1 = make([]LargeStruct, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, LargeStruct{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, LargeStruct{}) // var yyz1 LargeStruct + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []LargeStruct{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go new file mode 100644 index 000000000..9f000d3ad --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go @@ -0,0 +1,6723 @@ +// +build use_ffjson + +// DO NOT EDIT! +// Code generated by ffjson +// source: .root/src/github.com/mailru/easyjson/benchmark/data.go +// DO NOT EDIT! + +package benchmark + +import ( + "bytes" + "errors" + "fmt" + fflib "github.com/pquerna/ffjson/fflib/v1" +) + +func (mj *Entities) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Entities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"hashtags":`) + if mj.Hashtags != nil { + buf.WriteString(`[`) + for i, v := range mj.Hashtags { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"user_mentions":`) + if mj.UserMentions != nil { + buf.WriteString(`[`) + for i, v := range mj.UserMentions { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Entitiesbase = iota + ffj_t_Entitiesno_such_key + + ffj_t_Entities_Hashtags + + ffj_t_Entities_Urls + + ffj_t_Entities_UserMentions +) + +var ffj_key_Entities_Hashtags = []byte("hashtags") + +var ffj_key_Entities_Urls = []byte("urls") + +var ffj_key_Entities_UserMentions = []byte("user_mentions") + +func (uj *Entities) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Entities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Entitiesbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Entitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'h': + + if bytes.Equal(ffj_key_Entities_Hashtags, kn) { + currentKey = ffj_t_Entities_Hashtags + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_Entities_Urls, kn) { + currentKey = ffj_t_Entities_Urls + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Entities_UserMentions, kn) { + currentKey = ffj_t_Entities_UserMentions + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_Entities_UserMentions, kn) { + currentKey = ffj_t_Entities_UserMentions + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Entities_Urls, kn) { + currentKey = ffj_t_Entities_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Entities_Hashtags, kn) { + currentKey = ffj_t_Entities_Hashtags + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Entitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Entities_Hashtags: + goto handle_Hashtags + + case ffj_t_Entities_Urls: + goto handle_Urls + + case ffj_t_Entities_UserMentions: + goto handle_UserMentions + + case ffj_t_Entitiesno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Hashtags: + + /* handler: uj.Hashtags type=[]benchmark.Hashtag kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Hashtags = nil + } else { + + uj.Hashtags = make([]Hashtag, 0) + + wantVal := true + + for { + + var tmp_uj__Hashtags Hashtag + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Hashtags type=benchmark.Hashtag kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Hashtags.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Hashtags = append(uj.Hashtags, tmp_uj__Hashtags) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Urls: + + /* handler: uj.Urls type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__Urls *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__Urls = nil + } else { + if tmp_uj__Urls == nil { + tmp_uj__Urls = new(string) + } + + /* handler: tmp_uj__Urls type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__Urls = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__Urls = &tval + + } + } + + } + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_UserMentions: + + /* handler: uj.UserMentions type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.UserMentions = nil + } else { + + uj.UserMentions = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__UserMentions *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__UserMentions type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__UserMentions = nil + } else { + if tmp_uj__UserMentions == nil { + tmp_uj__UserMentions = new(string) + } + + /* handler: tmp_uj__UserMentions type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__UserMentions = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__UserMentions = &tval + + } + } + + } + } + + uj.UserMentions = append(uj.UserMentions, tmp_uj__UserMentions) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *Hashtag) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Hashtag) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"indices":`) + if mj.Indices != nil { + buf.WriteString(`[`) + for i, v := range mj.Indices { + if i != 0 { + buf.WriteString(`,`) + } + fflib.FormatBits2(buf, uint64(v), 10, v < 0) + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"text":`) + fflib.WriteJsonString(buf, string(mj.Text)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Hashtagbase = iota + ffj_t_Hashtagno_such_key + + ffj_t_Hashtag_Indices + + ffj_t_Hashtag_Text +) + +var ffj_key_Hashtag_Indices = []byte("indices") + +var ffj_key_Hashtag_Text = []byte("text") + +func (uj *Hashtag) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Hashtag) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Hashtagbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Hashtagno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'i': + + if bytes.Equal(ffj_key_Hashtag_Indices, kn) { + currentKey = ffj_t_Hashtag_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_Hashtag_Text, kn) { + currentKey = ffj_t_Hashtag_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_Hashtag_Text, kn) { + currentKey = ffj_t_Hashtag_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Hashtag_Indices, kn) { + currentKey = ffj_t_Hashtag_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Hashtagno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Hashtag_Indices: + goto handle_Indices + + case ffj_t_Hashtag_Text: + goto handle_Text + + case ffj_t_Hashtagno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Indices: + + /* handler: uj.Indices type=[]int kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Indices = nil + } else { + + uj.Indices = make([]int, 0) + + wantVal := true + + for { + + var tmp_uj__Indices int + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Indices type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + tmp_uj__Indices = int(tval) + + } + } + + uj.Indices = append(uj.Indices, tmp_uj__Indices) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Text: + + /* handler: uj.Text type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Text = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *LargeStruct) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *LargeStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"search_metadata":`) + + { + + err = mj.SearchMetadata.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"statuses":`) + if mj.Statuses != nil { + buf.WriteString(`[`) + for i, v := range mj.Statuses { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_LargeStructbase = iota + ffj_t_LargeStructno_such_key + + ffj_t_LargeStruct_SearchMetadata + + ffj_t_LargeStruct_Statuses +) + +var ffj_key_LargeStruct_SearchMetadata = []byte("search_metadata") + +var ffj_key_LargeStruct_Statuses = []byte("statuses") + +func (uj *LargeStruct) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *LargeStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_LargeStructbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_LargeStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 's': + + if bytes.Equal(ffj_key_LargeStruct_SearchMetadata, kn) { + currentKey = ffj_t_LargeStruct_SearchMetadata + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_LargeStruct_Statuses, kn) { + currentKey = ffj_t_LargeStruct_Statuses + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_LargeStruct_Statuses, kn) { + currentKey = ffj_t_LargeStruct_Statuses + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_LargeStruct_SearchMetadata, kn) { + currentKey = ffj_t_LargeStruct_SearchMetadata + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_LargeStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_LargeStruct_SearchMetadata: + goto handle_SearchMetadata + + case ffj_t_LargeStruct_Statuses: + goto handle_Statuses + + case ffj_t_LargeStructno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_SearchMetadata: + + /* handler: uj.SearchMetadata type=benchmark.SearchMetadata kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.SearchMetadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Statuses: + + /* handler: uj.Statuses type=[]benchmark.Status kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Statuses = nil + } else { + + uj.Statuses = make([]Status, 0) + + wantVal := true + + for { + + var tmp_uj__Statuses Status + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Statuses type=benchmark.Status kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Statuses.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Statuses = append(uj.Statuses, tmp_uj__Statuses) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *SearchMetadata) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *SearchMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"completed_in":`) + fflib.AppendFloat(buf, float64(mj.CompletedIn), 'g', -1, 64) + buf.WriteString(`,"count":`) + fflib.FormatBits2(buf, uint64(mj.Count), 10, mj.Count < 0) + buf.WriteString(`,"max_id":`) + fflib.FormatBits2(buf, uint64(mj.MaxID), 10, mj.MaxID < 0) + buf.WriteString(`,"max_id_str":`) + fflib.WriteJsonString(buf, string(mj.MaxIDStr)) + buf.WriteString(`,"next_results":`) + fflib.WriteJsonString(buf, string(mj.NextResults)) + buf.WriteString(`,"query":`) + fflib.WriteJsonString(buf, string(mj.Query)) + buf.WriteString(`,"refresh_url":`) + fflib.WriteJsonString(buf, string(mj.RefreshURL)) + buf.WriteString(`,"since_id":`) + fflib.FormatBits2(buf, uint64(mj.SinceID), 10, mj.SinceID < 0) + buf.WriteString(`,"since_id_str":`) + fflib.WriteJsonString(buf, string(mj.SinceIDStr)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_SearchMetadatabase = iota + ffj_t_SearchMetadatano_such_key + + ffj_t_SearchMetadata_CompletedIn + + ffj_t_SearchMetadata_Count + + ffj_t_SearchMetadata_MaxID + + ffj_t_SearchMetadata_MaxIDStr + + ffj_t_SearchMetadata_NextResults + + ffj_t_SearchMetadata_Query + + ffj_t_SearchMetadata_RefreshURL + + ffj_t_SearchMetadata_SinceID + + ffj_t_SearchMetadata_SinceIDStr +) + +var ffj_key_SearchMetadata_CompletedIn = []byte("completed_in") + +var ffj_key_SearchMetadata_Count = []byte("count") + +var ffj_key_SearchMetadata_MaxID = []byte("max_id") + +var ffj_key_SearchMetadata_MaxIDStr = []byte("max_id_str") + +var ffj_key_SearchMetadata_NextResults = []byte("next_results") + +var ffj_key_SearchMetadata_Query = []byte("query") + +var ffj_key_SearchMetadata_RefreshURL = []byte("refresh_url") + +var ffj_key_SearchMetadata_SinceID = []byte("since_id") + +var ffj_key_SearchMetadata_SinceIDStr = []byte("since_id_str") + +func (uj *SearchMetadata) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *SearchMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_SearchMetadatabase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_SearchMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_SearchMetadata_CompletedIn, kn) { + currentKey = ffj_t_SearchMetadata_CompletedIn + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_Count, kn) { + currentKey = ffj_t_SearchMetadata_Count + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'm': + + if bytes.Equal(ffj_key_SearchMetadata_MaxID, kn) { + currentKey = ffj_t_SearchMetadata_MaxID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_MaxIDStr, kn) { + currentKey = ffj_t_SearchMetadata_MaxIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'n': + + if bytes.Equal(ffj_key_SearchMetadata_NextResults, kn) { + currentKey = ffj_t_SearchMetadata_NextResults + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'q': + + if bytes.Equal(ffj_key_SearchMetadata_Query, kn) { + currentKey = ffj_t_SearchMetadata_Query + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_SearchMetadata_RefreshURL, kn) { + currentKey = ffj_t_SearchMetadata_RefreshURL + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_SearchMetadata_SinceID, kn) { + currentKey = ffj_t_SearchMetadata_SinceID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_SinceIDStr, kn) { + currentKey = ffj_t_SearchMetadata_SinceIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_SinceIDStr, kn) { + currentKey = ffj_t_SearchMetadata_SinceIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_SinceID, kn) { + currentKey = ffj_t_SearchMetadata_SinceID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_RefreshURL, kn) { + currentKey = ffj_t_SearchMetadata_RefreshURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_SearchMetadata_Query, kn) { + currentKey = ffj_t_SearchMetadata_Query + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_NextResults, kn) { + currentKey = ffj_t_SearchMetadata_NextResults + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_MaxIDStr, kn) { + currentKey = ffj_t_SearchMetadata_MaxIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_SearchMetadata_MaxID, kn) { + currentKey = ffj_t_SearchMetadata_MaxID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_SearchMetadata_Count, kn) { + currentKey = ffj_t_SearchMetadata_Count + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_SearchMetadata_CompletedIn, kn) { + currentKey = ffj_t_SearchMetadata_CompletedIn + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_SearchMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_SearchMetadata_CompletedIn: + goto handle_CompletedIn + + case ffj_t_SearchMetadata_Count: + goto handle_Count + + case ffj_t_SearchMetadata_MaxID: + goto handle_MaxID + + case ffj_t_SearchMetadata_MaxIDStr: + goto handle_MaxIDStr + + case ffj_t_SearchMetadata_NextResults: + goto handle_NextResults + + case ffj_t_SearchMetadata_Query: + goto handle_Query + + case ffj_t_SearchMetadata_RefreshURL: + goto handle_RefreshURL + + case ffj_t_SearchMetadata_SinceID: + goto handle_SinceID + + case ffj_t_SearchMetadata_SinceIDStr: + goto handle_SinceIDStr + + case ffj_t_SearchMetadatano_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_CompletedIn: + + /* handler: uj.CompletedIn type=float64 kind=float64 quoted=false*/ + + { + if tok != fflib.FFTok_double && tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for float64", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseFloat(fs.Output.Bytes(), 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.CompletedIn = float64(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Count: + + /* handler: uj.Count type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.Count = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_MaxID: + + /* handler: uj.MaxID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.MaxID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_MaxIDStr: + + /* handler: uj.MaxIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.MaxIDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_NextResults: + + /* handler: uj.NextResults type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.NextResults = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Query: + + /* handler: uj.Query type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Query = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_RefreshURL: + + /* handler: uj.RefreshURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.RefreshURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_SinceID: + + /* handler: uj.SinceID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.SinceID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_SinceIDStr: + + /* handler: uj.SinceIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.SinceIDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *Status) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Status) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.Contributors != nil { + buf.WriteString(`{"contributors":`) + fflib.WriteJsonString(buf, string(*mj.Contributors)) + } else { + buf.WriteString(`{"contributors":null`) + } + if mj.Coordinates != nil { + buf.WriteString(`,"coordinates":`) + fflib.WriteJsonString(buf, string(*mj.Coordinates)) + } else { + buf.WriteString(`,"coordinates":null`) + } + buf.WriteString(`,"created_at":`) + fflib.WriteJsonString(buf, string(mj.CreatedAt)) + buf.WriteString(`,"entities":`) + + { + + err = mj.Entities.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + if mj.Favorited { + buf.WriteString(`,"favorited":true`) + } else { + buf.WriteString(`,"favorited":false`) + } + if mj.Geo != nil { + buf.WriteString(`,"geo":`) + fflib.WriteJsonString(buf, string(*mj.Geo)) + } else { + buf.WriteString(`,"geo":null`) + } + buf.WriteString(`,"id":`) + fflib.FormatBits2(buf, uint64(mj.ID), 10, mj.ID < 0) + buf.WriteString(`,"id_str":`) + fflib.WriteJsonString(buf, string(mj.IDStr)) + if mj.InReplyToScreenName != nil { + buf.WriteString(`,"in_reply_to_screen_name":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToScreenName)) + } else { + buf.WriteString(`,"in_reply_to_screen_name":null`) + } + if mj.InReplyToStatusID != nil { + buf.WriteString(`,"in_reply_to_status_id":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToStatusID)) + } else { + buf.WriteString(`,"in_reply_to_status_id":null`) + } + if mj.InReplyToStatusIDStr != nil { + buf.WriteString(`,"in_reply_to_status_id_str":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToStatusIDStr)) + } else { + buf.WriteString(`,"in_reply_to_status_id_str":null`) + } + if mj.InReplyToUserID != nil { + buf.WriteString(`,"in_reply_to_user_id":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToUserID)) + } else { + buf.WriteString(`,"in_reply_to_user_id":null`) + } + if mj.InReplyToUserIDStr != nil { + buf.WriteString(`,"in_reply_to_user_id_str":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToUserIDStr)) + } else { + buf.WriteString(`,"in_reply_to_user_id_str":null`) + } + buf.WriteString(`,"metadata":`) + + { + + err = mj.Metadata.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + if mj.Place != nil { + buf.WriteString(`,"place":`) + fflib.WriteJsonString(buf, string(*mj.Place)) + } else { + buf.WriteString(`,"place":null`) + } + buf.WriteString(`,"retweet_count":`) + fflib.FormatBits2(buf, uint64(mj.RetweetCount), 10, mj.RetweetCount < 0) + if mj.Retweeted { + buf.WriteString(`,"retweeted":true`) + } else { + buf.WriteString(`,"retweeted":false`) + } + buf.WriteString(`,"source":`) + fflib.WriteJsonString(buf, string(mj.Source)) + buf.WriteString(`,"text":`) + fflib.WriteJsonString(buf, string(mj.Text)) + if mj.Truncated { + buf.WriteString(`,"truncated":true`) + } else { + buf.WriteString(`,"truncated":false`) + } + buf.WriteString(`,"user":`) + + { + + err = mj.User.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Statusbase = iota + ffj_t_Statusno_such_key + + ffj_t_Status_Contributors + + ffj_t_Status_Coordinates + + ffj_t_Status_CreatedAt + + ffj_t_Status_Entities + + ffj_t_Status_Favorited + + ffj_t_Status_Geo + + ffj_t_Status_ID + + ffj_t_Status_IDStr + + ffj_t_Status_InReplyToScreenName + + ffj_t_Status_InReplyToStatusID + + ffj_t_Status_InReplyToStatusIDStr + + ffj_t_Status_InReplyToUserID + + ffj_t_Status_InReplyToUserIDStr + + ffj_t_Status_Metadata + + ffj_t_Status_Place + + ffj_t_Status_RetweetCount + + ffj_t_Status_Retweeted + + ffj_t_Status_Source + + ffj_t_Status_Text + + ffj_t_Status_Truncated + + ffj_t_Status_User +) + +var ffj_key_Status_Contributors = []byte("contributors") + +var ffj_key_Status_Coordinates = []byte("coordinates") + +var ffj_key_Status_CreatedAt = []byte("created_at") + +var ffj_key_Status_Entities = []byte("entities") + +var ffj_key_Status_Favorited = []byte("favorited") + +var ffj_key_Status_Geo = []byte("geo") + +var ffj_key_Status_ID = []byte("id") + +var ffj_key_Status_IDStr = []byte("id_str") + +var ffj_key_Status_InReplyToScreenName = []byte("in_reply_to_screen_name") + +var ffj_key_Status_InReplyToStatusID = []byte("in_reply_to_status_id") + +var ffj_key_Status_InReplyToStatusIDStr = []byte("in_reply_to_status_id_str") + +var ffj_key_Status_InReplyToUserID = []byte("in_reply_to_user_id") + +var ffj_key_Status_InReplyToUserIDStr = []byte("in_reply_to_user_id_str") + +var ffj_key_Status_Metadata = []byte("metadata") + +var ffj_key_Status_Place = []byte("place") + +var ffj_key_Status_RetweetCount = []byte("retweet_count") + +var ffj_key_Status_Retweeted = []byte("retweeted") + +var ffj_key_Status_Source = []byte("source") + +var ffj_key_Status_Text = []byte("text") + +var ffj_key_Status_Truncated = []byte("truncated") + +var ffj_key_Status_User = []byte("user") + +func (uj *Status) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Status) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Statusbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Statusno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_Status_Contributors, kn) { + currentKey = ffj_t_Status_Contributors + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Coordinates, kn) { + currentKey = ffj_t_Status_Coordinates + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_CreatedAt, kn) { + currentKey = ffj_t_Status_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'e': + + if bytes.Equal(ffj_key_Status_Entities, kn) { + currentKey = ffj_t_Status_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'f': + + if bytes.Equal(ffj_key_Status_Favorited, kn) { + currentKey = ffj_t_Status_Favorited + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'g': + + if bytes.Equal(ffj_key_Status_Geo, kn) { + currentKey = ffj_t_Status_Geo + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_Status_ID, kn) { + currentKey = ffj_t_Status_ID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_IDStr, kn) { + currentKey = ffj_t_Status_IDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToScreenName, kn) { + currentKey = ffj_t_Status_InReplyToScreenName + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToStatusID, kn) { + currentKey = ffj_t_Status_InReplyToStatusID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToStatusIDStr, kn) { + currentKey = ffj_t_Status_InReplyToStatusIDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToUserID, kn) { + currentKey = ffj_t_Status_InReplyToUserID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToUserIDStr, kn) { + currentKey = ffj_t_Status_InReplyToUserIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'm': + + if bytes.Equal(ffj_key_Status_Metadata, kn) { + currentKey = ffj_t_Status_Metadata + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'p': + + if bytes.Equal(ffj_key_Status_Place, kn) { + currentKey = ffj_t_Status_Place + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_Status_RetweetCount, kn) { + currentKey = ffj_t_Status_RetweetCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Retweeted, kn) { + currentKey = ffj_t_Status_Retweeted + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_Status_Source, kn) { + currentKey = ffj_t_Status_Source + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_Status_Text, kn) { + currentKey = ffj_t_Status_Text + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Truncated, kn) { + currentKey = ffj_t_Status_Truncated + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_Status_User, kn) { + currentKey = ffj_t_Status_User + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_Status_User, kn) { + currentKey = ffj_t_Status_User + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Truncated, kn) { + currentKey = ffj_t_Status_Truncated + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Text, kn) { + currentKey = ffj_t_Status_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Source, kn) { + currentKey = ffj_t_Status_Source + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Retweeted, kn) { + currentKey = ffj_t_Status_Retweeted + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_Status_RetweetCount, kn) { + currentKey = ffj_t_Status_RetweetCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Place, kn) { + currentKey = ffj_t_Status_Place + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Metadata, kn) { + currentKey = ffj_t_Status_Metadata + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToUserIDStr, kn) { + currentKey = ffj_t_Status_InReplyToUserIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToUserID, kn) { + currentKey = ffj_t_Status_InReplyToUserID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToStatusIDStr, kn) { + currentKey = ffj_t_Status_InReplyToStatusIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToStatusID, kn) { + currentKey = ffj_t_Status_InReplyToStatusID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToScreenName, kn) { + currentKey = ffj_t_Status_InReplyToScreenName + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_IDStr, kn) { + currentKey = ffj_t_Status_IDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_ID, kn) { + currentKey = ffj_t_Status_ID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Geo, kn) { + currentKey = ffj_t_Status_Geo + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Favorited, kn) { + currentKey = ffj_t_Status_Favorited + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Entities, kn) { + currentKey = ffj_t_Status_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_Status_CreatedAt, kn) { + currentKey = ffj_t_Status_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Coordinates, kn) { + currentKey = ffj_t_Status_Coordinates + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Contributors, kn) { + currentKey = ffj_t_Status_Contributors + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Statusno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Status_Contributors: + goto handle_Contributors + + case ffj_t_Status_Coordinates: + goto handle_Coordinates + + case ffj_t_Status_CreatedAt: + goto handle_CreatedAt + + case ffj_t_Status_Entities: + goto handle_Entities + + case ffj_t_Status_Favorited: + goto handle_Favorited + + case ffj_t_Status_Geo: + goto handle_Geo + + case ffj_t_Status_ID: + goto handle_ID + + case ffj_t_Status_IDStr: + goto handle_IDStr + + case ffj_t_Status_InReplyToScreenName: + goto handle_InReplyToScreenName + + case ffj_t_Status_InReplyToStatusID: + goto handle_InReplyToStatusID + + case ffj_t_Status_InReplyToStatusIDStr: + goto handle_InReplyToStatusIDStr + + case ffj_t_Status_InReplyToUserID: + goto handle_InReplyToUserID + + case ffj_t_Status_InReplyToUserIDStr: + goto handle_InReplyToUserIDStr + + case ffj_t_Status_Metadata: + goto handle_Metadata + + case ffj_t_Status_Place: + goto handle_Place + + case ffj_t_Status_RetweetCount: + goto handle_RetweetCount + + case ffj_t_Status_Retweeted: + goto handle_Retweeted + + case ffj_t_Status_Source: + goto handle_Source + + case ffj_t_Status_Text: + goto handle_Text + + case ffj_t_Status_Truncated: + goto handle_Truncated + + case ffj_t_Status_User: + goto handle_User + + case ffj_t_Statusno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Contributors: + + /* handler: uj.Contributors type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Contributors = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Contributors = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Coordinates: + + /* handler: uj.Coordinates type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Coordinates = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Coordinates = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_CreatedAt: + + /* handler: uj.CreatedAt type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.CreatedAt = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Entities: + + /* handler: uj.Entities type=benchmark.Entities kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Favorited: + + /* handler: uj.Favorited type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Favorited = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Favorited = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Geo: + + /* handler: uj.Geo type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Geo = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Geo = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ID: + + /* handler: uj.ID type=int64 kind=int64 quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int64", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ID = int64(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IDStr: + + /* handler: uj.IDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToScreenName: + + /* handler: uj.InReplyToScreenName type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToScreenName = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToScreenName = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToStatusID: + + /* handler: uj.InReplyToStatusID type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToStatusID = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToStatusID = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToStatusIDStr: + + /* handler: uj.InReplyToStatusIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToStatusIDStr = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToStatusIDStr = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToUserID: + + /* handler: uj.InReplyToUserID type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToUserID = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToUserID = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToUserIDStr: + + /* handler: uj.InReplyToUserIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToUserIDStr = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToUserIDStr = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Metadata: + + /* handler: uj.Metadata type=benchmark.StatusMetadata kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Metadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Place: + + /* handler: uj.Place type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Place = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Place = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_RetweetCount: + + /* handler: uj.RetweetCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.RetweetCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Retweeted: + + /* handler: uj.Retweeted type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Retweeted = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Retweeted = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Source: + + /* handler: uj.Source type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Source = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Text: + + /* handler: uj.Text type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Text = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Truncated: + + /* handler: uj.Truncated type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Truncated = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Truncated = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_User: + + /* handler: uj.User type=benchmark.User kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.User.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *StatusMetadata) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *StatusMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"iso_language_code":`) + fflib.WriteJsonString(buf, string(mj.IsoLanguageCode)) + buf.WriteString(`,"result_type":`) + fflib.WriteJsonString(buf, string(mj.ResultType)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_StatusMetadatabase = iota + ffj_t_StatusMetadatano_such_key + + ffj_t_StatusMetadata_IsoLanguageCode + + ffj_t_StatusMetadata_ResultType +) + +var ffj_key_StatusMetadata_IsoLanguageCode = []byte("iso_language_code") + +var ffj_key_StatusMetadata_ResultType = []byte("result_type") + +func (uj *StatusMetadata) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *StatusMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_StatusMetadatabase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_StatusMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'i': + + if bytes.Equal(ffj_key_StatusMetadata_IsoLanguageCode, kn) { + currentKey = ffj_t_StatusMetadata_IsoLanguageCode + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_StatusMetadata_ResultType, kn) { + currentKey = ffj_t_StatusMetadata_ResultType + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_StatusMetadata_ResultType, kn) { + currentKey = ffj_t_StatusMetadata_ResultType + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_StatusMetadata_IsoLanguageCode, kn) { + currentKey = ffj_t_StatusMetadata_IsoLanguageCode + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_StatusMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_StatusMetadata_IsoLanguageCode: + goto handle_IsoLanguageCode + + case ffj_t_StatusMetadata_ResultType: + goto handle_ResultType + + case ffj_t_StatusMetadatano_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_IsoLanguageCode: + + /* handler: uj.IsoLanguageCode type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IsoLanguageCode = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ResultType: + + /* handler: uj.ResultType type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ResultType = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *URL) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *URL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.ExpandedURL != nil { + buf.WriteString(`{"expanded_url":`) + fflib.WriteJsonString(buf, string(*mj.ExpandedURL)) + } else { + buf.WriteString(`{"expanded_url":null`) + } + buf.WriteString(`,"indices":`) + if mj.Indices != nil { + buf.WriteString(`[`) + for i, v := range mj.Indices { + if i != 0 { + buf.WriteString(`,`) + } + fflib.FormatBits2(buf, uint64(v), 10, v < 0) + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"url":`) + fflib.WriteJsonString(buf, string(mj.URL)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_URLbase = iota + ffj_t_URLno_such_key + + ffj_t_URL_ExpandedURL + + ffj_t_URL_Indices + + ffj_t_URL_URL +) + +var ffj_key_URL_ExpandedURL = []byte("expanded_url") + +var ffj_key_URL_Indices = []byte("indices") + +var ffj_key_URL_URL = []byte("url") + +func (uj *URL) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *URL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_URLbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_URLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'e': + + if bytes.Equal(ffj_key_URL_ExpandedURL, kn) { + currentKey = ffj_t_URL_ExpandedURL + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_URL_Indices, kn) { + currentKey = ffj_t_URL_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_URL_URL, kn) { + currentKey = ffj_t_URL_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_URL_URL, kn) { + currentKey = ffj_t_URL_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_URL_Indices, kn) { + currentKey = ffj_t_URL_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_URL_ExpandedURL, kn) { + currentKey = ffj_t_URL_ExpandedURL + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_URLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_URL_ExpandedURL: + goto handle_ExpandedURL + + case ffj_t_URL_Indices: + goto handle_Indices + + case ffj_t_URL_URL: + goto handle_URL + + case ffj_t_URLno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_ExpandedURL: + + /* handler: uj.ExpandedURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.ExpandedURL = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.ExpandedURL = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Indices: + + /* handler: uj.Indices type=[]int kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Indices = nil + } else { + + uj.Indices = make([]int, 0) + + wantVal := true + + for { + + var tmp_uj__Indices int + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Indices type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + tmp_uj__Indices = int(tval) + + } + } + + uj.Indices = append(uj.Indices, tmp_uj__Indices) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.URL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *User) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *User) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.ContributorsEnabled { + buf.WriteString(`{"contributors_enabled":true`) + } else { + buf.WriteString(`{"contributors_enabled":false`) + } + buf.WriteString(`,"created_at":`) + fflib.WriteJsonString(buf, string(mj.CreatedAt)) + if mj.DefaultProfile { + buf.WriteString(`,"default_profile":true`) + } else { + buf.WriteString(`,"default_profile":false`) + } + if mj.DefaultProfileImage { + buf.WriteString(`,"default_profile_image":true`) + } else { + buf.WriteString(`,"default_profile_image":false`) + } + buf.WriteString(`,"description":`) + fflib.WriteJsonString(buf, string(mj.Description)) + buf.WriteString(`,"entities":`) + + { + + err = mj.Entities.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"favourites_count":`) + fflib.FormatBits2(buf, uint64(mj.FavouritesCount), 10, mj.FavouritesCount < 0) + if mj.FollowRequestSent != nil { + buf.WriteString(`,"follow_request_sent":`) + fflib.WriteJsonString(buf, string(*mj.FollowRequestSent)) + } else { + buf.WriteString(`,"follow_request_sent":null`) + } + buf.WriteString(`,"followers_count":`) + fflib.FormatBits2(buf, uint64(mj.FollowersCount), 10, mj.FollowersCount < 0) + if mj.Following != nil { + buf.WriteString(`,"following":`) + fflib.WriteJsonString(buf, string(*mj.Following)) + } else { + buf.WriteString(`,"following":null`) + } + buf.WriteString(`,"friends_count":`) + fflib.FormatBits2(buf, uint64(mj.FriendsCount), 10, mj.FriendsCount < 0) + if mj.GeoEnabled { + buf.WriteString(`,"geo_enabled":true`) + } else { + buf.WriteString(`,"geo_enabled":false`) + } + buf.WriteString(`,"id":`) + fflib.FormatBits2(buf, uint64(mj.ID), 10, mj.ID < 0) + buf.WriteString(`,"id_str":`) + fflib.WriteJsonString(buf, string(mj.IDStr)) + if mj.IsTranslator { + buf.WriteString(`,"is_translator":true`) + } else { + buf.WriteString(`,"is_translator":false`) + } + buf.WriteString(`,"lang":`) + fflib.WriteJsonString(buf, string(mj.Lang)) + buf.WriteString(`,"listed_count":`) + fflib.FormatBits2(buf, uint64(mj.ListedCount), 10, mj.ListedCount < 0) + buf.WriteString(`,"location":`) + fflib.WriteJsonString(buf, string(mj.Location)) + buf.WriteString(`,"name":`) + fflib.WriteJsonString(buf, string(mj.Name)) + if mj.Notifications != nil { + buf.WriteString(`,"notifications":`) + fflib.WriteJsonString(buf, string(*mj.Notifications)) + } else { + buf.WriteString(`,"notifications":null`) + } + buf.WriteString(`,"profile_background_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundColor)) + buf.WriteString(`,"profile_background_image_url":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundImageURL)) + buf.WriteString(`,"profile_background_image_url_https":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundImageURLHTTPS)) + if mj.ProfileBackgroundTile { + buf.WriteString(`,"profile_background_tile":true`) + } else { + buf.WriteString(`,"profile_background_tile":false`) + } + buf.WriteString(`,"profile_image_url":`) + fflib.WriteJsonString(buf, string(mj.ProfileImageURL)) + buf.WriteString(`,"profile_image_url_https":`) + fflib.WriteJsonString(buf, string(mj.ProfileImageURLHTTPS)) + buf.WriteString(`,"profile_link_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileLinkColor)) + buf.WriteString(`,"profile_sidebar_border_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileSidebarBorderColor)) + buf.WriteString(`,"profile_sidebar_fill_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileSidebarFillColor)) + buf.WriteString(`,"profile_text_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileTextColor)) + if mj.ProfileUseBackgroundImage { + buf.WriteString(`,"profile_use_background_image":true`) + } else { + buf.WriteString(`,"profile_use_background_image":false`) + } + if mj.Protected { + buf.WriteString(`,"protected":true`) + } else { + buf.WriteString(`,"protected":false`) + } + buf.WriteString(`,"screen_name":`) + fflib.WriteJsonString(buf, string(mj.ScreenName)) + if mj.ShowAllInlineMedia { + buf.WriteString(`,"show_all_inline_media":true`) + } else { + buf.WriteString(`,"show_all_inline_media":false`) + } + buf.WriteString(`,"statuses_count":`) + fflib.FormatBits2(buf, uint64(mj.StatusesCount), 10, mj.StatusesCount < 0) + buf.WriteString(`,"time_zone":`) + fflib.WriteJsonString(buf, string(mj.TimeZone)) + if mj.URL != nil { + buf.WriteString(`,"url":`) + fflib.WriteJsonString(buf, string(*mj.URL)) + } else { + buf.WriteString(`,"url":null`) + } + buf.WriteString(`,"utc_offset":`) + fflib.FormatBits2(buf, uint64(mj.UtcOffset), 10, mj.UtcOffset < 0) + if mj.Verified { + buf.WriteString(`,"verified":true`) + } else { + buf.WriteString(`,"verified":false`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Userbase = iota + ffj_t_Userno_such_key + + ffj_t_User_ContributorsEnabled + + ffj_t_User_CreatedAt + + ffj_t_User_DefaultProfile + + ffj_t_User_DefaultProfileImage + + ffj_t_User_Description + + ffj_t_User_Entities + + ffj_t_User_FavouritesCount + + ffj_t_User_FollowRequestSent + + ffj_t_User_FollowersCount + + ffj_t_User_Following + + ffj_t_User_FriendsCount + + ffj_t_User_GeoEnabled + + ffj_t_User_ID + + ffj_t_User_IDStr + + ffj_t_User_IsTranslator + + ffj_t_User_Lang + + ffj_t_User_ListedCount + + ffj_t_User_Location + + ffj_t_User_Name + + ffj_t_User_Notifications + + ffj_t_User_ProfileBackgroundColor + + ffj_t_User_ProfileBackgroundImageURL + + ffj_t_User_ProfileBackgroundImageURLHTTPS + + ffj_t_User_ProfileBackgroundTile + + ffj_t_User_ProfileImageURL + + ffj_t_User_ProfileImageURLHTTPS + + ffj_t_User_ProfileLinkColor + + ffj_t_User_ProfileSidebarBorderColor + + ffj_t_User_ProfileSidebarFillColor + + ffj_t_User_ProfileTextColor + + ffj_t_User_ProfileUseBackgroundImage + + ffj_t_User_Protected + + ffj_t_User_ScreenName + + ffj_t_User_ShowAllInlineMedia + + ffj_t_User_StatusesCount + + ffj_t_User_TimeZone + + ffj_t_User_URL + + ffj_t_User_UtcOffset + + ffj_t_User_Verified +) + +var ffj_key_User_ContributorsEnabled = []byte("contributors_enabled") + +var ffj_key_User_CreatedAt = []byte("created_at") + +var ffj_key_User_DefaultProfile = []byte("default_profile") + +var ffj_key_User_DefaultProfileImage = []byte("default_profile_image") + +var ffj_key_User_Description = []byte("description") + +var ffj_key_User_Entities = []byte("entities") + +var ffj_key_User_FavouritesCount = []byte("favourites_count") + +var ffj_key_User_FollowRequestSent = []byte("follow_request_sent") + +var ffj_key_User_FollowersCount = []byte("followers_count") + +var ffj_key_User_Following = []byte("following") + +var ffj_key_User_FriendsCount = []byte("friends_count") + +var ffj_key_User_GeoEnabled = []byte("geo_enabled") + +var ffj_key_User_ID = []byte("id") + +var ffj_key_User_IDStr = []byte("id_str") + +var ffj_key_User_IsTranslator = []byte("is_translator") + +var ffj_key_User_Lang = []byte("lang") + +var ffj_key_User_ListedCount = []byte("listed_count") + +var ffj_key_User_Location = []byte("location") + +var ffj_key_User_Name = []byte("name") + +var ffj_key_User_Notifications = []byte("notifications") + +var ffj_key_User_ProfileBackgroundColor = []byte("profile_background_color") + +var ffj_key_User_ProfileBackgroundImageURL = []byte("profile_background_image_url") + +var ffj_key_User_ProfileBackgroundImageURLHTTPS = []byte("profile_background_image_url_https") + +var ffj_key_User_ProfileBackgroundTile = []byte("profile_background_tile") + +var ffj_key_User_ProfileImageURL = []byte("profile_image_url") + +var ffj_key_User_ProfileImageURLHTTPS = []byte("profile_image_url_https") + +var ffj_key_User_ProfileLinkColor = []byte("profile_link_color") + +var ffj_key_User_ProfileSidebarBorderColor = []byte("profile_sidebar_border_color") + +var ffj_key_User_ProfileSidebarFillColor = []byte("profile_sidebar_fill_color") + +var ffj_key_User_ProfileTextColor = []byte("profile_text_color") + +var ffj_key_User_ProfileUseBackgroundImage = []byte("profile_use_background_image") + +var ffj_key_User_Protected = []byte("protected") + +var ffj_key_User_ScreenName = []byte("screen_name") + +var ffj_key_User_ShowAllInlineMedia = []byte("show_all_inline_media") + +var ffj_key_User_StatusesCount = []byte("statuses_count") + +var ffj_key_User_TimeZone = []byte("time_zone") + +var ffj_key_User_URL = []byte("url") + +var ffj_key_User_UtcOffset = []byte("utc_offset") + +var ffj_key_User_Verified = []byte("verified") + +func (uj *User) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *User) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Userbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Userno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_User_ContributorsEnabled, kn) { + currentKey = ffj_t_User_ContributorsEnabled + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_CreatedAt, kn) { + currentKey = ffj_t_User_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'd': + + if bytes.Equal(ffj_key_User_DefaultProfile, kn) { + currentKey = ffj_t_User_DefaultProfile + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_DefaultProfileImage, kn) { + currentKey = ffj_t_User_DefaultProfileImage + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Description, kn) { + currentKey = ffj_t_User_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'e': + + if bytes.Equal(ffj_key_User_Entities, kn) { + currentKey = ffj_t_User_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'f': + + if bytes.Equal(ffj_key_User_FavouritesCount, kn) { + currentKey = ffj_t_User_FavouritesCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FollowRequestSent, kn) { + currentKey = ffj_t_User_FollowRequestSent + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FollowersCount, kn) { + currentKey = ffj_t_User_FollowersCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Following, kn) { + currentKey = ffj_t_User_Following + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FriendsCount, kn) { + currentKey = ffj_t_User_FriendsCount + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'g': + + if bytes.Equal(ffj_key_User_GeoEnabled, kn) { + currentKey = ffj_t_User_GeoEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_User_ID, kn) { + currentKey = ffj_t_User_ID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_IDStr, kn) { + currentKey = ffj_t_User_IDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_IsTranslator, kn) { + currentKey = ffj_t_User_IsTranslator + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'l': + + if bytes.Equal(ffj_key_User_Lang, kn) { + currentKey = ffj_t_User_Lang + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ListedCount, kn) { + currentKey = ffj_t_User_ListedCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Location, kn) { + currentKey = ffj_t_User_Location + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'n': + + if bytes.Equal(ffj_key_User_Name, kn) { + currentKey = ffj_t_User_Name + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Notifications, kn) { + currentKey = ffj_t_User_Notifications + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'p': + + if bytes.Equal(ffj_key_User_ProfileBackgroundColor, kn) { + currentKey = ffj_t_User_ProfileBackgroundColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundImageURL, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundTile, kn) { + currentKey = ffj_t_User_ProfileBackgroundTile + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileImageURL, kn) { + currentKey = ffj_t_User_ProfileImageURL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileLinkColor, kn) { + currentKey = ffj_t_User_ProfileLinkColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileSidebarBorderColor, kn) { + currentKey = ffj_t_User_ProfileSidebarBorderColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileSidebarFillColor, kn) { + currentKey = ffj_t_User_ProfileSidebarFillColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileTextColor, kn) { + currentKey = ffj_t_User_ProfileTextColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileUseBackgroundImage, kn) { + currentKey = ffj_t_User_ProfileUseBackgroundImage + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Protected, kn) { + currentKey = ffj_t_User_Protected + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_User_ScreenName, kn) { + currentKey = ffj_t_User_ScreenName + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ShowAllInlineMedia, kn) { + currentKey = ffj_t_User_ShowAllInlineMedia + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_StatusesCount, kn) { + currentKey = ffj_t_User_StatusesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_User_TimeZone, kn) { + currentKey = ffj_t_User_TimeZone + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_User_URL, kn) { + currentKey = ffj_t_User_URL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_UtcOffset, kn) { + currentKey = ffj_t_User_UtcOffset + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'v': + + if bytes.Equal(ffj_key_User_Verified, kn) { + currentKey = ffj_t_User_Verified + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Verified, kn) { + currentKey = ffj_t_User_Verified + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_UtcOffset, kn) { + currentKey = ffj_t_User_UtcOffset + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_URL, kn) { + currentKey = ffj_t_User_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_TimeZone, kn) { + currentKey = ffj_t_User_TimeZone + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_StatusesCount, kn) { + currentKey = ffj_t_User_StatusesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ShowAllInlineMedia, kn) { + currentKey = ffj_t_User_ShowAllInlineMedia + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ScreenName, kn) { + currentKey = ffj_t_User_ScreenName + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Protected, kn) { + currentKey = ffj_t_User_Protected + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileUseBackgroundImage, kn) { + currentKey = ffj_t_User_ProfileUseBackgroundImage + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_ProfileTextColor, kn) { + currentKey = ffj_t_User_ProfileTextColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileSidebarFillColor, kn) { + currentKey = ffj_t_User_ProfileSidebarFillColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileSidebarBorderColor, kn) { + currentKey = ffj_t_User_ProfileSidebarBorderColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileLinkColor, kn) { + currentKey = ffj_t_User_ProfileLinkColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_ProfileImageURL, kn) { + currentKey = ffj_t_User_ProfileImageURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundTile, kn) { + currentKey = ffj_t_User_ProfileBackgroundTile + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundImageURL, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundColor, kn) { + currentKey = ffj_t_User_ProfileBackgroundColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Notifications, kn) { + currentKey = ffj_t_User_Notifications + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Name, kn) { + currentKey = ffj_t_User_Name + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Location, kn) { + currentKey = ffj_t_User_Location + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ListedCount, kn) { + currentKey = ffj_t_User_ListedCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Lang, kn) { + currentKey = ffj_t_User_Lang + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_IsTranslator, kn) { + currentKey = ffj_t_User_IsTranslator + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_IDStr, kn) { + currentKey = ffj_t_User_IDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_ID, kn) { + currentKey = ffj_t_User_ID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_GeoEnabled, kn) { + currentKey = ffj_t_User_GeoEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FriendsCount, kn) { + currentKey = ffj_t_User_FriendsCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Following, kn) { + currentKey = ffj_t_User_Following + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FollowersCount, kn) { + currentKey = ffj_t_User_FollowersCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FollowRequestSent, kn) { + currentKey = ffj_t_User_FollowRequestSent + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FavouritesCount, kn) { + currentKey = ffj_t_User_FavouritesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Entities, kn) { + currentKey = ffj_t_User_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Description, kn) { + currentKey = ffj_t_User_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_DefaultProfileImage, kn) { + currentKey = ffj_t_User_DefaultProfileImage + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_DefaultProfile, kn) { + currentKey = ffj_t_User_DefaultProfile + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_CreatedAt, kn) { + currentKey = ffj_t_User_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ContributorsEnabled, kn) { + currentKey = ffj_t_User_ContributorsEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Userno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_User_ContributorsEnabled: + goto handle_ContributorsEnabled + + case ffj_t_User_CreatedAt: + goto handle_CreatedAt + + case ffj_t_User_DefaultProfile: + goto handle_DefaultProfile + + case ffj_t_User_DefaultProfileImage: + goto handle_DefaultProfileImage + + case ffj_t_User_Description: + goto handle_Description + + case ffj_t_User_Entities: + goto handle_Entities + + case ffj_t_User_FavouritesCount: + goto handle_FavouritesCount + + case ffj_t_User_FollowRequestSent: + goto handle_FollowRequestSent + + case ffj_t_User_FollowersCount: + goto handle_FollowersCount + + case ffj_t_User_Following: + goto handle_Following + + case ffj_t_User_FriendsCount: + goto handle_FriendsCount + + case ffj_t_User_GeoEnabled: + goto handle_GeoEnabled + + case ffj_t_User_ID: + goto handle_ID + + case ffj_t_User_IDStr: + goto handle_IDStr + + case ffj_t_User_IsTranslator: + goto handle_IsTranslator + + case ffj_t_User_Lang: + goto handle_Lang + + case ffj_t_User_ListedCount: + goto handle_ListedCount + + case ffj_t_User_Location: + goto handle_Location + + case ffj_t_User_Name: + goto handle_Name + + case ffj_t_User_Notifications: + goto handle_Notifications + + case ffj_t_User_ProfileBackgroundColor: + goto handle_ProfileBackgroundColor + + case ffj_t_User_ProfileBackgroundImageURL: + goto handle_ProfileBackgroundImageURL + + case ffj_t_User_ProfileBackgroundImageURLHTTPS: + goto handle_ProfileBackgroundImageURLHTTPS + + case ffj_t_User_ProfileBackgroundTile: + goto handle_ProfileBackgroundTile + + case ffj_t_User_ProfileImageURL: + goto handle_ProfileImageURL + + case ffj_t_User_ProfileImageURLHTTPS: + goto handle_ProfileImageURLHTTPS + + case ffj_t_User_ProfileLinkColor: + goto handle_ProfileLinkColor + + case ffj_t_User_ProfileSidebarBorderColor: + goto handle_ProfileSidebarBorderColor + + case ffj_t_User_ProfileSidebarFillColor: + goto handle_ProfileSidebarFillColor + + case ffj_t_User_ProfileTextColor: + goto handle_ProfileTextColor + + case ffj_t_User_ProfileUseBackgroundImage: + goto handle_ProfileUseBackgroundImage + + case ffj_t_User_Protected: + goto handle_Protected + + case ffj_t_User_ScreenName: + goto handle_ScreenName + + case ffj_t_User_ShowAllInlineMedia: + goto handle_ShowAllInlineMedia + + case ffj_t_User_StatusesCount: + goto handle_StatusesCount + + case ffj_t_User_TimeZone: + goto handle_TimeZone + + case ffj_t_User_URL: + goto handle_URL + + case ffj_t_User_UtcOffset: + goto handle_UtcOffset + + case ffj_t_User_Verified: + goto handle_Verified + + case ffj_t_Userno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_ContributorsEnabled: + + /* handler: uj.ContributorsEnabled type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ContributorsEnabled = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ContributorsEnabled = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_CreatedAt: + + /* handler: uj.CreatedAt type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.CreatedAt = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_DefaultProfile: + + /* handler: uj.DefaultProfile type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.DefaultProfile = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.DefaultProfile = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_DefaultProfileImage: + + /* handler: uj.DefaultProfileImage type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.DefaultProfileImage = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.DefaultProfileImage = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Description: + + /* handler: uj.Description type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Description = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Entities: + + /* handler: uj.Entities type=benchmark.UserEntities kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FavouritesCount: + + /* handler: uj.FavouritesCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FavouritesCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FollowRequestSent: + + /* handler: uj.FollowRequestSent type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.FollowRequestSent = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.FollowRequestSent = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FollowersCount: + + /* handler: uj.FollowersCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FollowersCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Following: + + /* handler: uj.Following type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Following = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Following = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FriendsCount: + + /* handler: uj.FriendsCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FriendsCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_GeoEnabled: + + /* handler: uj.GeoEnabled type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.GeoEnabled = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.GeoEnabled = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ID: + + /* handler: uj.ID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IDStr: + + /* handler: uj.IDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IsTranslator: + + /* handler: uj.IsTranslator type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.IsTranslator = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.IsTranslator = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Lang: + + /* handler: uj.Lang type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Lang = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ListedCount: + + /* handler: uj.ListedCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ListedCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Location: + + /* handler: uj.Location type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Location = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Name: + + /* handler: uj.Name type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Name = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Notifications: + + /* handler: uj.Notifications type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Notifications = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Notifications = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundColor: + + /* handler: uj.ProfileBackgroundColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundImageURL: + + /* handler: uj.ProfileBackgroundImageURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundImageURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundImageURLHTTPS: + + /* handler: uj.ProfileBackgroundImageURLHTTPS type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundImageURLHTTPS = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundTile: + + /* handler: uj.ProfileBackgroundTile type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ProfileBackgroundTile = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ProfileBackgroundTile = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileImageURL: + + /* handler: uj.ProfileImageURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileImageURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileImageURLHTTPS: + + /* handler: uj.ProfileImageURLHTTPS type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileImageURLHTTPS = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileLinkColor: + + /* handler: uj.ProfileLinkColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileLinkColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileSidebarBorderColor: + + /* handler: uj.ProfileSidebarBorderColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileSidebarBorderColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileSidebarFillColor: + + /* handler: uj.ProfileSidebarFillColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileSidebarFillColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileTextColor: + + /* handler: uj.ProfileTextColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileTextColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileUseBackgroundImage: + + /* handler: uj.ProfileUseBackgroundImage type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ProfileUseBackgroundImage = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ProfileUseBackgroundImage = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Protected: + + /* handler: uj.Protected type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Protected = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Protected = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ScreenName: + + /* handler: uj.ScreenName type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ScreenName = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ShowAllInlineMedia: + + /* handler: uj.ShowAllInlineMedia type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ShowAllInlineMedia = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ShowAllInlineMedia = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_StatusesCount: + + /* handler: uj.StatusesCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.StatusesCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_TimeZone: + + /* handler: uj.TimeZone type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.TimeZone = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.URL = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.URL = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_UtcOffset: + + /* handler: uj.UtcOffset type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.UtcOffset = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Verified: + + /* handler: uj.Verified type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Verified = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Verified = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntities) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"description":`) + + { + + err = mj.Description.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"url":`) + + { + + err = mj.URL.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntitiesbase = iota + ffj_t_UserEntitiesno_such_key + + ffj_t_UserEntities_Description + + ffj_t_UserEntities_URL +) + +var ffj_key_UserEntities_Description = []byte("description") + +var ffj_key_UserEntities_URL = []byte("url") + +func (uj *UserEntities) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntitiesbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'd': + + if bytes.Equal(ffj_key_UserEntities_Description, kn) { + currentKey = ffj_t_UserEntities_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_UserEntities_URL, kn) { + currentKey = ffj_t_UserEntities_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_UserEntities_URL, kn) { + currentKey = ffj_t_UserEntities_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_UserEntities_Description, kn) { + currentKey = ffj_t_UserEntities_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntities_Description: + goto handle_Description + + case ffj_t_UserEntities_URL: + goto handle_URL + + case ffj_t_UserEntitiesno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Description: + + /* handler: uj.Description type=benchmark.UserEntityDescription kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Description.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=benchmark.UserEntityURL kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.URL.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntityDescription) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntityDescription) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntityDescriptionbase = iota + ffj_t_UserEntityDescriptionno_such_key + + ffj_t_UserEntityDescription_Urls +) + +var ffj_key_UserEntityDescription_Urls = []byte("urls") + +func (uj *UserEntityDescription) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntityDescription) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntityDescriptionbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntityDescriptionno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'u': + + if bytes.Equal(ffj_key_UserEntityDescription_Urls, kn) { + currentKey = ffj_t_UserEntityDescription_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_UserEntityDescription_Urls, kn) { + currentKey = ffj_t_UserEntityDescription_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntityDescriptionno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntityDescription_Urls: + goto handle_Urls + + case ffj_t_UserEntityDescriptionno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Urls: + + /* handler: uj.Urls type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__Urls *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__Urls = nil + } else { + if tmp_uj__Urls == nil { + tmp_uj__Urls = new(string) + } + + /* handler: tmp_uj__Urls type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__Urls = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__Urls = &tval + + } + } + + } + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntityURL) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntityURL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntityURLbase = iota + ffj_t_UserEntityURLno_such_key + + ffj_t_UserEntityURL_Urls +) + +var ffj_key_UserEntityURL_Urls = []byte("urls") + +func (uj *UserEntityURL) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntityURL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntityURLbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntityURLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'u': + + if bytes.Equal(ffj_key_UserEntityURL_Urls, kn) { + currentKey = ffj_t_UserEntityURL_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_UserEntityURL_Urls, kn) { + currentKey = ffj_t_UserEntityURL_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntityURLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntityURL_Urls: + goto handle_Urls + + case ffj_t_UserEntityURLno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Urls: + + /* handler: uj.Urls type=[]benchmark.URL kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]URL, 0) + + wantVal := true + + for { + + var tmp_uj__Urls URL + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=benchmark.URL kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Urls.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *XLStruct) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *XLStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"Data":`) + if mj.Data != nil { + buf.WriteString(`[`) + for i, v := range mj.Data { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_XLStructbase = iota + ffj_t_XLStructno_such_key + + ffj_t_XLStruct_Data +) + +var ffj_key_XLStruct_Data = []byte("Data") + +func (uj *XLStruct) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *XLStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_XLStructbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_XLStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'D': + + if bytes.Equal(ffj_key_XLStruct_Data, kn) { + currentKey = ffj_t_XLStruct_Data + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_XLStruct_Data, kn) { + currentKey = ffj_t_XLStruct_Data + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_XLStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_XLStruct_Data: + goto handle_Data + + case ffj_t_XLStructno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Data: + + /* handler: uj.Data type=[]benchmark.LargeStruct kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Data = nil + } else { + + uj.Data = make([]LargeStruct, 0) + + wantVal := true + + for { + + var tmp_uj__Data LargeStruct + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Data type=benchmark.LargeStruct kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Data.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Data = append(uj.Data, tmp_uj__Data) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/data_var.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_var.go new file mode 100644 index 000000000..ea4202dbe --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/data_var.go @@ -0,0 +1,350 @@ +package benchmark + +var largeStructData = LargeStruct{ + SearchMetadata: SearchMetadata{ + CompletedIn: 0.035, + Count: 4, + MaxID: 250126199840518145, + MaxIDStr: "250126199840518145", + NextResults: "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", + Query: "%23freebandnames", + RefreshURL: "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", + SinceID: 24012619984051000, + SinceIDStr: "24012619984051000", + }, + Statuses: []Status{ + { + Contributors: nil, + Coordinates: nil, + CreatedAt: "Mon Sep 24 03:35:21 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "freebandnames"}, + }, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 250075927172759552, + IDStr: "250075927172759552", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "Twitter for Mac", + Text: "Aggressive Ponytail #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Mon Apr 26 06:01:55 +0000 2010", + DefaultProfile: true, + DefaultProfileImage: false, + Description: "Born 330 Live 310", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: []*string{}, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 0}, + URL: "", + }}, + }, + }, + FavouritesCount: 0, + FollowRequestSent: nil, + FollowersCount: 70, + Following: nil, + FriendsCount: 110, + GeoEnabled: true, + ID: 137238150, + IDStr: "137238150", + IsTranslator: false, + Lang: "en", + ListedCount: 2, + Location: "LA, CA", + Name: "Sean Cummings", + Notifications: nil, + ProfileBackgroundColor: "C0DEED", + ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme1/bg.png", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme1/bg.png", + ProfileBackgroundTile: false, + ProfileImageURL: "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + ProfileLinkColor: "0084B4", + ProfileSidebarBorderColor: "C0DEED", + ProfileSidebarFillColor: "DDEEF6", + ProfileTextColor: "333333", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "sean_cummings", + ShowAllInlineMedia: false, + StatusesCount: 579, + TimeZone: "Pacific Time (US & Canada)", + URL: nil, + UtcOffset: -28800, + Verified: false, + }, + }, + { + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 23:40:54 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "FreeBandNames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249292149810667520, + IDStr: "249292149810667520", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "pl", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "web", + Text: "Thee Namaste Nerdz. #FreeBandNames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Tue Apr 07 19:05:07 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", + Entities: UserEntities{ + Description: UserEntityDescription{Urls: []*string{}}, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 32}, + URL: "http://bullcityrecords.com/wnng/"}}, + }, + }, + FavouritesCount: 8, + FollowRequestSent: nil, + FollowersCount: 2052, + Following: nil, + FriendsCount: 348, + GeoEnabled: false, + ID: 29516238, + IDStr: "29516238", + IsTranslator: false, + Lang: "en", + ListedCount: 118, + Location: "Durham, NC", + Name: "Chaz Martenstein", + Notifications: nil, + ProfileBackgroundColor: "9AE4E8", + ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", + ProfileBackgroundTile: true, + ProfileImageURL: "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + ProfileLinkColor: "0084B4", + ProfileSidebarBorderColor: "BDDCAD", + ProfileSidebarFillColor: "DDFFCC", + ProfileTextColor: "333333", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "bullcityrecords", + ShowAllInlineMedia: true, + StatusesCount: 7579, + TimeZone: "Eastern Time (US & Canada)", + URL: nil, + UtcOffset: -18000, + Verified: false, + }, + }, + Status{ + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 23:30:20 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{29, 43}, + Text: "freebandnames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249289491129438208, + IDStr: "249289491129438208", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "web", + Text: "Mexican Heaven, Mexican Hell #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Tue Sep 01 21:21:35 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: nil, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 0}, + URL: "", + }}, + }, + }, + FavouritesCount: 19, + FollowRequestSent: nil, + FollowersCount: 63, + Following: nil, + FriendsCount: 63, + GeoEnabled: false, + ID: 70789458, + IDStr: "70789458", + IsTranslator: false, + Lang: "en", + ListedCount: 1, + Location: "Kingston New York", + Name: "Thomas John Wakeman", + Notifications: nil, + ProfileBackgroundColor: "352726", + ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme5/bg.gif", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme5/bg.gif", + ProfileBackgroundTile: false, + ProfileImageURL: "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + ProfileLinkColor: "D02B55", + ProfileSidebarBorderColor: "829D5E", + ProfileSidebarFillColor: "99CC33", + ProfileTextColor: "3E4415", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "MonkiesFist", + ShowAllInlineMedia: false, + StatusesCount: 1048, + TimeZone: "Eastern Time (US & Canada)", + URL: nil, + UtcOffset: -18000, + Verified: false, + }, + }, + Status{ + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 22:51:18 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "freebandnames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249279667666817024, + IDStr: "249279667666817024", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "Twitter for iPhone", + Text: "The Foolish Mortals #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Mon May 04 00:05:00 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "Cartoonist, Illustrator, and T-Shirt connoisseur", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: []*string{}, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 24}, + URL: "http://www.omnitarian.me", + }}, + }, + }, + FavouritesCount: 647, + FollowRequestSent: nil, + FollowersCount: 608, + Following: nil, + FriendsCount: 249, + GeoEnabled: false, + ID: 37539828, + IDStr: "37539828", + IsTranslator: false, + Lang: "en", + ListedCount: 52, + Location: "Wisconsin, USA", + Name: "Marty Elmer", + Notifications: nil, + ProfileBackgroundColor: "EEE3C4", + ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", + ProfileBackgroundTile: true, + ProfileImageURL: "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + ProfileLinkColor: "3B2A26", + ProfileSidebarBorderColor: "615A44", + ProfileSidebarFillColor: "BFAC83", + ProfileTextColor: "000000", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "Omnitarian", + ShowAllInlineMedia: true, + StatusesCount: 3575, + TimeZone: "Central Time (US & Canada)", + URL: nil, + UtcOffset: -21600, + Verified: false, + }, + }, + }, +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/default_test.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/default_test.go new file mode 100644 index 000000000..b647bef23 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/default_test.go @@ -0,0 +1,118 @@ +// +build !use_easyjson,!use_ffjson,!use_codec + +package benchmark + +import ( + "encoding/json" + "testing" +) + +func BenchmarkStd_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := json.Unmarshal(largeStructText, &s) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkStd_Unmarshal_S(b *testing.B) { + for i := 0; i < b.N; i++ { + var s Entities + err := json.Unmarshal(smallStructText, &s) + if err != nil { + b.Error(err) + } + } + b.SetBytes(int64(len(smallStructText))) +} + +func BenchmarkStd_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_M_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_M_ToWriter(b *testing.B) { + enc := json.NewEncoder(&DummyWriter{}) + for i := 0; i < b.N; i++ { + err := enc.Encode(&largeStructData) + if err != nil { + b.Error(err) + } + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go new file mode 100644 index 000000000..3d928ca7c --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go @@ -0,0 +1,11 @@ +package benchmark + +import ( + "testing" +) + +type DummyWriter struct{} + +func (w DummyWriter) Write(data []byte) (int, error) { return len(data), nil } + +func TestToSuppressNoTestsWarning(t *testing.T) {} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go new file mode 100644 index 000000000..16b670b27 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go @@ -0,0 +1,184 @@ +// +build use_easyjson + +package benchmark + +import ( + "testing" + + "github.com/mailru/easyjson" + "github.com/mailru/easyjson/jwriter" +) + +func BenchmarkEJ_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := s.UnmarshalJSON(largeStructText) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkEJ_Unmarshal_S(b *testing.B) { + b.SetBytes(int64(len(smallStructText))) + + for i := 0; i < b.N; i++ { + var s Entities + err := s.UnmarshalJSON(smallStructText) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkEJ_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := easyjson.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := easyjson.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L_ToWriter(b *testing.B) { + var l int64 + out := &DummyWriter{} + for i := 0; i < b.N; i++ { + w := jwriter.Writer{} + xlStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + b.SetBytes(l) + +} +func BenchmarkEJ_Marshal_M_Parallel(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _, err := largeStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + } + }) +} + +func BenchmarkEJ_Marshal_M_ToWriter(b *testing.B) { + var l int64 + out := &DummyWriter{} + for i := 0; i < b.N; i++ { + w := jwriter.Writer{} + largeStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + b.SetBytes(l) + +} +func BenchmarkEJ_Marshal_M_ToWriter_Parallel(b *testing.B) { + out := &DummyWriter{} + + b.RunParallel(func(pb *testing.PB) { + var l int64 + for pb.Next() { + w := jwriter.Writer{} + largeStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + if l > 0 { + b.SetBytes(l) + } + }) + +} + +func BenchmarkEJ_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := xlStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L_ToWriter_Parallel(b *testing.B) { + out := &DummyWriter{} + b.RunParallel(func(pb *testing.PB) { + var l int64 + for pb.Next() { + w := jwriter.Writer{} + + xlStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + l = int64(w.Size()) + w.DumpTo(out) + } + if l > 0 { + b.SetBytes(l) + } + }) +} + +func BenchmarkEJ_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := smallStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := smallStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/example.json b/accounts/vendor/github.com/mailru/easyjson/benchmark/example.json new file mode 100644 index 000000000..2405022cf --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/example.json @@ -0,0 +1,415 @@ +{ + "statuses": [ + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Mon Sep 24 03:35:21 +0000 2012", + "id_str": "250075927172759552", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Aggressive Ponytail #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 250075927172759552, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "DDEEF6", + "profile_sidebar_border_color": "C0DEED", + "profile_background_tile": false, + "name": "Sean Cummings", + "profile_image_url": "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + "created_at": "Mon Apr 26 06:01:55 +0000 2010", + "location": "LA, CA", + "follow_request_sent": null, + "profile_link_color": "0084B4", + "is_translator": false, + "id_str": "137238150", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "", + "indices": [ + 0, + 0 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": true, + "contributors_enabled": false, + "favourites_count": 0, + "url": null, + "profile_image_url_https": "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + "utc_offset": -28800, + "id": 137238150, + "profile_use_background_image": true, + "listed_count": 2, + "profile_text_color": "333333", + "lang": "en", + "followers_count": 70, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png", + "profile_background_color": "C0DEED", + "verified": false, + "geo_enabled": true, + "time_zone": "Pacific Time (US & Canada)", + "description": "Born 330 Live 310", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png", + "statuses_count": 579, + "friends_count": 110, + "following": null, + "show_all_inline_media": false, + "screen_name": "sean_cummings" + }, + "in_reply_to_screen_name": null, + "source": "Twitter for Mac", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 23:40:54 +0000 2012", + "id_str": "249292149810667520", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "FreeBandNames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Thee Namaste Nerdz. #FreeBandNames", + "metadata": { + "iso_language_code": "pl", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249292149810667520, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "DDFFCC", + "profile_sidebar_border_color": "BDDCAD", + "profile_background_tile": true, + "name": "Chaz Martenstein", + "profile_image_url": "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + "created_at": "Tue Apr 07 19:05:07 +0000 2009", + "location": "Durham, NC", + "follow_request_sent": null, + "profile_link_color": "0084B4", + "is_translator": false, + "id_str": "29516238", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "http://bullcityrecords.com/wnng/", + "indices": [ + 0, + 32 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 8, + "url": "http://bullcityrecords.com/wnng/", + "profile_image_url_https": "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + "utc_offset": -18000, + "id": 29516238, + "profile_use_background_image": true, + "listed_count": 118, + "profile_text_color": "333333", + "lang": "en", + "followers_count": 2052, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", + "profile_background_color": "9AE4E8", + "verified": false, + "geo_enabled": false, + "time_zone": "Eastern Time (US & Canada)", + "description": "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", + "statuses_count": 7579, + "friends_count": 348, + "following": null, + "show_all_inline_media": true, + "screen_name": "bullcityrecords" + }, + "in_reply_to_screen_name": null, + "source": "web", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 23:30:20 +0000 2012", + "id_str": "249289491129438208", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 29, + 43 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Mexican Heaven, Mexican Hell #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249289491129438208, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "99CC33", + "profile_sidebar_border_color": "829D5E", + "profile_background_tile": false, + "name": "Thomas John Wakeman", + "profile_image_url": "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + "created_at": "Tue Sep 01 21:21:35 +0000 2009", + "location": "Kingston New York", + "follow_request_sent": null, + "profile_link_color": "D02B55", + "is_translator": false, + "id_str": "70789458", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "", + "indices": [ + 0, + 0 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 19, + "url": null, + "profile_image_url_https": "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + "utc_offset": -18000, + "id": 70789458, + "profile_use_background_image": true, + "listed_count": 1, + "profile_text_color": "3E4415", + "lang": "en", + "followers_count": 63, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme5/bg.gif", + "profile_background_color": "352726", + "verified": false, + "geo_enabled": false, + "time_zone": "Eastern Time (US & Canada)", + "description": "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/images/themes/theme5/bg.gif", + "statuses_count": 1048, + "friends_count": 63, + "following": null, + "show_all_inline_media": false, + "screen_name": "MonkiesFist" + }, + "in_reply_to_screen_name": null, + "source": "web", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 22:51:18 +0000 2012", + "id_str": "249279667666817024", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "The Foolish Mortals #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249279667666817024, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "BFAC83", + "profile_sidebar_border_color": "615A44", + "profile_background_tile": true, + "name": "Marty Elmer", + "profile_image_url": "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + "created_at": "Mon May 04 00:05:00 +0000 2009", + "location": "Wisconsin, USA", + "follow_request_sent": null, + "profile_link_color": "3B2A26", + "is_translator": false, + "id_str": "37539828", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "http://www.omnitarian.me", + "indices": [ + 0, + 24 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 647, + "url": "http://www.omnitarian.me", + "profile_image_url_https": "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + "utc_offset": -21600, + "id": 37539828, + "profile_use_background_image": true, + "listed_count": 52, + "profile_text_color": "000000", + "lang": "en", + "followers_count": 608, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", + "profile_background_color": "EEE3C4", + "verified": false, + "geo_enabled": false, + "time_zone": "Central Time (US & Canada)", + "description": "Cartoonist, Illustrator, and T-Shirt connoisseur", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", + "statuses_count": 3575, + "friends_count": 249, + "following": null, + "show_all_inline_media": true, + "screen_name": "Omnitarian" + }, + "in_reply_to_screen_name": null, + "source": "Twitter for iPhone", + "in_reply_to_status_id": null + } + ], + "search_metadata": { + "max_id": 250126199840518145, + "since_id": 24012619984051000, + "refresh_url": "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", + "next_results": "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", + "count": 4, + "completed_in": 0.035, + "since_id_str": "24012619984051000", + "query": "%23freebandnames", + "max_id_str": "250126199840518145" + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go b/accounts/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go new file mode 100644 index 000000000..03671827c --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go @@ -0,0 +1,190 @@ +// +build use_ffjson + +package benchmark + +import ( + "testing" + + "github.com/pquerna/ffjson/ffjson" +) + +func BenchmarkFF_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := ffjson.UnmarshalFast(largeStructText, &s) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkFF_Unmarshal_S(b *testing.B) { + for i := 0; i < b.N; i++ { + var s Entities + err := ffjson.UnmarshalFast(smallStructText, &s) + if err != nil { + b.Error(err) + } + } + b.SetBytes(int64(len(smallStructText))) +} + +func BenchmarkFF_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_M_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Pool_Parallel(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} +func BenchmarkFF_Marshal_M_Pool_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Pool_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_M_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/benchmark/ujson.sh b/accounts/vendor/github.com/mailru/easyjson/benchmark/ujson.sh new file mode 100755 index 000000000..378e7df46 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/benchmark/ujson.sh @@ -0,0 +1,7 @@ +#/bin/bash + +echo -n "Python ujson module, DECODE: " +python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read()" 'ujson.loads(data)' + +echo -n "Python ujson module, ENCODE: " +python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read(); obj = ujson.loads(data)" 'ujson.dumps(obj)' diff --git a/accounts/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go b/accounts/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go new file mode 100644 index 000000000..032251172 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go @@ -0,0 +1,184 @@ +// Package bootstrap implements the bootstrapping logic: generation of a .go file to +// launch the actual generator and launching the generator itself. +// +// The package may be preferred to a command-line utility if generating the serializers +// from golang code is required. +package bootstrap + +import ( + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "sort" +) + +const genPackage = "github.com/mailru/easyjson/gen" +const pkgWriter = "github.com/mailru/easyjson/jwriter" +const pkgLexer = "github.com/mailru/easyjson/jlexer" + +type Generator struct { + PkgPath, PkgName string + Types []string + + NoStdMarshalers bool + SnakeCase bool + OmitEmpty bool + + OutName string + BuildTags string + + StubsOnly bool + LeaveTemps bool + NoFormat bool +} + +// writeStub outputs an initial stubs for marshalers/unmarshalers so that the package +// using marshalers/unmarshales compiles correctly for boostrapping code. +func (g *Generator) writeStub() error { + f, err := os.Create(g.OutName) + if err != nil { + return err + } + defer f.Close() + + if g.BuildTags != "" { + fmt.Fprintln(f, "// +build ", g.BuildTags) + fmt.Fprintln(f) + } + fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson stub code to make the package") + fmt.Fprintln(f, "// compilable during generation.") + fmt.Fprintln(f) + fmt.Fprintln(f, "package ", g.PkgName) + + if len(g.Types) > 0 { + fmt.Fprintln(f) + fmt.Fprintln(f, "import (") + fmt.Fprintln(f, ` "`+pkgWriter+`"`) + fmt.Fprintln(f, ` "`+pkgLexer+`"`) + fmt.Fprintln(f, ")") + } + + sort.Strings(g.Types) + for _, t := range g.Types { + fmt.Fprintln(f) + if !g.NoStdMarshalers { + fmt.Fprintln(f, "func (", t, ") MarshalJSON() ([]byte, error) { return nil, nil }") + fmt.Fprintln(f, "func (*", t, ") UnmarshalJSON([]byte) error { return nil }") + } + + fmt.Fprintln(f, "func (", t, ") MarshalEasyJSON(w *jwriter.Writer) {}") + fmt.Fprintln(f, "func (*", t, ") UnmarshalEasyJSON(l *jlexer.Lexer) {}") + fmt.Fprintln(f) + fmt.Fprintln(f, "type EasyJSON_exporter_"+t+" *"+t) + } + return nil +} + +// writeMain creates a .go file that launches the generator if 'go run'. +func (g *Generator) writeMain() (path string, err error) { + f, err := ioutil.TempFile(filepath.Dir(g.OutName), "easyjson-bootstrap") + if err != nil { + return "", err + } + + fmt.Fprintln(f, "// +build ignore") + fmt.Fprintln(f) + fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch") + fmt.Fprintln(f, "// the actual generator.") + fmt.Fprintln(f) + fmt.Fprintln(f, "package main") + fmt.Fprintln(f) + fmt.Fprintln(f, "import (") + fmt.Fprintln(f, ` "fmt"`) + fmt.Fprintln(f, ` "os"`) + fmt.Fprintln(f) + fmt.Fprintf(f, " %q\n", genPackage) + if len(g.Types) > 0 { + fmt.Fprintln(f) + fmt.Fprintf(f, " pkg %q\n", g.PkgPath) + } + fmt.Fprintln(f, ")") + fmt.Fprintln(f) + fmt.Fprintln(f, "func main() {") + fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName)) + fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath) + if g.BuildTags != "" { + fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags) + } + if g.SnakeCase { + fmt.Fprintln(f, " g.UseSnakeCase()") + } + if g.OmitEmpty { + fmt.Fprintln(f, " g.OmitEmpty()") + } + if g.NoStdMarshalers { + fmt.Fprintln(f, " g.NoStdMarshalers()") + } + + sort.Strings(g.Types) + for _, v := range g.Types { + fmt.Fprintln(f, " g.Add(pkg.EasyJSON_exporter_"+v+"(nil))") + } + + fmt.Fprintln(f, " if err := g.Run(os.Stdout); err != nil {") + fmt.Fprintln(f, " fmt.Fprintln(os.Stderr, err)") + fmt.Fprintln(f, " os.Exit(1)") + fmt.Fprintln(f, " }") + fmt.Fprintln(f, "}") + + src := f.Name() + if err := f.Close(); err != nil { + return src, err + } + + dest := src + ".go" + return dest, os.Rename(src, dest) +} + +func (g *Generator) Run() error { + if err := g.writeStub(); err != nil { + return err + } + if g.StubsOnly { + return nil + } + + path, err := g.writeMain() + if err != nil { + return err + } + if !g.LeaveTemps { + defer os.Remove(path) + } + + f, err := os.Create(g.OutName + ".tmp") + if err != nil { + return err + } + if !g.LeaveTemps { + defer os.Remove(f.Name()) // will not remove after rename + } + + cmd := exec.Command("go", "run", "-tags", g.BuildTags, path) + cmd.Stdout = f + cmd.Stderr = os.Stderr + if err = cmd.Run(); err != nil { + return err + } + + f.Close() + + if !g.NoFormat { + cmd = exec.Command("gofmt", "-w", f.Name()) + cmd.Stderr = os.Stderr + cmd.Stdout = os.Stdout + + if err = cmd.Run(); err != nil { + return err + } + } + + return os.Rename(f.Name(), g.OutName) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/buffer/pool.go b/accounts/vendor/github.com/mailru/easyjson/buffer/pool.go new file mode 100644 index 000000000..07fb4bc1f --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/buffer/pool.go @@ -0,0 +1,270 @@ +// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to +// reduce copying and to allow reuse of individual chunks. +package buffer + +import ( + "io" + "sync" +) + +// PoolConfig contains configuration for the allocation and reuse strategy. +type PoolConfig struct { + StartSize int // Minimum chunk size that is allocated. + PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. + MaxSize int // Maximum chunk size that will be allocated. +} + +var config = PoolConfig{ + StartSize: 128, + PooledSize: 512, + MaxSize: 32768, +} + +// Reuse pool: chunk size -> pool. +var buffers = map[int]*sync.Pool{} + +func initBuffers() { + for l := config.PooledSize; l <= config.MaxSize; l *= 2 { + buffers[l] = new(sync.Pool) + } +} + +func init() { + initBuffers() +} + +// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. +func Init(cfg PoolConfig) { + config = cfg + initBuffers() +} + +// putBuf puts a chunk to reuse pool if it can be reused. +func putBuf(buf []byte) { + size := cap(buf) + if size < config.PooledSize { + return + } + if c := buffers[size]; c != nil { + c.Put(buf[:0]) + } +} + +// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. +func getBuf(size int) []byte { + if size < config.PooledSize { + return make([]byte, 0, size) + } + + if c := buffers[size]; c != nil { + v := c.Get() + if v != nil { + return v.([]byte) + } + } + return make([]byte, 0, size) +} + +// Buffer is a buffer optimized for serialization without extra copying. +type Buffer struct { + + // Buf is the current chunk that can be used for serialization. + Buf []byte + + toPool []byte + bufs [][]byte +} + +// EnsureSpace makes sure that the current chunk contains at least s free bytes, +// possibly creating a new chunk. +func (b *Buffer) EnsureSpace(s int) { + if cap(b.Buf)-len(b.Buf) >= s { + return + } + l := len(b.Buf) + if l > 0 { + if cap(b.toPool) != cap(b.Buf) { + // Chunk was reallocated, toPool can be pooled. + putBuf(b.toPool) + } + if cap(b.bufs) == 0 { + b.bufs = make([][]byte, 0, 8) + } + b.bufs = append(b.bufs, b.Buf) + l = cap(b.toPool) * 2 + } else { + l = config.StartSize + } + + if l > config.MaxSize { + l = config.MaxSize + } + b.Buf = getBuf(l) + b.toPool = b.Buf +} + +// AppendByte appends a single byte to buffer. +func (b *Buffer) AppendByte(data byte) { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + b.Buf = append(b.Buf, data) +} + +// AppendBytes appends a byte slice to buffer. +func (b *Buffer) AppendBytes(data []byte) { + for len(data) > 0 { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + + sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } + + b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } +} + +// AppendBytes appends a string to buffer. +func (b *Buffer) AppendString(data string) { + for len(data) > 0 { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + + sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } + + b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } +} + +// Size computes the size of a buffer by adding sizes of every chunk. +func (b *Buffer) Size() int { + size := len(b.Buf) + for _, buf := range b.bufs { + size += len(buf) + } + return size +} + +// DumpTo outputs the contents of a buffer to a writer and resets the buffer. +func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { + var n int + for _, buf := range b.bufs { + if err == nil { + n, err = w.Write(buf) + written += n + } + putBuf(buf) + } + + if err == nil { + n, err = w.Write(b.Buf) + written += n + } + putBuf(b.toPool) + + b.bufs = nil + b.Buf = nil + b.toPool = nil + + return +} + +// BuildBytes creates a single byte slice with all the contents of the buffer. Data is +// copied if it does not fit in a single chunk. You can optionally provide one byte +// slice as argument that it will try to reuse. +func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { + if len(b.bufs) == 0 { + ret := b.Buf + b.toPool = nil + b.Buf = nil + return ret + } + + var ret []byte + size := b.Size() + + // If we got a buffer as argument and it is big enought, reuse it. + if len(reuse) == 1 && cap(reuse[0]) >= size { + ret = reuse[0][:0] + } else { + ret = make([]byte, 0, size) + } + for _, buf := range b.bufs { + ret = append(ret, buf...) + putBuf(buf) + } + + ret = append(ret, b.Buf...) + putBuf(b.toPool) + + b.bufs = nil + b.toPool = nil + b.Buf = nil + + return ret +} + +type readCloser struct { + offset int + bufs [][]byte +} + +func (r *readCloser) Read(p []byte) (n int, err error) { + for _, buf := range r.bufs { + // Copy as much as we can. + x := copy(p[n:], buf[r.offset:]) + n += x // Increment how much we filled. + + // Did we empty the whole buffer? + if r.offset+x == len(buf) { + // On to the next buffer. + r.offset = 0 + r.bufs = r.bufs[1:] + + // We can release this buffer. + putBuf(buf) + } else { + r.offset += x + } + + if n == len(p) { + break + } + } + // No buffers left or nothing read? + if len(r.bufs) == 0 { + err = io.EOF + } + return +} + +func (r *readCloser) Close() error { + // Release all remaining buffers. + for _, buf := range r.bufs { + putBuf(buf) + } + // In case Close gets called multiple times. + r.bufs = nil + + return nil +} + +// ReadCloser creates an io.ReadCloser with all the contents of the buffer. +func (b *Buffer) ReadCloser() io.ReadCloser { + ret := &readCloser{0, append(b.bufs, b.Buf)} + + b.bufs = nil + b.toPool = nil + b.Buf = nil + + return ret +} diff --git a/accounts/vendor/github.com/mailru/easyjson/buffer/pool_test.go b/accounts/vendor/github.com/mailru/easyjson/buffer/pool_test.go new file mode 100644 index 000000000..680623ace --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/buffer/pool_test.go @@ -0,0 +1,107 @@ +package buffer + +import ( + "bytes" + "testing" +) + +func TestAppendByte(t *testing.T) { + var b Buffer + var want []byte + + for i := 0; i < 1000; i++ { + b.AppendByte(1) + b.AppendByte(2) + want = append(want, 1, 2) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestAppendBytes(t *testing.T) { + var b Buffer + var want []byte + + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte{1, 2}) + want = append(want, 1, 2) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestAppendString(t *testing.T) { + var b Buffer + var want []byte + + s := "test" + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte(s)) + want = append(want, s...) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestDumpTo(t *testing.T) { + var b Buffer + var want []byte + + s := "test" + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte(s)) + want = append(want, s...) + } + + out := &bytes.Buffer{} + n, err := b.DumpTo(out) + if err != nil { + t.Errorf("DumpTo() error: %v", err) + } + + got := out.Bytes() + if !bytes.Equal(got, want) { + t.Errorf("DumpTo(): got %v; want %v", got, want) + } + + if n != len(want) { + t.Errorf("DumpTo() = %v; want %v", n, len(want)) + } +} + +func TestReadCloser(t *testing.T) { + var b Buffer + var want []byte + + s := "test" + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte(s)) + want = append(want, s...) + } + + out := &bytes.Buffer{} + rc := b.ReadCloser() + n, err := out.ReadFrom(rc) + if err != nil { + t.Errorf("ReadCloser() error: %v", err) + } + rc.Close() // Will always return nil + + got := out.Bytes() + if !bytes.Equal(got, want) { + t.Errorf("DumpTo(): got %v; want %v", got, want) + } + + if n != int64(len(want)) { + t.Errorf("DumpTo() = %v; want %v", n, len(want)) + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/easyjson/main.go b/accounts/vendor/github.com/mailru/easyjson/easyjson/main.go new file mode 100644 index 000000000..628792675 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/easyjson/main.go @@ -0,0 +1,99 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/mailru/easyjson/bootstrap" + // Reference the gen package to be friendly to vendoring tools, + // as it is an indirect dependency. + // (The temporary bootstrapping code uses it.) + _ "github.com/mailru/easyjson/gen" + "github.com/mailru/easyjson/parser" +) + +var buildTags = flag.String("build_tags", "", "build tags to add to generated file") +var snakeCase = flag.Bool("snake_case", false, "use snake_case names instead of CamelCase by default") +var noStdMarshalers = flag.Bool("no_std_marshalers", false, "don't generate MarshalJSON/UnmarshalJSON funcs") +var omitEmpty = flag.Bool("omit_empty", false, "omit empty fields by default") +var allStructs = flag.Bool("all", false, "generate marshaler/unmarshalers for all structs in a file") +var leaveTemps = flag.Bool("leave_temps", false, "do not delete temporary files") +var stubs = flag.Bool("stubs", false, "only generate stubs for marshaler/unmarshaler funcs") +var noformat = flag.Bool("noformat", false, "do not run 'gofmt -w' on output file") +var specifiedName = flag.String("output_filename", "", "specify the filename of the output") +var processPkg = flag.Bool("pkg", false, "process the whole package instead of just the given file") + +func generate(fname string) (err error) { + fInfo, err := os.Stat(fname) + if err != nil { + return err + } + + p := parser.Parser{AllStructs: *allStructs} + if err := p.Parse(fname, fInfo.IsDir()); err != nil { + return fmt.Errorf("Error parsing %v: %v", fname, err) + } + + var outName string + if fInfo.IsDir() { + outName = filepath.Join(fname, p.PkgName+"_easyjson.go") + } else { + if s := strings.TrimSuffix(fname, ".go"); s == fname { + return errors.New("Filename must end in '.go'") + } else { + outName = s + "_easyjson.go" + } + } + + if *specifiedName != "" { + outName = *specifiedName + } + + g := bootstrap.Generator{ + BuildTags: *buildTags, + PkgPath: p.PkgPath, + PkgName: p.PkgName, + Types: p.StructNames, + SnakeCase: *snakeCase, + NoStdMarshalers: *noStdMarshalers, + OmitEmpty: *omitEmpty, + LeaveTemps: *leaveTemps, + OutName: outName, + StubsOnly: *stubs, + NoFormat: *noformat, + } + + if err := g.Run(); err != nil { + return fmt.Errorf("Bootstrap failed: %v", err) + } + return nil +} + +func main() { + flag.Parse() + + files := flag.Args() + + gofile := os.Getenv("GOFILE") + if *processPkg { + gofile = filepath.Dir(gofile) + } + + if len(files) == 0 && gofile != "" { + files = []string{gofile} + } else if len(files) == 0 { + flag.Usage() + os.Exit(1) + } + + for _, fname := range files { + if err := generate(fname); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/gen/decoder.go b/accounts/vendor/github.com/mailru/easyjson/gen/decoder.go new file mode 100644 index 000000000..80f8d2cc6 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/gen/decoder.go @@ -0,0 +1,471 @@ +package gen + +import ( + "encoding" + "encoding/json" + "fmt" + "reflect" + "strings" + "unicode" + + "github.com/mailru/easyjson" +) + +// Target this byte size for initial slice allocation to reduce garbage collection. +const minSliceBytes = 64 + +func (g *Generator) getDecoderName(t reflect.Type) string { + return g.functionName("decode", t) +} + +var primitiveDecoders = map[reflect.Kind]string{ + reflect.String: "in.String()", + reflect.Bool: "in.Bool()", + reflect.Int: "in.Int()", + reflect.Int8: "in.Int8()", + reflect.Int16: "in.Int16()", + reflect.Int32: "in.Int32()", + reflect.Int64: "in.Int64()", + reflect.Uint: "in.Uint()", + reflect.Uint8: "in.Uint8()", + reflect.Uint16: "in.Uint16()", + reflect.Uint32: "in.Uint32()", + reflect.Uint64: "in.Uint64()", + reflect.Float32: "in.Float32()", + reflect.Float64: "in.Float64()", +} + +var primitiveStringDecoders = map[reflect.Kind]string{ + reflect.Int: "in.IntStr()", + reflect.Int8: "in.Int8Str()", + reflect.Int16: "in.Int16Str()", + reflect.Int32: "in.Int32Str()", + reflect.Int64: "in.Int64Str()", + reflect.Uint: "in.UintStr()", + reflect.Uint8: "in.Uint8Str()", + reflect.Uint16: "in.Uint16Str()", + reflect.Uint32: "in.Uint32Str()", + reflect.Uint64: "in.Uint64Str()", +} + +// genTypeDecoder generates decoding code for the type t, but uses unmarshaler interface if implemented by t. +func (g *Generator) genTypeDecoder(t reflect.Type, out string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + unmarshalerIface := reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(unmarshalerIface) { + fmt.Fprintln(g.out, ws+"("+out+").UnmarshalEasyJSON(in)") + return nil + } + + unmarshalerIface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(unmarshalerIface) { + fmt.Fprintln(g.out, ws+"if data := in.Raw(); in.Ok() {") + fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalJSON(data) )") + fmt.Fprintln(g.out, ws+"}") + return nil + } + + unmarshalerIface = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(unmarshalerIface) { + fmt.Fprintln(g.out, ws+"if data := in.UnsafeBytes(); in.Ok() {") + fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalText(data) )") + fmt.Fprintln(g.out, ws+"}") + return nil + } + + err := g.genTypeDecoderNoCheck(t, out, tags, indent) + return err +} + +// genTypeDecoderNoCheck generates decoding code for the type t. +func (g *Generator) genTypeDecoderNoCheck(t reflect.Type, out string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + // Check whether type is primitive, needs to be done after interface check. + if dec := primitiveStringDecoders[t.Kind()]; dec != "" && tags.asString { + fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") + return nil + } else if dec := primitiveDecoders[t.Kind()]; dec != "" { + fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") + return nil + } + + switch t.Kind() { + case reflect.Slice: + tmpVar := g.uniqueVarName() + elem := t.Elem() + + if elem.Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" "+out+" = in.Bytes()") + fmt.Fprintln(g.out, ws+"}") + + } else { + + capacity := minSliceBytes / elem.Size() + if capacity == 0 { + capacity = 1 + } + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('[')") + fmt.Fprintln(g.out, ws+" if "+out+" == nil {") + fmt.Fprintln(g.out, ws+" if !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+", 0, "+fmt.Sprint(capacity)+")") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" "+out+" = "+g.getType(t)+"{}") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" } else { ") + fmt.Fprintln(g.out, ws+" "+out+" = ("+out+")[:0]") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) + + g.genTypeDecoder(elem, tmpVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" "+out+" = append("+out+", "+tmpVar+")") + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Array: + iterVar := g.uniqueVarName() + elem := t.Elem() + + if elem.Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" copy("+out+"[:], in.Bytes())") + fmt.Fprintln(g.out, ws+"}") + + } else { + + length := t.Len() + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('[')") + fmt.Fprintln(g.out, ws+" "+iterVar+" := 0") + fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" if "+iterVar+" < "+fmt.Sprint(length)+" {") + + g.genTypeDecoder(elem, out+"["+iterVar+"]", tags, indent+3) + + fmt.Fprintln(g.out, ws+" "+iterVar+"++") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" in.SkipRecursive()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Struct: + dec := g.getDecoderName(t) + g.addType(t) + + fmt.Fprintln(g.out, ws+dec+"(in, &"+out+")") + + case reflect.Ptr: + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" if "+out+" == nil {") + fmt.Fprintln(g.out, ws+" "+out+" = new("+g.getType(t.Elem())+")") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeDecoder(t.Elem(), "*"+out, tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + + case reflect.Map: + key := t.Key() + if key.Kind() != reflect.String { + return fmt.Errorf("map type %v not supported: only string keys are allowed", key) + } + elem := t.Elem() + tmpVar := g.uniqueVarName() + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('{')") + fmt.Fprintln(g.out, ws+" if !in.IsDelim('}') {") + fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+")") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+" }") + + fmt.Fprintln(g.out, ws+" for !in.IsDelim('}') {") + fmt.Fprintln(g.out, ws+" key := "+g.getType(t.Key())+"(in.String())") + fmt.Fprintln(g.out, ws+" in.WantColon()") + fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) + + g.genTypeDecoder(elem, tmpVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" ("+out+")[key] = "+tmpVar) + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim('}')") + fmt.Fprintln(g.out, ws+"}") + + case reflect.Interface: + if t.NumMethod() != 0 { + return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) + } + fmt.Fprintln(g.out, ws+"if m, ok := "+out+".(easyjson.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalEasyJSON(in)") + fmt.Fprintln(g.out, ws+"} else if m, ok := "+out+".(json.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalJSON(in.Raw())") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" "+out+" = in.Interface()") + fmt.Fprintln(g.out, ws+"}") + default: + return fmt.Errorf("don't know how to decode %v", t) + } + return nil + +} + +func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField) error { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if tags.omit { + return nil + } + + fmt.Fprintf(g.out, " case %q:\n", jsonName) + if err := g.genTypeDecoder(f.Type, "out."+f.Name, tags, 3); err != nil { + return err + } + + if tags.required { + fmt.Fprintf(g.out, "%sSet = true\n", f.Name) + } + + return nil +} + +func (g *Generator) genRequiredFieldSet(t reflect.Type, f reflect.StructField) { + tags := parseFieldTags(f) + + if !tags.required { + return + } + + fmt.Fprintf(g.out, "var %sSet bool\n", f.Name) +} + +func (g *Generator) genRequiredFieldCheck(t reflect.Type, f reflect.StructField) { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if !tags.required { + return + } + + g.imports["fmt"] = "fmt" + + fmt.Fprintf(g.out, "if !%sSet {\n", f.Name) + fmt.Fprintf(g.out, " in.AddError(fmt.Errorf(\"key '%s' is required\"))\n", jsonName) + fmt.Fprintf(g.out, "}\n") +} + +func mergeStructFields(fields1, fields2 []reflect.StructField) (fields []reflect.StructField) { + used := map[string]bool{} + for _, f := range fields2 { + used[f.Name] = true + fields = append(fields, f) + } + + for _, f := range fields1 { + if !used[f.Name] { + fields = append(fields, f) + } + } + return +} + +func getStructFields(t reflect.Type) ([]reflect.StructField, error) { + if t.Kind() != reflect.Struct { + return nil, fmt.Errorf("got %v; expected a struct", t) + } + + var efields []reflect.StructField + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.Anonymous { + continue + } + + t1 := f.Type + if t1.Kind() == reflect.Ptr { + t1 = t1.Elem() + } + + fs, err := getStructFields(t1) + if err != nil { + return nil, fmt.Errorf("error processing embedded field: %v", err) + } + efields = mergeStructFields(efields, fs) + } + + var fields []reflect.StructField + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Anonymous { + continue + } + + c := []rune(f.Name)[0] + if unicode.IsUpper(c) { + fields = append(fields, f) + } + } + return mergeStructFields(efields, fields), nil +} + +func (g *Generator) genDecoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + return g.genSliceArrayDecoder(t) + default: + return g.genStructDecoder(t) + } +} + +func (g *Generator) genSliceArrayDecoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") + fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") + err := g.genTypeDecoderNoCheck(t, "*out", fieldTags{}, 1) + if err != nil { + return err + } + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructDecoder(t reflect.Type) error { + if t.Kind() != reflect.Struct { + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") + fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") + fmt.Fprintln(g.out, " if in.IsNull() {") + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.Skip()") + fmt.Fprintln(g.out, " return") + fmt.Fprintln(g.out, " }") + + // Init embedded pointer fields. + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.Anonymous || f.Type.Kind() != reflect.Ptr { + continue + } + fmt.Fprintln(g.out, " out."+f.Name+" = new("+g.getType(f.Type.Elem())+")") + } + + fs, err := getStructFields(t) + if err != nil { + return fmt.Errorf("cannot generate decoder for %v: %v", t, err) + } + + for _, f := range fs { + g.genRequiredFieldSet(t, f) + } + + fmt.Fprintln(g.out, " in.Delim('{')") + fmt.Fprintln(g.out, " for !in.IsDelim('}') {") + fmt.Fprintln(g.out, " key := in.UnsafeString()") + fmt.Fprintln(g.out, " in.WantColon()") + fmt.Fprintln(g.out, " if in.IsNull() {") + fmt.Fprintln(g.out, " in.Skip()") + fmt.Fprintln(g.out, " in.WantComma()") + fmt.Fprintln(g.out, " continue") + fmt.Fprintln(g.out, " }") + + fmt.Fprintln(g.out, " switch key {") + for _, f := range fs { + if err := g.genStructFieldDecoder(t, f); err != nil { + return err + } + } + + fmt.Fprintln(g.out, " default:") + fmt.Fprintln(g.out, " in.SkipRecursive()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.WantComma()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.Delim('}')") + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + + for _, f := range fs { + g.genRequiredFieldCheck(t, f) + } + + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructUnmarshaler(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + if !g.noStdMarshalers { + fmt.Fprintln(g.out, "// UnmarshalJSON supports json.Unmarshaler interface") + fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalJSON(data []byte) error {") + fmt.Fprintln(g.out, " r := jlexer.Lexer{Data: data}") + fmt.Fprintln(g.out, " "+fname+"(&r, v)") + fmt.Fprintln(g.out, " return r.Error()") + fmt.Fprintln(g.out, "}") + } + + fmt.Fprintln(g.out, "// UnmarshalEasyJSON supports easyjson.Unmarshaler interface") + fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalEasyJSON(l *jlexer.Lexer) {") + fmt.Fprintln(g.out, " "+fname+"(l, v)") + fmt.Fprintln(g.out, "}") + + return nil +} diff --git a/accounts/vendor/github.com/mailru/easyjson/gen/encoder.go b/accounts/vendor/github.com/mailru/easyjson/gen/encoder.go new file mode 100644 index 000000000..a54f6e24b --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/gen/encoder.go @@ -0,0 +1,358 @@ +package gen + +import ( + "encoding" + "encoding/json" + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/mailru/easyjson" +) + +func (g *Generator) getEncoderName(t reflect.Type) string { + return g.functionName("encode", t) +} + +var primitiveEncoders = map[reflect.Kind]string{ + reflect.String: "out.String(string(%v))", + reflect.Bool: "out.Bool(bool(%v))", + reflect.Int: "out.Int(int(%v))", + reflect.Int8: "out.Int8(int8(%v))", + reflect.Int16: "out.Int16(int16(%v))", + reflect.Int32: "out.Int32(int32(%v))", + reflect.Int64: "out.Int64(int64(%v))", + reflect.Uint: "out.Uint(uint(%v))", + reflect.Uint8: "out.Uint8(uint8(%v))", + reflect.Uint16: "out.Uint16(uint16(%v))", + reflect.Uint32: "out.Uint32(uint32(%v))", + reflect.Uint64: "out.Uint64(uint64(%v))", + reflect.Float32: "out.Float32(float32(%v))", + reflect.Float64: "out.Float64(float64(%v))", +} + +var primitiveStringEncoders = map[reflect.Kind]string{ + reflect.Int: "out.IntStr(int(%v))", + reflect.Int8: "out.Int8Str(int8(%v))", + reflect.Int16: "out.Int16Str(int16(%v))", + reflect.Int32: "out.Int32Str(int32(%v))", + reflect.Int64: "out.Int64Str(int64(%v))", + reflect.Uint: "out.UintStr(uint(%v))", + reflect.Uint8: "out.Uint8Str(uint8(%v))", + reflect.Uint16: "out.Uint16Str(uint16(%v))", + reflect.Uint32: "out.Uint32Str(uint32(%v))", + reflect.Uint64: "out.Uint64Str(uint64(%v))", +} + +// fieldTags contains parsed version of json struct field tags. +type fieldTags struct { + name string + + omit bool + omitEmpty bool + noOmitEmpty bool + asString bool + required bool +} + +// parseFieldTags parses the json field tag into a structure. +func parseFieldTags(f reflect.StructField) fieldTags { + var ret fieldTags + + for i, s := range strings.Split(f.Tag.Get("json"), ",") { + switch { + case i == 0 && s == "-": + ret.omit = true + case i == 0: + ret.name = s + case s == "omitempty": + ret.omitEmpty = true + case s == "!omitempty": + ret.noOmitEmpty = true + case s == "string": + ret.asString = true + case s == "required": + ret.required = true + } + } + + return ret +} + +// genTypeEncoder generates code that encodes in of type t into the writer, but uses marshaler interface if implemented by t. +func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(marshalerIface) { + fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)") + return nil + } + + marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(marshalerIface) { + fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )") + return nil + } + + marshalerIface = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(marshalerIface) { + fmt.Fprintln(g.out, ws+"out.RawText( ("+in+").MarshalText() )") + return nil + } + + err := g.genTypeEncoderNoCheck(t, in, tags, indent) + return err +} + +// genTypeEncoderNoCheck generates code that encodes in of type t into the writer. +func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + // Check whether type is primitive, needs to be done after interface check. + if enc := primitiveStringEncoders[t.Kind()]; enc != "" && tags.asString { + fmt.Fprintf(g.out, ws+enc+"\n", in) + return nil + } else if enc := primitiveEncoders[t.Kind()]; enc != "" { + fmt.Fprintf(g.out, ws+enc+"\n", in) + return nil + } + + switch t.Kind() { + case reflect.Slice: + elem := t.Elem() + iVar := g.uniqueVarName() + vVar := g.uniqueVarName() + + if t.Elem().Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")") + } else { + fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {") + fmt.Fprintln(g.out, ws+` out.RawString("null")`) + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.RawByte('[')") + fmt.Fprintln(g.out, ws+" for "+iVar+", "+vVar+" := range "+in+" {") + fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") + fmt.Fprintln(g.out, ws+" out.RawByte(',')") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeEncoder(elem, vVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" out.RawByte(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Array: + elem := t.Elem() + iVar := g.uniqueVarName() + + if t.Elem().Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+"[:])") + } else { + fmt.Fprintln(g.out, ws+"out.RawByte('[')") + fmt.Fprintln(g.out, ws+"for "+iVar+" := range "+in+" {") + fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") + fmt.Fprintln(g.out, ws+" out.RawByte(',')") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeEncoder(elem, in+"["+iVar+"]", tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + fmt.Fprintln(g.out, ws+"out.RawByte(']')") + } + + case reflect.Struct: + enc := g.getEncoderName(t) + g.addType(t) + + fmt.Fprintln(g.out, ws+enc+"(out, "+in+")") + + case reflect.Ptr: + fmt.Fprintln(g.out, ws+"if "+in+" == nil {") + fmt.Fprintln(g.out, ws+` out.RawString("null")`) + fmt.Fprintln(g.out, ws+"} else {") + + g.genTypeEncoder(t.Elem(), "*"+in, tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + + case reflect.Map: + key := t.Key() + if key.Kind() != reflect.String { + return fmt.Errorf("map type %v not supported: only string keys are allowed", key) + } + tmpVar := g.uniqueVarName() + + fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {") + fmt.Fprintln(g.out, ws+" out.RawString(`null`)") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.RawByte('{')") + fmt.Fprintln(g.out, ws+" "+tmpVar+"First := true") + fmt.Fprintln(g.out, ws+" for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {") + fmt.Fprintln(g.out, ws+" if !"+tmpVar+"First { out.RawByte(',') }") + fmt.Fprintln(g.out, ws+" "+tmpVar+"First = false") + fmt.Fprintln(g.out, ws+" out.String(string("+tmpVar+"Name))") + fmt.Fprintln(g.out, ws+" out.RawByte(':')") + + g.genTypeEncoder(t.Elem(), tmpVar+"Value", tags, indent+2) + + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" out.RawByte('}')") + fmt.Fprintln(g.out, ws+"}") + + case reflect.Interface: + if t.NumMethod() != 0 { + return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) + } + fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") + fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") + fmt.Fprintln(g.out, ws+"} else if m, ok := "+in+".(json.Marshaler); ok {") + fmt.Fprintln(g.out, ws+" out.Raw(m.MarshalJSON())") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.Raw(json.Marshal("+in+"))") + fmt.Fprintln(g.out, ws+"}") + + default: + return fmt.Errorf("don't know how to encode %v", t) + } + return nil +} + +func (g *Generator) notEmptyCheck(t reflect.Type, v string) string { + optionalIface := reflect.TypeOf((*easyjson.Optional)(nil)).Elem() + if reflect.PtrTo(t).Implements(optionalIface) { + return "(" + v + ").IsDefined()" + } + + switch t.Kind() { + case reflect.Slice, reflect.Map: + return "len(" + v + ") != 0" + case reflect.Interface, reflect.Ptr: + return v + " != nil" + case reflect.Bool: + return v + case reflect.String: + return v + ` != ""` + case reflect.Float32, reflect.Float64, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + + return v + " != 0" + + default: + // note: Array types don't have a useful empty value + return "true" + } +} + +func (g *Generator) genStructFieldEncoder(t reflect.Type, f reflect.StructField) error { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if tags.omit { + return nil + } + if !tags.omitEmpty && !g.omitEmpty || tags.noOmitEmpty { + fmt.Fprintln(g.out, " if !first { out.RawByte(',') }") + fmt.Fprintln(g.out, " first = false") + fmt.Fprintf(g.out, " out.RawString(%q)\n", strconv.Quote(jsonName)+":") + return g.genTypeEncoder(f.Type, "in."+f.Name, tags, 1) + } + + fmt.Fprintln(g.out, " if", g.notEmptyCheck(f.Type, "in."+f.Name), "{") + fmt.Fprintln(g.out, " if !first { out.RawByte(',') }") + fmt.Fprintln(g.out, " first = false") + + fmt.Fprintf(g.out, " out.RawString(%q)\n", strconv.Quote(jsonName)+":") + if err := g.genTypeEncoder(f.Type, "in."+f.Name, tags, 2); err != nil { + return err + } + fmt.Fprintln(g.out, " }") + return nil +} + +func (g *Generator) genEncoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + return g.genSliceArrayMapEncoder(t) + default: + return g.genStructEncoder(t) + } +} + +func (g *Generator) genSliceArrayMapEncoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") + err := g.genTypeEncoderNoCheck(t, "in", fieldTags{}, 1) + if err != nil { + return err + } + fmt.Fprintln(g.out, "}") + return nil +} + +func (g *Generator) genStructEncoder(t reflect.Type) error { + if t.Kind() != reflect.Struct { + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") + fmt.Fprintln(g.out, " out.RawByte('{')") + fmt.Fprintln(g.out, " first := true") + fmt.Fprintln(g.out, " _ = first") + + fs, err := getStructFields(t) + if err != nil { + return fmt.Errorf("cannot generate encoder for %v: %v", t, err) + } + for _, f := range fs { + if err := g.genStructFieldEncoder(t, f); err != nil { + return err + } + } + + fmt.Fprintln(g.out, " out.RawByte('}')") + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructMarshaler(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + if !g.noStdMarshalers { + fmt.Fprintln(g.out, "// MarshalJSON supports json.Marshaler interface") + fmt.Fprintln(g.out, "func (v "+typ+") MarshalJSON() ([]byte, error) {") + fmt.Fprintln(g.out, " w := jwriter.Writer{}") + fmt.Fprintln(g.out, " "+fname+"(&w, v)") + fmt.Fprintln(g.out, " return w.Buffer.BuildBytes(), w.Error") + fmt.Fprintln(g.out, "}") + } + + fmt.Fprintln(g.out, "// MarshalEasyJSON supports easyjson.Marshaler interface") + fmt.Fprintln(g.out, "func (v "+typ+") MarshalEasyJSON(w *jwriter.Writer) {") + fmt.Fprintln(g.out, " "+fname+"(w, v)") + fmt.Fprintln(g.out, "}") + + return nil +} diff --git a/accounts/vendor/github.com/mailru/easyjson/gen/generator.go b/accounts/vendor/github.com/mailru/easyjson/gen/generator.go new file mode 100644 index 000000000..988a3a5f8 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/gen/generator.go @@ -0,0 +1,449 @@ +package gen + +import ( + "bytes" + "fmt" + "hash/fnv" + "io" + "path" + "reflect" + "sort" + "strconv" + "strings" + "unicode" +) + +const pkgWriter = "github.com/mailru/easyjson/jwriter" +const pkgLexer = "github.com/mailru/easyjson/jlexer" +const pkgEasyJSON = "github.com/mailru/easyjson" + +// FieldNamer defines a policy for generating names for struct fields. +type FieldNamer interface { + GetJSONFieldName(t reflect.Type, f reflect.StructField) string +} + +// Generator generates the requested marshaler/unmarshalers. +type Generator struct { + out *bytes.Buffer + + pkgName string + pkgPath string + buildTags string + hashString string + + varCounter int + + noStdMarshalers bool + omitEmpty bool + fieldNamer FieldNamer + + // package path to local alias map for tracking imports + imports map[string]string + + // types that marshalers were requested for by user + marshalers map[reflect.Type]bool + + // types that encoders were already generated for + typesSeen map[reflect.Type]bool + + // types that encoders were requested for (e.g. by encoders of other types) + typesUnseen []reflect.Type + + // function name to relevant type maps to track names of de-/encoders in + // case of a name clash or unnamed structs + functionNames map[string]reflect.Type +} + +// NewGenerator initializes and returns a Generator. +func NewGenerator(filename string) *Generator { + ret := &Generator{ + imports: map[string]string{ + pkgWriter: "jwriter", + pkgLexer: "jlexer", + pkgEasyJSON: "easyjson", + "encoding/json": "json", + }, + fieldNamer: DefaultFieldNamer{}, + marshalers: make(map[reflect.Type]bool), + typesSeen: make(map[reflect.Type]bool), + functionNames: make(map[string]reflect.Type), + } + + // Use a file-unique prefix on all auxiliary funcs to avoid + // name clashes. + hash := fnv.New32() + hash.Write([]byte(filename)) + ret.hashString = fmt.Sprintf("%x", hash.Sum32()) + + return ret +} + +// SetPkg sets the name and path of output package. +func (g *Generator) SetPkg(name, path string) { + g.pkgName = name + g.pkgPath = path +} + +// SetBuildTags sets build tags for the output file. +func (g *Generator) SetBuildTags(tags string) { + g.buildTags = tags +} + +// SetFieldNamer sets field naming strategy. +func (g *Generator) SetFieldNamer(n FieldNamer) { + g.fieldNamer = n +} + +// UseSnakeCase sets snake_case field naming strategy. +func (g *Generator) UseSnakeCase() { + g.fieldNamer = SnakeCaseFieldNamer{} +} + +// NoStdMarshalers instructs not to generate standard MarshalJSON/UnmarshalJSON +// methods (only the custom interface). +func (g *Generator) NoStdMarshalers() { + g.noStdMarshalers = true +} + +// OmitEmpty triggers `json=",omitempty"` behaviour by default. +func (g *Generator) OmitEmpty() { + g.omitEmpty = true +} + +// addTypes requests to generate encoding/decoding funcs for the given type. +func (g *Generator) addType(t reflect.Type) { + if g.typesSeen[t] { + return + } + for _, t1 := range g.typesUnseen { + if t1 == t { + return + } + } + g.typesUnseen = append(g.typesUnseen, t) +} + +// Add requests to generate marshaler/unmarshalers and encoding/decoding +// funcs for the type of given object. +func (g *Generator) Add(obj interface{}) { + t := reflect.TypeOf(obj) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + g.addType(t) + g.marshalers[t] = true +} + +// printHeader prints package declaration and imports. +func (g *Generator) printHeader() { + if g.buildTags != "" { + fmt.Println("// +build ", g.buildTags) + fmt.Println() + } + fmt.Println("// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.") + fmt.Println() + fmt.Println("package ", g.pkgName) + fmt.Println() + + byAlias := map[string]string{} + var aliases []string + for path, alias := range g.imports { + aliases = append(aliases, alias) + byAlias[alias] = path + } + + sort.Strings(aliases) + fmt.Println("import (") + for _, alias := range aliases { + fmt.Printf(" %s %q\n", alias, byAlias[alias]) + } + + fmt.Println(")") + fmt.Println("") + fmt.Println("// suppress unused package warning") + fmt.Println("var (") + fmt.Println(" _ *json.RawMessage") + fmt.Println(" _ *jlexer.Lexer") + fmt.Println(" _ *jwriter.Writer") + fmt.Println(" _ easyjson.Marshaler") + fmt.Println(")") + + fmt.Println() +} + +// Run runs the generator and outputs generated code to out. +func (g *Generator) Run(out io.Writer) error { + g.out = &bytes.Buffer{} + + for len(g.typesUnseen) > 0 { + t := g.typesUnseen[len(g.typesUnseen)-1] + g.typesUnseen = g.typesUnseen[:len(g.typesUnseen)-1] + g.typesSeen[t] = true + + if err := g.genDecoder(t); err != nil { + return err + } + if err := g.genEncoder(t); err != nil { + return err + } + + if !g.marshalers[t] { + continue + } + + if err := g.genStructMarshaler(t); err != nil { + return err + } + if err := g.genStructUnmarshaler(t); err != nil { + return err + } + } + g.printHeader() + _, err := out.Write(g.out.Bytes()) + return err +} + +// fixes vendored paths +func fixPkgPathVendoring(pkgPath string) string { + const vendor = "/vendor/" + if i := strings.LastIndex(pkgPath, vendor); i != -1 { + return pkgPath[i+len(vendor):] + } + return pkgPath +} + +func fixAliasName(alias string) string { + alias = strings.Replace( + strings.Replace(alias, ".", "_", -1), + "-", + "_", + -1, + ) + return alias +} + +// pkgAlias creates and returns and import alias for a given package. +func (g *Generator) pkgAlias(pkgPath string) string { + pkgPath = fixPkgPathVendoring(pkgPath) + if alias := g.imports[pkgPath]; alias != "" { + return alias + } + + for i := 0; ; i++ { + alias := fixAliasName(path.Base(pkgPath)) + if i > 0 { + alias += fmt.Sprint(i) + } + + exists := false + for _, v := range g.imports { + if v == alias { + exists = true + break + } + } + + if !exists { + g.imports[pkgPath] = alias + return alias + } + } +} + +// getType return the textual type name of given type that can be used in generated code. +func (g *Generator) getType(t reflect.Type) string { + if t.Name() == "" { + switch t.Kind() { + case reflect.Ptr: + return "*" + g.getType(t.Elem()) + case reflect.Slice: + return "[]" + g.getType(t.Elem()) + case reflect.Array: + return "[" + strconv.Itoa(t.Len()) + "]" + g.getType(t.Elem()) + case reflect.Map: + return "map[" + g.getType(t.Key()) + "]" + g.getType(t.Elem()) + } + } + + if t.Name() == "" || t.PkgPath() == "" { + if t.Kind() == reflect.Struct { + // the fields of an anonymous struct can have named types, + // and t.String() will not be sufficient because it does not + // remove the package name when it matches g.pkgPath. + // so we convert by hand + nf := t.NumField() + lines := make([]string, 0, nf) + for i := 0; i < nf; i++ { + f := t.Field(i) + line := f.Name + " " + g.getType(f.Type) + t := f.Tag + if t != "" { + line += " " + escapeTag(t) + } + lines = append(lines, line) + } + return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") + } + return t.String() + } else if t.PkgPath() == g.pkgPath { + return t.Name() + } + return g.pkgAlias(t.PkgPath()) + "." + t.Name() +} + +// escape a struct field tag string back to source code +func escapeTag(tag reflect.StructTag) string { + t := string(tag) + if strings.ContainsRune(t, '`') { + // there are ` in the string; we can't use ` to enclose the string + return strconv.Quote(t) + } + return "`" + t + "`" +} + +// uniqueVarName returns a file-unique name that can be used for generated variables. +func (g *Generator) uniqueVarName() string { + g.varCounter++ + return fmt.Sprint("v", g.varCounter) +} + +// safeName escapes unsafe characters in pkg/type name and returns a string that can be used +// in encoder/decoder names for the type. +func (g *Generator) safeName(t reflect.Type) string { + name := t.PkgPath() + if t.Name() == "" { + name += "anonymous" + } else { + name += "." + t.Name() + } + + parts := []string{} + part := []rune{} + for _, c := range name { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + part = append(part, c) + } else if len(part) > 0 { + parts = append(parts, string(part)) + part = []rune{} + } + } + return joinFunctionNameParts(false, parts...) +} + +// functionName returns a function name for a given type with a given prefix. If a function +// with this prefix already exists for a type, it is returned. +// +// Method is used to track encoder/decoder names for the type. +func (g *Generator) functionName(prefix string, t reflect.Type) string { + prefix = joinFunctionNameParts(true, "easyjson", g.hashString, prefix) + name := joinFunctionNameParts(true, prefix, g.safeName(t)) + + // Most of the names will be unique, try a shortcut first. + if e, ok := g.functionNames[name]; !ok || e == t { + g.functionNames[name] = t + return name + } + + // Search if the function already exists. + for name1, t1 := range g.functionNames { + if t1 == t && strings.HasPrefix(name1, prefix) { + return name1 + } + } + + // Create a new name in the case of a clash. + for i := 1; ; i++ { + nm := fmt.Sprint(name, i) + if _, ok := g.functionNames[nm]; ok { + continue + } + g.functionNames[nm] = t + return nm + } +} + +// DefaultFieldsNamer implements trivial naming policy equivalent to encoding/json. +type DefaultFieldNamer struct{} + +func (DefaultFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { + jsonName := strings.Split(f.Tag.Get("json"), ",")[0] + if jsonName != "" { + return jsonName + } else { + return f.Name + } +} + +// SnakeCaseFieldNamer implements CamelCase to snake_case conversion for fields names. +type SnakeCaseFieldNamer struct{} + +func camelToSnake(name string) string { + var ret bytes.Buffer + + multipleUpper := false + var lastUpper rune + var beforeUpper rune + + for _, c := range name { + // Non-lowercase character after uppercase is considered to be uppercase too. + isUpper := (unicode.IsUpper(c) || (lastUpper != 0 && !unicode.IsLower(c))) + + if lastUpper != 0 { + // Output a delimiter if last character was either the first uppercase character + // in a row, or the last one in a row (e.g. 'S' in "HTTPServer"). + // Do not output a delimiter at the beginning of the name. + + firstInRow := !multipleUpper + lastInRow := !isUpper + + if ret.Len() > 0 && (firstInRow || lastInRow) && beforeUpper != '_' { + ret.WriteByte('_') + } + ret.WriteRune(unicode.ToLower(lastUpper)) + } + + // Buffer uppercase char, do not output it yet as a delimiter may be required if the + // next character is lowercase. + if isUpper { + multipleUpper = (lastUpper != 0) + lastUpper = c + continue + } + + ret.WriteRune(c) + lastUpper = 0 + beforeUpper = c + multipleUpper = false + } + + if lastUpper != 0 { + ret.WriteRune(unicode.ToLower(lastUpper)) + } + return string(ret.Bytes()) +} + +func (SnakeCaseFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { + jsonName := strings.Split(f.Tag.Get("json"), ",")[0] + if jsonName != "" { + return jsonName + } + + return camelToSnake(f.Name) +} + +func joinFunctionNameParts(keepFirst bool, parts ...string) string { + buf := bytes.NewBufferString("") + for i, part := range parts { + if i == 0 && keepFirst { + buf.WriteString(part) + } else { + if len(part) > 0 { + buf.WriteString(strings.ToUpper(string(part[0]))) + } + if len(part) > 1 { + buf.WriteString(part[1:]) + } + } + } + return buf.String() +} diff --git a/accounts/vendor/github.com/mailru/easyjson/gen/generator_test.go b/accounts/vendor/github.com/mailru/easyjson/gen/generator_test.go new file mode 100644 index 000000000..62c03f084 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/gen/generator_test.go @@ -0,0 +1,65 @@ +package gen + +import ( + "testing" +) + +func TestCamelToSnake(t *testing.T) { + for i, test := range []struct { + In, Out string + }{ + {"", ""}, + {"A", "a"}, + {"SimpleExample", "simple_example"}, + {"internalField", "internal_field"}, + + {"SomeHTTPStuff", "some_http_stuff"}, + {"WriteJSON", "write_json"}, + {"HTTP2Server", "http2_server"}, + {"Some_Mixed_Case", "some_mixed_case"}, + {"do_nothing", "do_nothing"}, + + {"JSONHTTPRPCServer", "jsonhttprpc_server"}, // nothing can be done here without a dictionary + } { + got := camelToSnake(test.In) + if got != test.Out { + t.Errorf("[%d] camelToSnake(%s) = %s; want %s", i, test.In, got, test.Out) + } + } +} + +func TestJoinFunctionNameParts(t *testing.T) { + for i, test := range []struct { + keepFirst bool + parts []string + out string + }{ + {false, []string{}, ""}, + {false, []string{"a"}, "A"}, + {false, []string{"simple", "example"}, "SimpleExample"}, + {true, []string{"first", "example"}, "firstExample"}, + {false, []string{"some", "UPPER", "case"}, "SomeUPPERCase"}, + {false, []string{"number", "123"}, "Number123"}, + } { + got := joinFunctionNameParts(test.keepFirst, test.parts...) + if got != test.out { + t.Errorf("[%d] joinFunctionNameParts(%v) = %s; want %s", i, test.parts, got, test.out) + } + } +} + +func TestFixVendorPath(t *testing.T) { + for i, test := range []struct { + In, Out string + }{ + {"", ""}, + {"time", "time"}, + {"project/vendor/subpackage", "subpackage"}, + } { + got := fixPkgPathVendoring(test.In) + if got != test.Out { + t.Errorf("[%d] fixPkgPathVendoring(%s) = %s; want %s", i, test.In, got, test.Out) + } + } + +} diff --git a/accounts/vendor/github.com/mailru/easyjson/helpers.go b/accounts/vendor/github.com/mailru/easyjson/helpers.go new file mode 100644 index 000000000..b86b87d22 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/helpers.go @@ -0,0 +1,78 @@ +// Package easyjson contains marshaler/unmarshaler interfaces and helper functions. +package easyjson + +import ( + "io" + "io/ioutil" + "net/http" + "strconv" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// Marshaler is an easyjson-compatible marshaler interface. +type Marshaler interface { + MarshalEasyJSON(w *jwriter.Writer) +} + +// Marshaler is an easyjson-compatible unmarshaler interface. +type Unmarshaler interface { + UnmarshalEasyJSON(w *jlexer.Lexer) +} + +// Optional defines an undefined-test method for a type to integrate with 'omitempty' logic. +type Optional interface { + IsDefined() bool +} + +// Marshal returns data as a single byte slice. Method is suboptimal as the data is likely to be copied +// from a chain of smaller chunks. +func Marshal(v Marshaler) ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.BuildBytes() +} + +// MarshalToWriter marshals the data to an io.Writer. +func MarshalToWriter(v Marshaler, w io.Writer) (written int, err error) { + jw := jwriter.Writer{} + v.MarshalEasyJSON(&jw) + return jw.DumpTo(w) +} + +// MarshalToHTTPResponseWriter sets Content-Length and Content-Type headers for the +// http.ResponseWriter, and send the data to the writer. started will be equal to +// false if an error occurred before any http.ResponseWriter methods were actually +// invoked (in this case a 500 reply is possible). +func MarshalToHTTPResponseWriter(v Marshaler, w http.ResponseWriter) (started bool, written int, err error) { + jw := jwriter.Writer{} + v.MarshalEasyJSON(&jw) + if jw.Error != nil { + return false, 0, jw.Error + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(jw.Size())) + + started = true + written, err = jw.DumpTo(w) + return +} + +// Unmarshal decodes the JSON in data into the object. +func Unmarshal(data []byte, v Unmarshaler) error { + l := jlexer.Lexer{Data: data} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// UnmarshalFromReader reads all the data in the reader and decodes as JSON into the object. +func UnmarshalFromReader(r io.Reader, v Unmarshaler) error { + data, err := ioutil.ReadAll(r) + if err != nil { + return err + } + l := jlexer.Lexer{Data: data} + v.UnmarshalEasyJSON(&l) + return l.Error() +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go new file mode 100644 index 000000000..ff7b27c5b --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go @@ -0,0 +1,24 @@ +// This file will only be included to the build if neither +// easyjson_nounsafe nor appengine build tag is set. See README notes +// for more details. + +//+build !easyjson_nounsafe +//+build !appengine + +package jlexer + +import ( + "reflect" + "unsafe" +) + +// bytesToStr creates a string pointing at the slice to avoid copying. +// +// Warning: the string returned by the function should be used with care, as the whole input data +// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data +// may be garbage-collected even when the string exists. +func bytesToStr(data []byte) string { + h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) + shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} + return *(*string)(unsafe.Pointer(&shdr)) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go new file mode 100644 index 000000000..864d1be67 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go @@ -0,0 +1,13 @@ +// This file is included to the build if any of the buildtags below +// are defined. Refer to README notes for more details. + +//+build easyjson_nounsafe appengine + +package jlexer + +// bytesToStr creates a string normally from []byte +// +// Note that this method is roughly 1.5x slower than using the 'unsafe' method. +func bytesToStr(data []byte) string { + return string(data) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jlexer/error.go b/accounts/vendor/github.com/mailru/easyjson/jlexer/error.go new file mode 100644 index 000000000..e90ec40d0 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jlexer/error.go @@ -0,0 +1,15 @@ +package jlexer + +import "fmt" + +// LexerError implements the error interface and represents all possible errors that can be +// generated during parsing the JSON data. +type LexerError struct { + Reason string + Offset int + Data string +} + +func (l *LexerError) Error() string { + return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer.go new file mode 100644 index 000000000..e81f1031b --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer.go @@ -0,0 +1,1114 @@ +// Package jlexer contains a JSON lexer implementation. +// +// It is expected that it is mostly used with generated parser code, so the interface is tuned +// for a parser that knows what kind of data is expected. +package jlexer + +import ( + "encoding/base64" + "errors" + "fmt" + "io" + "strconv" + "unicode" + "unicode/utf16" + "unicode/utf8" +) + +// tokenKind determines type of a token. +type tokenKind byte + +const ( + tokenUndef tokenKind = iota // No token. + tokenDelim // Delimiter: one of '{', '}', '[' or ']'. + tokenString // A string literal, e.g. "abc\u1234" + tokenNumber // Number literal, e.g. 1.5e5 + tokenBool // Boolean literal: true or false. + tokenNull // null keyword. +) + +// token describes a single token: type, position in the input and value. +type token struct { + kind tokenKind // Type of a token. + + boolValue bool // Value if a boolean literal token. + byteValue []byte // Raw value of a token. + delimValue byte +} + +// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. +type Lexer struct { + Data []byte // Input data given to the lexer. + + start int // Start of the current token. + pos int // Current unscanned position in the input stream. + token token // Last scanned token, if token.kind != tokenUndef. + + firstElement bool // Whether current element is the first in array or an object. + wantSep byte // A comma or a colon character, which need to occur before a token. + + UseMultipleErrors bool // If we want to use multiple errors. + fatalError error // Fatal error occurred during lexing. It is usually a syntax error. + multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. +} + +// FetchToken scans the input for the next token. +func (r *Lexer) FetchToken() { + r.token.kind = tokenUndef + r.start = r.pos + + // Check if r.Data has r.pos element + // If it doesn't, it mean corrupted input data + if len(r.Data) < r.pos { + r.errParse("Unexpected end of data") + return + } + // Determine the type of a token by skipping whitespace and reading the + // first character. + for _, c := range r.Data[r.pos:] { + switch c { + case ':', ',': + if r.wantSep == c { + r.pos++ + r.start++ + r.wantSep = 0 + } else { + r.errSyntax() + } + + case ' ', '\t', '\r', '\n': + r.pos++ + r.start++ + + case '"': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenString + r.fetchString() + return + + case '{', '[': + if r.wantSep != 0 { + r.errSyntax() + } + r.firstElement = true + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return + + case '}', ']': + if !r.firstElement && (r.wantSep != ',') { + r.errSyntax() + } + r.wantSep = 0 + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return + + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': + if r.wantSep != 0 { + r.errSyntax() + } + r.token.kind = tokenNumber + r.fetchNumber() + return + + case 'n': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenNull + r.fetchNull() + return + + case 't': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenBool + r.token.boolValue = true + r.fetchTrue() + return + + case 'f': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenBool + r.token.boolValue = false + r.fetchFalse() + return + + default: + r.errSyntax() + return + } + } + r.fatalError = io.EOF + return +} + +// isTokenEnd returns true if the char can follow a non-delimiter token +func isTokenEnd(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' +} + +// fetchNull fetches and checks remaining bytes of null keyword. +func (r *Lexer) fetchNull() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'u' || + r.Data[r.pos-2] != 'l' || + r.Data[r.pos-1] != 'l' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 4 + r.errSyntax() + } +} + +// fetchTrue fetches and checks remaining bytes of true keyword. +func (r *Lexer) fetchTrue() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'r' || + r.Data[r.pos-2] != 'u' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 4 + r.errSyntax() + } +} + +// fetchFalse fetches and checks remaining bytes of false keyword. +func (r *Lexer) fetchFalse() { + r.pos += 5 + if r.pos > len(r.Data) || + r.Data[r.pos-4] != 'a' || + r.Data[r.pos-3] != 'l' || + r.Data[r.pos-2] != 's' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 5 + r.errSyntax() + } +} + +// fetchNumber scans a number literal token. +func (r *Lexer) fetchNumber() { + hasE := false + afterE := false + hasDot := false + + r.pos++ + for i, c := range r.Data[r.pos:] { + switch { + case c >= '0' && c <= '9': + afterE = false + case c == '.' && !hasDot: + hasDot = true + case (c == 'e' || c == 'E') && !hasE: + hasE = true + hasDot = true + afterE = true + case (c == '+' || c == '-') && afterE: + afterE = false + default: + r.pos += i + if !isTokenEnd(c) { + r.errSyntax() + } else { + r.token.byteValue = r.Data[r.start:r.pos] + } + return + } + } + + r.pos = len(r.Data) + r.token.byteValue = r.Data[r.start:] +} + +// findStringLen tries to scan into the string literal for ending quote char to determine required size. +// The size will be exact if no escapes are present and may be inexact if there are escaped chars. +func findStringLen(data []byte) (hasEscapes bool, length int) { + delta := 0 + + for i := 0; i < len(data); i++ { + switch data[i] { + case '\\': + i++ + delta++ + if i < len(data) && data[i] == 'u' { + delta++ + } + case '"': + return (delta > 0), (i - delta) + } + } + + return false, len(data) +} + +// getu4 decodes \uXXXX from the beginning of s, returning the hex value, +// or it returns -1. +func getu4(s []byte) rune { + if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { + return -1 + } + var val rune + for i := 2; i < len(s) && i < 6; i++ { + var v byte + c := s[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + v = c - '0' + case 'a', 'b', 'c', 'd', 'e', 'f': + v = c - 'a' + 10 + case 'A', 'B', 'C', 'D', 'E', 'F': + v = c - 'A' + 10 + default: + return -1 + } + + val <<= 4 + val |= rune(v) + } + return val +} + +// processEscape processes a single escape sequence and returns number of bytes processed. +func (r *Lexer) processEscape(data []byte) (int, error) { + if len(data) < 2 { + return 0, fmt.Errorf("syntax error at %v", string(data)) + } + + c := data[1] + switch c { + case '"', '/', '\\': + r.token.byteValue = append(r.token.byteValue, c) + return 2, nil + case 'b': + r.token.byteValue = append(r.token.byteValue, '\b') + return 2, nil + case 'f': + r.token.byteValue = append(r.token.byteValue, '\f') + return 2, nil + case 'n': + r.token.byteValue = append(r.token.byteValue, '\n') + return 2, nil + case 'r': + r.token.byteValue = append(r.token.byteValue, '\r') + return 2, nil + case 't': + r.token.byteValue = append(r.token.byteValue, '\t') + return 2, nil + case 'u': + rr := getu4(data) + if rr < 0 { + return 0, errors.New("syntax error") + } + + read := 6 + if utf16.IsSurrogate(rr) { + rr1 := getu4(data[read:]) + if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { + read += 6 + rr = dec + } else { + rr = unicode.ReplacementChar + } + } + var d [4]byte + s := utf8.EncodeRune(d[:], rr) + r.token.byteValue = append(r.token.byteValue, d[:s]...) + return read, nil + } + + return 0, errors.New("syntax error") +} + +// fetchString scans a string literal token. +func (r *Lexer) fetchString() { + r.pos++ + data := r.Data[r.pos:] + + hasEscapes, length := findStringLen(data) + if !hasEscapes { + r.token.byteValue = data[:length] + r.pos += length + 1 + return + } + + r.token.byteValue = make([]byte, 0, length) + p := 0 + for i := 0; i < len(data); { + switch data[i] { + case '"': + r.pos += i + 1 + r.token.byteValue = append(r.token.byteValue, data[p:i]...) + i++ + return + + case '\\': + r.token.byteValue = append(r.token.byteValue, data[p:i]...) + off, err := r.processEscape(data[i:]) + if err != nil { + r.errParse(err.Error()) + return + } + i += off + p = i + + default: + i++ + } + } + r.errParse("unterminated string literal") +} + +// scanToken scans the next token if no token is currently available in the lexer. +func (r *Lexer) scanToken() { + if r.token.kind != tokenUndef || r.fatalError != nil { + return + } + + r.FetchToken() +} + +// consume resets the current token to allow scanning the next one. +func (r *Lexer) consume() { + r.token.kind = tokenUndef + r.token.delimValue = 0 +} + +// Ok returns true if no error (including io.EOF) was encountered during scanning. +func (r *Lexer) Ok() bool { + return r.fatalError == nil +} + +const maxErrorContextLen = 13 + +func (r *Lexer) errParse(what string) { + if r.fatalError == nil { + var str string + if len(r.Data)-r.pos <= maxErrorContextLen { + str = string(r.Data) + } else { + str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: what, + Offset: r.pos, + Data: str, + } + } +} + +func (r *Lexer) errSyntax() { + r.errParse("syntax error") +} + +func (r *Lexer) errInvalidToken(expected string) { + if r.fatalError != nil { + return + } + if r.UseMultipleErrors { + r.pos = r.start + r.consume() + r.SkipRecursive() + switch expected { + case "[": + r.token.delimValue = ']' + r.token.kind = tokenDelim + case "{": + r.token.delimValue = '}' + r.token.kind = tokenDelim + } + r.addNonfatalError(&LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.start, + Data: string(r.Data[r.start:r.pos]), + }) + return + } + + var str string + if len(r.token.byteValue) <= maxErrorContextLen { + str = string(r.token.byteValue) + } else { + str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.pos, + Data: str, + } +} + +func (r *Lexer) GetPos() int { + return r.pos +} + +// Delim consumes a token and verifies that it is the given delimiter. +func (r *Lexer) Delim(c byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + + if !r.Ok() || r.token.delimValue != c { + r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. + r.errInvalidToken(string([]byte{c})) + } else { + r.consume() + } +} + +// IsDelim returns true if there was no scanning error and next token is the given delimiter. +func (r *Lexer) IsDelim(c byte) bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return !r.Ok() || r.token.delimValue == c +} + +// Null verifies that the next token is null and consumes it. +func (r *Lexer) Null() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNull { + r.errInvalidToken("null") + } + r.consume() +} + +// IsNull returns true if the next token is a null keyword. +func (r *Lexer) IsNull() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return r.Ok() && r.token.kind == tokenNull +} + +// Skip skips a single token. +func (r *Lexer) Skip() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + r.consume() +} + +// SkipRecursive skips next array or object completely, or just skips a single token if not +// an array/object. +// +// Note: no syntax validation is performed on the skipped data. +func (r *Lexer) SkipRecursive() { + r.scanToken() + var start, end byte + + if r.token.delimValue == '{' { + start, end = '{', '}' + } else if r.token.delimValue == '[' { + start, end = '[', ']' + } else { + r.consume() + return + } + + r.consume() + + level := 1 + inQuotes := false + wasEscape := false + + for i, c := range r.Data[r.pos:] { + switch { + case c == start && !inQuotes: + level++ + case c == end && !inQuotes: + level-- + if level == 0 { + r.pos += i + 1 + return + } + case c == '\\' && inQuotes: + wasEscape = !wasEscape + continue + case c == '"' && inQuotes: + inQuotes = wasEscape + case c == '"': + inQuotes = true + } + wasEscape = false + } + r.pos = len(r.Data) + r.fatalError = &LexerError{ + Reason: "EOF reached while skipping array/object or token", + Offset: r.pos, + Data: string(r.Data[r.pos:]), + } +} + +// Raw fetches the next item recursively as a data slice +func (r *Lexer) Raw() []byte { + r.SkipRecursive() + if !r.Ok() { + return nil + } + return r.Data[r.start:r.pos] +} + +// IsStart returns whether the lexer is positioned at the start +// of an input string. +func (r *Lexer) IsStart() bool { + return r.pos == 0 +} + +// Consumed reads all remaining bytes from the input, publishing an error if +// there is anything but whitespace remaining. +func (r *Lexer) Consumed() { + if r.pos > len(r.Data) || !r.Ok() { + return + } + + for _, c := range r.Data[r.pos:] { + if c != ' ' && c != '\t' && c != '\r' && c != '\n' { + r.AddError(&LexerError{ + Reason: "invalid character '" + string(c) + "' after top-level value", + Offset: r.pos, + Data: string(r.Data[r.pos:]), + }) + return + } + + r.pos++ + r.start++ + } +} + +func (r *Lexer) unsafeString() (string, []byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "", nil + } + bytes := r.token.byteValue + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret, bytes +} + +// UnsafeString returns the string value if the token is a string literal. +// +// Warning: returned string may point to the input buffer, so the string should not outlive +// the input buffer. Intended pattern of usage is as an argument to a switch statement. +func (r *Lexer) UnsafeString() string { + ret, _ := r.unsafeString() + return ret +} + +// UnsafeBytes returns the byte slice if the token is a string literal. +func (r *Lexer) UnsafeBytes() []byte { + _, ret := r.unsafeString() + return ret +} + +// String reads a string literal. +func (r *Lexer) String() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "" + } + ret := string(r.token.byteValue) + r.consume() + return ret +} + +// Bytes reads a string literal and base64 decodes it into a byte slice. +func (r *Lexer) Bytes() []byte { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return nil + } + ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) + len, err := base64.StdEncoding.Decode(ret, r.token.byteValue) + if err != nil { + r.fatalError = &LexerError{ + Reason: err.Error(), + } + return nil + } + + r.consume() + return ret[:len] +} + +// Bool reads a true or false boolean keyword. +func (r *Lexer) Bool() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenBool { + r.errInvalidToken("bool") + return false + } + ret := r.token.boolValue + r.consume() + return ret +} + +func (r *Lexer) number() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNumber { + r.errInvalidToken("number") + return "" + } + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret +} + +func (r *Lexer) Uint8() uint8 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint8(n) +} + +func (r *Lexer) Uint16() uint16 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint16(n) +} + +func (r *Lexer) Uint32() uint32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint32(n) +} + +func (r *Lexer) Uint64() uint64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Uint() uint { + return uint(r.Uint64()) +} + +func (r *Lexer) Int8() int8 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int8(n) +} + +func (r *Lexer) Int16() int16 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int16(n) +} + +func (r *Lexer) Int32() int32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int32(n) +} + +func (r *Lexer) Int64() int64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Int() int { + return int(r.Int64()) +} + +func (r *Lexer) Uint8Str() uint8 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint8(n) +} + +func (r *Lexer) Uint16Str() uint16 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint16(n) +} + +func (r *Lexer) Uint32Str() uint32 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint32(n) +} + +func (r *Lexer) Uint64Str() uint64 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return n +} + +func (r *Lexer) UintStr() uint { + return uint(r.Uint64Str()) +} + +func (r *Lexer) Int8Str() int8 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int8(n) +} + +func (r *Lexer) Int16Str() int16 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int16(n) +} + +func (r *Lexer) Int32Str() int32 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int32(n) +} + +func (r *Lexer) Int64Str() int64 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return n +} + +func (r *Lexer) IntStr() int { + return int(r.Int64Str()) +} + +func (r *Lexer) Float32() float32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseFloat(s, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return float32(n) +} + +func (r *Lexer) Float64() float64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseFloat(s, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Error() error { + return r.fatalError +} + +func (r *Lexer) AddError(e error) { + if r.fatalError == nil { + r.fatalError = e + } +} + +func (r *Lexer) AddNonFatalError(e error) { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Data: string(r.Data[r.start:r.pos]), + Reason: e.Error(), + }) +} + +func (r *Lexer) addNonfatalError(err *LexerError) { + if r.UseMultipleErrors { + // We don't want to add errors with the same offset. + if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { + return + } + r.multipleErrors = append(r.multipleErrors, err) + return + } + r.fatalError = err +} + +func (r *Lexer) GetNonFatalErrors() []*LexerError { + return r.multipleErrors +} + +// Interface fetches an interface{} analogous to the 'encoding/json' package. +func (r *Lexer) Interface() interface{} { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + + if !r.Ok() { + return nil + } + switch r.token.kind { + case tokenString: + return r.String() + case tokenNumber: + return r.Float64() + case tokenBool: + return r.Bool() + case tokenNull: + r.Null() + return nil + } + + if r.token.delimValue == '{' { + r.consume() + + ret := map[string]interface{}{} + for !r.IsDelim('}') { + key := r.String() + r.WantColon() + ret[key] = r.Interface() + r.WantComma() + } + r.Delim('}') + + if r.Ok() { + return ret + } else { + return nil + } + } else if r.token.delimValue == '[' { + r.consume() + + var ret []interface{} + for !r.IsDelim(']') { + ret = append(ret, r.Interface()) + r.WantComma() + } + r.Delim(']') + + if r.Ok() { + return ret + } else { + return nil + } + } + r.errSyntax() + return nil +} + +// WantComma requires a comma to be present before fetching next token. +func (r *Lexer) WantComma() { + r.wantSep = ',' + r.firstElement = false +} + +// WantColon requires a colon to be present before fetching next token. +func (r *Lexer) WantColon() { + r.wantSep = ':' + r.firstElement = false +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go b/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go new file mode 100644 index 000000000..b8a649898 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go @@ -0,0 +1,251 @@ +package jlexer + +import ( + "bytes" + "reflect" + "testing" +) + +func TestString(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: `"simple string"`, want: "simple string"}, + {toParse: " \r\r\n\t " + `"test"`, want: "test"}, + {toParse: `"\n\t\"\/\\\f\r"`, want: "\n\t\"/\\\f\r"}, + {toParse: `"\u0020"`, want: " "}, + {toParse: `"\u0020-\t"`, want: " -\t"}, + {toParse: `"\ufffd\uFFFD"`, want: "\ufffd\ufffd"}, + {toParse: `"\ud83d\ude00"`, want: "😀"}, + {toParse: `"\ud83d\ude08"`, want: "😈"}, + {toParse: `"\ud8"`, wantError: true}, + + {toParse: `"test"junk`, want: "test"}, + + {toParse: `5`, wantError: true}, // not a string + {toParse: `"\x"`, wantError: true}, // invalid escape + {toParse: `"\ud800"`, want: "�"}, // invalid utf-8 char; return replacement char + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.String() + if got != test.want { + t.Errorf("[%d, %q] String() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] String() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] String() ok; want error", i, test.toParse) + } + } +} + +func TestBytes(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: `"c2ltcGxlIHN0cmluZw=="`, want: "simple string"}, + {toParse: " \r\r\n\t " + `"dGVzdA=="`, want: "test"}, + + {toParse: `5`, wantError: true}, // not a JSON string + {toParse: `"foobar"`, wantError: true}, // not base64 encoded + {toParse: `"c2ltcGxlIHN0cmluZw="`, wantError: true}, // invalid base64 padding + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Bytes() + if bytes.Compare(got, []byte(test.want)) != 0 { + t.Errorf("[%d, %q] Bytes() = %v; want: %v", i, test.toParse, got, []byte(test.want)) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Bytes() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Bytes() ok; want error", i, test.toParse) + } + } +} + +func TestNumber(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: "123", want: "123"}, + {toParse: "-123", want: "-123"}, + {toParse: "\r\n12.35", want: "12.35"}, + {toParse: "12.35e+1", want: "12.35e+1"}, + {toParse: "12.35e-15", want: "12.35e-15"}, + {toParse: "12.35E-15", want: "12.35E-15"}, + {toParse: "12.35E15", want: "12.35E15"}, + + {toParse: `"a"`, wantError: true}, + {toParse: "123junk", wantError: true}, + {toParse: "1.2.3", wantError: true}, + {toParse: "1e2e3", wantError: true}, + {toParse: "1e2.3", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.number() + if got != test.want { + t.Errorf("[%d, %q] number() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] number() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] number() ok; want error", i, test.toParse) + } + } +} + +func TestBool(t *testing.T) { + for i, test := range []struct { + toParse string + want bool + wantError bool + }{ + {toParse: "true", want: true}, + {toParse: "false", want: false}, + + {toParse: "1", wantError: true}, + {toParse: "truejunk", wantError: true}, + {toParse: `false"junk"`, wantError: true}, + {toParse: "True", wantError: true}, + {toParse: "False", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Bool() + if got != test.want { + t.Errorf("[%d, %q] Bool() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Bool() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Bool() ok; want error", i, test.toParse) + } + } +} + +func TestSkipRecursive(t *testing.T) { + for i, test := range []struct { + toParse string + left string + wantError bool + }{ + {toParse: "5, 4", left: ", 4"}, + {toParse: "[5, 6], 4", left: ", 4"}, + {toParse: "[5, [7,8]]: 4", left: ": 4"}, + + {toParse: `{"a":1}, 4`, left: ", 4"}, + {toParse: `{"a":1, "b":{"c": 5}, "e":[12,15]}, 4`, left: ", 4"}, + + // array start/end chars in a string + {toParse: `[5, "]"], 4`, left: ", 4"}, + {toParse: `[5, "\"]"], 4`, left: ", 4"}, + {toParse: `[5, "["], 4`, left: ", 4"}, + {toParse: `[5, "\"["], 4`, left: ", 4"}, + + // object start/end chars in a string + {toParse: `{"a}":1}, 4`, left: ", 4"}, + {toParse: `{"a\"}":1}, 4`, left: ", 4"}, + {toParse: `{"a{":1}, 4`, left: ", 4"}, + {toParse: `{"a\"{":1}, 4`, left: ", 4"}, + + // object with double slashes at the end of string + {toParse: `{"a":"hey\\"}, 4`, left: ", 4"}, + } { + l := Lexer{Data: []byte(test.toParse)} + + l.SkipRecursive() + + got := string(l.Data[l.pos:]) + if got != test.left { + t.Errorf("[%d, %q] SkipRecursive() left = %v; want %v", i, test.toParse, got, test.left) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] SkipRecursive() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] SkipRecursive() ok; want error", i, test.toParse) + } + } +} + +func TestInterface(t *testing.T) { + for i, test := range []struct { + toParse string + want interface{} + wantError bool + }{ + {toParse: "null", want: nil}, + {toParse: "true", want: true}, + {toParse: `"a"`, want: "a"}, + {toParse: "5", want: float64(5)}, + + {toParse: `{}`, want: map[string]interface{}{}}, + {toParse: `[]`, want: []interface{}(nil)}, + + {toParse: `{"a": "b"}`, want: map[string]interface{}{"a": "b"}}, + {toParse: `[5]`, want: []interface{}{float64(5)}}, + + {toParse: `{"a":5 , "b" : "string"}`, want: map[string]interface{}{"a": float64(5), "b": "string"}}, + {toParse: `["a", 5 , null, true]`, want: []interface{}{"a", float64(5), nil, true}}, + + {toParse: `{"a" "b"}`, wantError: true}, + {toParse: `{"a": "b",}`, wantError: true}, + {toParse: `{"a":"b","c" "b"}`, wantError: true}, + {toParse: `{"a": "b","c":"d",}`, wantError: true}, + {toParse: `{,}`, wantError: true}, + + {toParse: `[1, 2,]`, wantError: true}, + {toParse: `[1 2]`, wantError: true}, + {toParse: `[,]`, wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Interface() + if !reflect.DeepEqual(got, test.want) { + t.Errorf("[%d, %q] Interface() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Interface() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Interface() ok; want error", i, test.toParse) + } + } +} + +func TestConsumed(t *testing.T) { + for i, test := range []struct { + toParse string + wantError bool + }{ + {toParse: "", wantError: false}, + {toParse: " ", wantError: false}, + {toParse: "\r\n", wantError: false}, + {toParse: "\t\t", wantError: false}, + + {toParse: "{", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + l.Consumed() + + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Consumed() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Consumed() ok; want error", i, test.toParse) + } + } +} diff --git a/accounts/vendor/github.com/mailru/easyjson/jwriter/writer.go b/accounts/vendor/github.com/mailru/easyjson/jwriter/writer.go new file mode 100644 index 000000000..7b55293a0 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/jwriter/writer.go @@ -0,0 +1,328 @@ +// Package jwriter contains a JSON writer. +package jwriter + +import ( + "encoding/base64" + "io" + "strconv" + "unicode/utf8" + + "github.com/mailru/easyjson/buffer" +) + +// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but +// Flags field in Writer is used to set and pass them around. +type Flags int + +const ( + NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. + NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. +) + +// Writer is a JSON writer. +type Writer struct { + Flags Flags + + Error error + Buffer buffer.Buffer + NoEscapeHTML bool +} + +// Size returns the size of the data that was written out. +func (w *Writer) Size() int { + return w.Buffer.Size() +} + +// DumpTo outputs the data to given io.Writer, resetting the buffer. +func (w *Writer) DumpTo(out io.Writer) (written int, err error) { + return w.Buffer.DumpTo(out) +} + +// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice +// as argument that it will try to reuse. +func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { + if w.Error != nil { + return nil, w.Error + } + + return w.Buffer.BuildBytes(reuse...), nil +} + +// ReadCloser returns an io.ReadCloser that can be used to read the data. +// ReadCloser also resets the buffer. +func (w *Writer) ReadCloser() (io.ReadCloser, error) { + if w.Error != nil { + return nil, w.Error + } + + return w.Buffer.ReadCloser(), nil +} + +// RawByte appends raw binary data to the buffer. +func (w *Writer) RawByte(c byte) { + w.Buffer.AppendByte(c) +} + +// RawByte appends raw binary data to the buffer. +func (w *Writer) RawString(s string) { + w.Buffer.AppendString(s) +} + +// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for +// calling with results of MarshalJSON-like functions. +func (w *Writer) Raw(data []byte, err error) { + switch { + case w.Error != nil: + return + case err != nil: + w.Error = err + case len(data) > 0: + w.Buffer.AppendBytes(data) + default: + w.RawString("null") + } +} + +// RawText encloses raw binary data in quotes and appends in to the buffer. +// Useful for calling with results of MarshalText-like functions. +func (w *Writer) RawText(data []byte, err error) { + switch { + case w.Error != nil: + return + case err != nil: + w.Error = err + case len(data) > 0: + w.String(string(data)) + default: + w.RawString("null") + } +} + +// Base64Bytes appends data to the buffer after base64 encoding it +func (w *Writer) Base64Bytes(data []byte) { + if data == nil { + w.Buffer.AppendString("null") + return + } + w.Buffer.AppendByte('"') + dst := make([]byte, base64.StdEncoding.EncodedLen(len(data))) + base64.StdEncoding.Encode(dst, data) + w.Buffer.AppendBytes(dst) + w.Buffer.AppendByte('"') +} + +func (w *Writer) Uint8(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint16(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint32(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint64(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) +} + +func (w *Writer) Int8(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int16(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int32(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int64(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) +} + +func (w *Writer) Uint8Str(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint16Str(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint32Str(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) UintStr(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint64Str(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int8Str(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int16Str(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int32Str(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) IntStr(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int64Str(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Float32(n float32) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) +} + +func (w *Writer) Float64(n float64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) +} + +func (w *Writer) Bool(v bool) { + w.Buffer.EnsureSpace(5) + if v { + w.Buffer.Buf = append(w.Buffer.Buf, "true"...) + } else { + w.Buffer.Buf = append(w.Buffer.Buf, "false"...) + } +} + +const chars = "0123456789abcdef" + +func isNotEscapedSingleChar(c byte, escapeHTML bool) bool { + // Note: might make sense to use a table if there are more chars to escape. With 4 chars + // it benchmarks the same. + if escapeHTML { + return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } else { + return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } +} + +func (w *Writer) String(s string) { + w.Buffer.AppendByte('"') + + // Portions of the string that contain no escapes are appended as + // byte slices. + + p := 0 // last non-escape symbol + + for i := 0; i < len(s); { + c := s[i] + + if isNotEscapedSingleChar(c, !w.NoEscapeHTML) { + // single-width character, no escaping is required + i++ + continue + } else if c < utf8.RuneSelf { + // single-with character, need to escape + w.Buffer.AppendString(s[p:i]) + switch c { + case '\t': + w.Buffer.AppendString(`\t`) + case '\r': + w.Buffer.AppendString(`\r`) + case '\n': + w.Buffer.AppendString(`\n`) + case '\\': + w.Buffer.AppendString(`\\`) + case '"': + w.Buffer.AppendString(`\"`) + default: + w.Buffer.AppendString(`\u00`) + w.Buffer.AppendByte(chars[c>>4]) + w.Buffer.AppendByte(chars[c&0xf]) + } + + i++ + p = i + continue + } + + // broken utf + runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) + if runeValue == utf8.RuneError && runeWidth == 1 { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\ufffd`) + i++ + p = i + continue + } + + // jsonp stuff - tab separator and line separator + if runeValue == '\u2028' || runeValue == '\u2029' { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\u202`) + w.Buffer.AppendByte(chars[runeValue&0xf]) + i += runeWidth + p = i + continue + } + i += runeWidth + } + w.Buffer.AppendString(s[p:]) + w.Buffer.AppendByte('"') +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go new file mode 100644 index 000000000..89e613265 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Bool struct { + V bool + Defined bool +} + +// Creates an optional type with a given value. +func OBool(v bool) Bool { + return Bool{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Bool) Get(deflt bool) bool { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Bool) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Bool(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Bool) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Bool{} + } else { + v.V = l.Bool() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Bool) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Bool) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Bool) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Bool) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go new file mode 100644 index 000000000..93ade1c72 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Float32 struct { + V float32 + Defined bool +} + +// Creates an optional type with a given value. +func OFloat32(v float32) Float32 { + return Float32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Float32) Get(deflt float32) float32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Float32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Float32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Float32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Float32{} + } else { + v.V = l.Float32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Float32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Float32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go new file mode 100644 index 000000000..90af91b03 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Float64 struct { + V float64 + Defined bool +} + +// Creates an optional type with a given value. +func OFloat64(v float64) Float64 { + return Float64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Float64) Get(deflt float64) float64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Float64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Float64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Float64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Float64{} + } else { + v.V = l.Float64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Float64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Float64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go new file mode 100644 index 000000000..71e74e830 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int struct { + V int + Defined bool +} + +// Creates an optional type with a given value. +func OInt(v int) Int { + return Int{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int) Get(deflt int) int { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int{} + } else { + v.V = l.Int() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go new file mode 100644 index 000000000..987e3df65 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int16 struct { + V int16 + Defined bool +} + +// Creates an optional type with a given value. +func OInt16(v int16) Int16 { + return Int16{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int16) Get(deflt int16) int16 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int16) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int16(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int16) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int16{} + } else { + v.V = l.Int16() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int16) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int16) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int16) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int16) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go new file mode 100644 index 000000000..e5f30d8c5 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int32 struct { + V int32 + Defined bool +} + +// Creates an optional type with a given value. +func OInt32(v int32) Int32 { + return Int32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int32) Get(deflt int32) int32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int32{} + } else { + v.V = l.Int32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go new file mode 100644 index 000000000..ff67a3353 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int64 struct { + V int64 + Defined bool +} + +// Creates an optional type with a given value. +func OInt64(v int64) Int64 { + return Int64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int64) Get(deflt int64) int64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int64{} + } else { + v.V = l.Int64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go new file mode 100644 index 000000000..41312d171 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int8 struct { + V int8 + Defined bool +} + +// Creates an optional type with a given value. +func OInt8(v int8) Int8 { + return Int8{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int8) Get(deflt int8) int8 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int8) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int8(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int8) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int8{} + } else { + v.V = l.Int8() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int8) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int8) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int8) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int8) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go new file mode 100644 index 000000000..3d818fa38 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type String struct { + V string + Defined bool +} + +// Creates an optional type with a given value. +func OString(v string) String { + return String{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v String) Get(deflt string) string { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v String) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.String(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *String) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = String{} + } else { + v.V = l.String() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *String) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *String) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v String) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v String) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go new file mode 100644 index 000000000..367db6759 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint struct { + V uint + Defined bool +} + +// Creates an optional type with a given value. +func OUint(v uint) Uint { + return Uint{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint) Get(deflt uint) uint { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint{} + } else { + v.V = l.Uint() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go new file mode 100644 index 000000000..6abc71dd3 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint16 struct { + V uint16 + Defined bool +} + +// Creates an optional type with a given value. +func OUint16(v uint16) Uint16 { + return Uint16{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint16) Get(deflt uint16) uint16 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint16) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint16(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint16) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint16{} + } else { + v.V = l.Uint16() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint16) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint16) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint16) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint16) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go new file mode 100644 index 000000000..490945c27 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint32 struct { + V uint32 + Defined bool +} + +// Creates an optional type with a given value. +func OUint32(v uint32) Uint32 { + return Uint32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint32) Get(deflt uint32) uint32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint32{} + } else { + v.V = l.Uint32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go new file mode 100644 index 000000000..37d2d418b --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint64 struct { + V uint64 + Defined bool +} + +// Creates an optional type with a given value. +func OUint64(v uint64) Uint64 { + return Uint64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint64) Get(deflt uint64) uint64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint64{} + } else { + v.V = l.Uint64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go new file mode 100644 index 000000000..55c4cdbae --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint8 struct { + V uint8 + Defined bool +} + +// Creates an optional type with a given value. +func OUint8(v uint8) Uint8 { + return Uint8{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint8) Get(deflt uint8) uint8 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint8) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint8(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint8) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint8{} + } else { + v.V = l.Uint8() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint8) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint8) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint8) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint8) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/optional/opt.go b/accounts/vendor/github.com/mailru/easyjson/opt/optional/opt.go new file mode 100644 index 000000000..6d3a07985 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/optional/opt.go @@ -0,0 +1,80 @@ +// +build none + +package optional + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) +type A int + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Optional struct { + V A + Defined bool +} + +// Creates an optional type with a given value. +func OOptional(v A) Optional { + return Optional{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Optional) Get(deflt A) A { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Optional) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Optional(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Optional) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Optional{} + } else { + v.V = l.Optional() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Optional) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Optional) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Optional) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Optional) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/opt/opts.go b/accounts/vendor/github.com/mailru/easyjson/opt/opts.go new file mode 100644 index 000000000..3617f7f9f --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/opt/opts.go @@ -0,0 +1,22 @@ +package opt + +//go:generate sed -i "s/\\+build none/generated by gotemplate/" optional/opt.go +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int(int) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint(uint) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int8(int8) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int16(int16) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int32(int32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int64(int64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint8(uint8) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint16(uint16) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint32(uint32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint64(uint64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float32(float32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float64(float64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Bool(bool) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" String(string) +//go:generate sed -i "s/generated by gotemplate/+build none/" optional/opt.go diff --git a/accounts/vendor/github.com/mailru/easyjson/parser/parser.go b/accounts/vendor/github.com/mailru/easyjson/parser/parser.go new file mode 100644 index 000000000..1c0b94caa --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/parser/parser.go @@ -0,0 +1,91 @@ +package parser + +import ( + "go/ast" + "go/parser" + "go/token" + "strings" +) + +const structComment = "easyjson:json" + +type Parser struct { + PkgPath string + PkgName string + StructNames []string + AllStructs bool +} + +type visitor struct { + *Parser + + name string + explicit bool +} + +func (p *Parser) needType(comments string) bool { + for _, v := range strings.Split(comments, "\n") { + if strings.HasPrefix(v, structComment) { + return true + } + } + return false +} + +func (v *visitor) Visit(n ast.Node) (w ast.Visitor) { + switch n := n.(type) { + case *ast.Package: + return v + case *ast.File: + v.PkgName = n.Name.String() + return v + + case *ast.GenDecl: + v.explicit = v.needType(n.Doc.Text()) + + if !v.explicit && !v.AllStructs { + return nil + } + return v + case *ast.TypeSpec: + v.name = n.Name.String() + + // Allow to specify non-structs explicitly independent of '-all' flag. + if v.explicit { + v.StructNames = append(v.StructNames, v.name) + return nil + } + return v + case *ast.StructType: + v.StructNames = append(v.StructNames, v.name) + return nil + } + return nil +} + +func (p *Parser) Parse(fname string, isDir bool) error { + var err error + if p.PkgPath, err = getPkgPath(fname, isDir); err != nil { + return err + } + + fset := token.NewFileSet() + if isDir { + packages, err := parser.ParseDir(fset, fname, nil, parser.ParseComments) + if err != nil { + return err + } + + for _, pckg := range packages { + ast.Walk(&visitor{Parser: p}, pckg) + } + } else { + f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments) + if err != nil { + return err + } + + ast.Walk(&visitor{Parser: p}, f) + } + return nil +} diff --git a/accounts/vendor/github.com/mailru/easyjson/parser/parser_unix.go b/accounts/vendor/github.com/mailru/easyjson/parser/parser_unix.go new file mode 100644 index 000000000..a1b9d84d1 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/parser/parser_unix.go @@ -0,0 +1,33 @@ +// +build !windows + +package parser + +import ( + "fmt" + "os" + "path" + "strings" +) + +func getPkgPath(fname string, isDir bool) (string, error) { + if !path.IsAbs(fname) { + pwd, err := os.Getwd() + if err != nil { + return "", err + } + fname = path.Join(pwd, fname) + } + + for _, p := range strings.Split(os.Getenv("GOPATH"), ":") { + prefix := path.Join(p, "src") + "/" + if rel := strings.TrimPrefix(fname, prefix); rel != fname { + if !isDir { + return path.Dir(rel), nil + } else { + return path.Clean(rel), nil + } + } + } + + return "", fmt.Errorf("file '%v' is not in GOPATH", fname) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/parser/parser_windows.go b/accounts/vendor/github.com/mailru/easyjson/parser/parser_windows.go new file mode 100644 index 000000000..64974aa97 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/parser/parser_windows.go @@ -0,0 +1,37 @@ +package parser + +import ( + "fmt" + "os" + "path" + "strings" +) + +func normalizePath(path string) string { + return strings.Replace(path, "\\", "/", -1) +} + +func getPkgPath(fname string, isDir bool) (string, error) { + if !path.IsAbs(fname) { + pwd, err := os.Getwd() + if err != nil { + return "", err + } + fname = path.Join(pwd, fname) + } + + fname = normalizePath(fname) + + for _, p := range strings.Split(os.Getenv("GOPATH"), ";") { + prefix := path.Join(normalizePath(p), "src") + "/" + if rel := strings.TrimPrefix(fname, prefix); rel != fname { + if !isDir { + return path.Dir(rel), nil + } else { + return path.Clean(rel), nil + } + } + } + + return "", fmt.Errorf("file '%v' is not in GOPATH", fname) +} diff --git a/accounts/vendor/github.com/mailru/easyjson/raw.go b/accounts/vendor/github.com/mailru/easyjson/raw.go new file mode 100644 index 000000000..81bd002e1 --- /dev/null +++ b/accounts/vendor/github.com/mailru/easyjson/raw.go @@ -0,0 +1,45 @@ +package easyjson + +import ( + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// RawMessage is a raw piece of JSON (number, string, bool, object, array or +// null) that is extracted without parsing and output as is during marshaling. +type RawMessage []byte + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v *RawMessage) MarshalEasyJSON(w *jwriter.Writer) { + if len(*v) == 0 { + w.RawString("null") + } else { + w.Raw(*v, nil) + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) { + *v = RawMessage(l.Raw()) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler interface. +func (v *RawMessage) UnmarshalJSON(data []byte) error { + *v = data + return nil +} + +var nullBytes = []byte("null") + +// MarshalJSON implements encoding/json.Marshaler interface. +func (v RawMessage) MarshalJSON() ([]byte, error) { + if len(v) == 0 { + return nullBytes, nil + } + return v, nil +} + +// IsDefined is required for integration with omitempty easyjson logic. +func (v *RawMessage) IsDefined() bool { + return len(*v) > 0 +} diff --git a/accounts/watch.go b/accounts/watch.go index 899fb7ec3..52b054d5c 100644 --- a/accounts/watch.go +++ b/accounts/watch.go @@ -27,14 +27,15 @@ import ( ) type watcher struct { - ac *addrCache + ac caching starting bool running bool ev chan notify.EventInfo + //evs []notify.EventInfo quit chan struct{} } -func newWatcher(ac *addrCache) *watcher { +func newWatcher(ac caching) *watcher { return &watcher{ ac: ac, ev: make(chan notify.EventInfo, 10), @@ -59,24 +60,24 @@ func (w *watcher) close() { func (w *watcher) loop() { defer func() { - w.ac.mu.Lock() + w.ac.muLock() w.running = false w.starting = false - w.ac.mu.Unlock() + w.ac.muUnlock() }() - err := notify.Watch(w.ac.keydir, w.ev, notify.All) + err := notify.Watch(w.ac.getKeydir(), w.ev, notify.All) if err != nil { - glog.V(logger.Detail).Infof("can't watch %s: %v", w.ac.keydir, err) + glog.V(logger.Detail).Infof("can't watch %s: %v", w.ac.getKeydir(), err) return } defer notify.Stop(w.ev) - glog.V(logger.Detail).Infof("now watching %s", w.ac.keydir) - defer glog.V(logger.Detail).Infof("no longer watching %s", w.ac.keydir) + glog.V(logger.Detail).Infof("now watching %s", w.ac.getKeydir()) + defer glog.V(logger.Detail).Infof("no longer watching %s", w.ac.getKeydir()) - w.ac.mu.Lock() + w.ac.muLock() w.running = true - w.ac.mu.Unlock() + w.ac.muUnlock() // Wait for file system events and reload. // When an event occurs, the reload call is delayed a bit so that @@ -98,13 +99,16 @@ func (w *watcher) loop() { } else { hadEvent = true } + //w.evs = append(w.evs, <-w.ev) case <-debounce.C: - w.ac.mu.Lock() + w.ac.muLock() + //w.evs = w.ac.reload(w.evs) w.ac.reload() - w.ac.mu.Unlock() + w.ac.muUnlock() if hadEvent { debounce.Reset(debounceDuration) inCycle, hadEvent = true, false + } else { inCycle, hadEvent = false, false } diff --git a/cmd/evm/main.go b/cmd/evm/main.go index 877bc277c..aa462f594 100644 --- a/cmd/evm/main.go +++ b/cmd/evm/main.go @@ -164,7 +164,7 @@ func run(ctx *cli.Context) error { if ctx.GlobalBool(DumpFlag.Name) { statedb.Commit() - fmt.Println(string(statedb.Dump())) + fmt.Println(string(statedb.Dump([]common.Address{}))) } if ctx.GlobalBool(SysStatFlag.Name) { diff --git a/cmd/geth/accountcmd.go b/cmd/geth/accountcmd.go index ba4bcb45e..86ac42a96 100644 --- a/cmd/geth/accountcmd.go +++ b/cmd/geth/accountcmd.go @@ -30,6 +30,10 @@ import ( ) var ( + AccountsIndexFlag = cli.BoolFlag{ + Name: "index-accounts,indexaccounts", + Usage: "enable key-value db store for indexing large amounts of key files", + } walletCommand = cli.Command{ Name: "wallet", Usage: "ethereum presale wallet", @@ -163,13 +167,49 @@ this import mechanism is not needed when you transfer an account between nodes. `, }, + { + Action: accountIndex, + Name: "index", + Usage: "build account index cache database", + Description: ` + + ethereum --index-accounts account index + +Create keystore directory index cache database (keystore/accounts.db). Relevant for use with large amounts of key files (>10,000). + +While idempotent, this command is only designed to segregate work and setup time for initial index creation. + +It is only useful to run once when it's your first time using '--index-accounts' flag option. + +It indexes all key files from keystore/* (non-recursively). + + `, + }, }, } ) +func accountIndex(ctx *cli.Context) error { + n := aliasableName(AccountsIndexFlag.Name, ctx) + if !ctx.GlobalBool(n) { + log.Fatalf("Use: $ geth --%v account index\n (missing '%v' flag)", n, n) + } + am := MakeAccountManager(ctx) + errs := am.BuildIndexDB() + if len(errs) > 0 { + for _, e := range errs { + if e != nil { + glog.V(logger.Error).Infof("init cache db err: %v", e) + } + } + } + return nil +} + func accountList(ctx *cli.Context) error { accman := MakeAccountManager(ctx) for i, acct := range accman.Accounts() { + fmt.Printf("Account #%d: {%x} %s\n", i, acct.Address, acct.File) } return nil diff --git a/cmd/geth/accountdb.bats b/cmd/geth/accountdb.bats new file mode 100644 index 000000000..1fdaa73e0 --- /dev/null +++ b/cmd/geth/accountdb.bats @@ -0,0 +1,164 @@ +#!/usr/bin/env bats + +: ${GETH_CMD:=$GOPATH/bin/geth} + +setup() { + DATA_DIR=`mktemp -d` + mkdir "$DATA_DIR/mainnet" +} + +teardown() { + rm -fr $DATA_DIR +} + +@test "account list blanko" { + run $GETH_CMD --datadir $DATA_DIR account + echo "$output" + + [ "$status" -eq 0 ] + [ "$output" = "" ] +} + +@test "account list testdata keystore (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + + run $GETH_CMD --datadir $DATA_DIR --index-accounts account + echo "$output" + + [ "$status" -eq 0 ] + # Note: cachedb stores files relative to keystore dir, while mem stores absolute paths. + # (whilei): I prefer relative to dir in case user wants to move keystore then paths will remain stable and not need to be reindexed. + # Also, both mem and cache implementations only scan 1 level (not recursively) and thus absolute path is unnecessarily verbose. + [ "${lines[0]}" == "Account #0: {7ef5a6135f1fd6a02593eedc869c6d41d934aef8} UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8" ] + [ "${lines[1]}" == "Account #1: {f466859ead1932d743d622cb74fc058882e8648a} aaa" ] + [ "${lines[2]}" == "Account #2: {289d485d9771714cce91d3393d764e1311907acc} zzz" ] +} + +@test "account create (db)" { + run $GETH_CMD --datadir $DATA_DIR --lightkdf --index-accounts account new <<< $'secret\nsecret\n' + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" =~ Address:.\{[0-9a-f]{40}\}$ ]] +} + +@test "account create pass mismatch (db)" { + run $GETH_CMD --datadir $DATA_DIR --lightkdf --index-accounts account new <<< $'secret\nother\n' + echo "$output" + + [ "$status" -ne 0 ] + [[ "$output" == *"Passphrases do not match" ]] +} + +@test "account update pass (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + + run $GETH_CMD --datadir $DATA_DIR --lightkdf --index-accounts account update f466859ead1932d743d622cb74fc058882e8648a <<< $'foobar\nother\nother\n' + echo "$output" + + [ "$status" -eq 0 ] +} + +@test "account import (db)" { + run $GETH_CMD --datadir $DATA_DIR --lightkdf --index-accounts wallet import $BATS_TEST_DIRNAME/testdata/guswallet.json <<< $'foo\n' + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" == *"Address: {d4584b5f6229b7be90727b0fc8c6b91bb427821f}" ]] + + echo "=== data dir files:" + ls $DATA_DIR/mainnet/keystore + [ $(ls $DATA_DIR/mainnet/keystore | wc -l) -eq 2 ] # keyfile + accounts.db +} + +@test "account import pass mismatch (db)" { + run $GETH_CMD --datadir $DATA_DIR --lightkdf --index-accounts wallet import $BATS_TEST_DIRNAME/testdata/guswallet.json <<< $'wrong\n' + echo "$output" + + [ "$status" -ne 0 ] + [[ "$output" == *"could not decrypt key with given passphrase" ]] +} + +@test "account unlock (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + touch $DATA_DIR/empty.js + + run $GETH_CMD --datadir $DATA_DIR --index-accounts --nat none --nodiscover --dev --unlock f466859ead1932d743d622cb74fc058882e8648a js $DATA_DIR/empty.js <<< $'foobar\n' + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" == *"Unlocked account f466859ead1932d743d622cb74fc058882e8648a"* ]] +} + +@test "account unlock pass mismatch (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + touch $DATA_DIR/empty.js + + run $GETH_CMD --datadir $DATA_DIR --index-accounts --nat none --nodiscover --dev --unlock f466859ead1932d743d622cb74fc058882e8648a js $DATA_DIR/empty.js <<< $'wrong1\nwrong2\nwrong3\n' + echo "$output" + + [ "$status" -ne 0 ] + [[ "$output" == *"Failed to unlock account f466859ead1932d743d622cb74fc058882e8648a (could not decrypt key with given passphrase)" ]] +} + +@test "account unlock multiple (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + touch $DATA_DIR/empty.js + + run $GETH_CMD --datadir $DATA_DIR --index-accounts --nat none --nodiscover --dev --unlock 0,2 js $DATA_DIR/empty.js <<< $'foobar\nfoobar\n' + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" == *"Unlocked account 7ef5a6135f1fd6a02593eedc869c6d41d934aef8"* ]] + [[ "$output" == *"Unlocked account 289d485d9771714cce91d3393d764e1311907acc"* ]] +} + +@test "account unlock multiple with pass file (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + touch $DATA_DIR/empty.js + echo $'foobar\nfoobar\nfoobar\n' > $DATA_DIR/pass.txt + + run $GETH_CMD --datadir $DATA_DIR --index-accounts --nat none --nodiscover --dev --password $DATA_DIR/pass.txt --unlock 0,2 js $DATA_DIR/empty.js + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" == *"Unlocked account 7ef5a6135f1fd6a02593eedc869c6d41d934aef8"* ]] + [[ "$output" == *"Unlocked account 289d485d9771714cce91d3393d764e1311907acc"* ]] +} + +@test "account unlock multiple with wrong pass file (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/keystore $DATA_DIR/mainnet + touch $DATA_DIR/empty.js + echo $'wrong\nwrong\nwrong\n' > $DATA_DIR/pass.txt + + run $GETH_CMD --datadir $DATA_DIR --nat none --index-accounts --nodiscover --dev --password $DATA_DIR/pass.txt --unlock 0,2 js $DATA_DIR/empty.js + echo "$output" + + [ "$status" -ne 0 ] + [[ "$output" == *"Failed to unlock account 0 (could not decrypt key with given passphrase)" ]] +} + +@test "account unlock ambiguous (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/dupes $DATA_DIR/mainnet/store + touch $DATA_DIR/empty.js + + run $GETH_CMD --datadir $DATA_DIR --keystore $DATA_DIR/mainnet/store --index-accounts --nat none --nodiscover --dev --unlock f466859ead1932d743d622cb74fc058882e8648a js $DATA_DIR/empty.js <<< $'foobar\n'$DATA_DIR/store/1 + echo "$output" + + [ "$status" -eq 0 ] + [[ "$output" == *"Multiple key files exist for address f466859ead1932d743d622cb74fc058882e8648a:"* ]] + [[ "$output" == *"Your passphrase unlocked 1"* ]] + [[ "$output" == *"Unlocked account f466859ead1932d743d622cb74fc058882e8648a"* ]] +} + +@test "account unlock ambiguous pass mismatch (db)" { + cp -R $BATS_TEST_DIRNAME/../../accounts/testdata/dupes $DATA_DIR/store + touch $DATA_DIR/empty.js + + run $GETH_CMD --datadir $DATA_DIR --keystore $DATA_DIR/store --index-accounts --nat none --nodiscover --dev --unlock f466859ead1932d743d622cb74fc058882e8648a js $DATA_DIR/empty.js <<< $'wrong\n'$DATA_DIR/store/1 + echo "$output" + + [ "$status" -ne 0 ] + [[ "$output" == *"Multiple key files exist for address f466859ead1932d743d622cb74fc058882e8648a:"* ]] + [[ "$output" == *"None of the listed files could be unlocked."* ]] +} diff --git a/cmd/geth/chaincmd.go b/cmd/geth/chaincmd.go index 210cc4f7f..7cec089d8 100644 --- a/cmd/geth/chaincmd.go +++ b/cmd/geth/chaincmd.go @@ -24,6 +24,7 @@ import ( "strconv" "time" + "encoding/json" "github.com/ethereumproject/go-ethereum/common" "github.com/ethereumproject/go-ethereum/console" "github.com/ethereumproject/go-ethereum/core" @@ -31,6 +32,7 @@ import ( "github.com/ethereumproject/go-ethereum/core/types" "github.com/ethereumproject/go-ethereum/logger/glog" "gopkg.in/urfave/cli.v1" + "strings" ) var ( @@ -82,10 +84,10 @@ Use "ethereum dump 0" to dump the genesis block. `, } rollbackCommand = cli.Command{ - Action: rollback, - Name: "rollback", + Action: rollback, + Name: "rollback", Aliases: []string{"roll-back", "set-head", "sethead"}, - Usage: "rollback [block index number] - set current head for blockchain", + Usage: "rollback [block index number] - set current head for blockchain", Description: ` Rollback set the current head block for block chain already in the database. This is a destructive action, purging any block more recent than the index specified. @@ -191,14 +193,44 @@ func upgradeDB(ctx *cli.Context) error { return nil } +// Original use allows n hashes|ints as space-separated arguments, dumping entire state for each block n[x]. +// $ geth dump [hash|num] [hash|num] ... [hash|num] +// $ geth dump 0x234234234234233 42 43 0xlksdf234r23r234223 +// +// Revised use allows n hashes|ints as comma-separated first argument and n addresses as comma-separated second argument, +// dumping only state information for given addresses if they're present. +// revised use: $ geth dump [hash|num],[hash|num],...,[hash|num] [address],[address],...,[address] func dump(ctx *cli.Context) error { + + if ctx.NArg() == 0 { + return fmt.Errorf("%v: use: $ geth dump [blockHash|blockNum],[blockHash|blockNum] [[addressHex|addressPrefixedHex],[addressHex|addressPrefixedHex]]", ErrInvalidFlag) + } + + blocks := strings.Split(ctx.Args()[0], ",") + addresses := []common.Address{} + argaddress := "" + if ctx.NArg() > 1 { + argaddress = ctx.Args()[1] + } + + if argaddress != "" { + argaddresses := strings.Split(argaddress, ",") + for _, a := range argaddresses { + addresses = append(addresses, common.HexToAddress(strings.TrimSpace(a))) + } + } + chain, chainDb := MakeChain(ctx) - for _, arg := range ctx.Args() { + defer chainDb.Close() + + dumps := state.Dumps{} + for _, b := range blocks { + b = strings.TrimSpace(b) var block *types.Block - if hashish(arg) { - block = chain.GetBlock(common.HexToHash(arg)) + if hashish(b) { + block = chain.GetBlock(common.HexToHash(b)) } else { - num, _ := strconv.Atoi(arg) + num, _ := strconv.Atoi(b) block = chain.GetBlockByNumber(uint64(num)) } if block == nil { @@ -207,12 +239,23 @@ func dump(ctx *cli.Context) error { } else { state, err := state.New(block.Root(), chainDb) if err != nil { - log.Fatal("could not create new state: ", err) + return fmt.Errorf("could not create new state: %v", err) + } + + if len(blocks) > 1 { + dumps = append(dumps, state.RawDump(addresses)) + } else { + fmt.Printf("%s\n", state.Dump(addresses)) + return nil } - fmt.Printf("%s\n", state.Dump()) } } - chainDb.Close() + json, err := json.MarshalIndent(dumps, "", " ") + if err != nil { + return fmt.Errorf("dump err: %v", err) + } + fmt.Printf("%s\n", json) + return nil } diff --git a/cmd/geth/cli.bats b/cmd/geth/cli.bats index 673a40f82..201bb326b 100644 --- a/cmd/geth/cli.bats +++ b/cmd/geth/cli.bats @@ -165,6 +165,92 @@ teardown() { [[ "$output" == *"Alloted 17MB cache"* ]] } +# Test `dump` command. +# All tests copy testdata/testdatadir to $DATA_DIR to ensure we're consistently testing against a not-only-init'ed chaindb. +@test "dump [noargs] | exit >0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump + echo "$output" + [ "$status" -gt 0 ] + [[ "$output" == *"invalid"* ]] # invalid use +} +@test "dump 0 [noaddress] | exit 0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump 0 + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" == *"root"* ]] # block state root + [[ "$output" == *"balance"* ]] + [[ "$output" == *"accounts"* ]] + [[ "$output" == *"d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"* ]] # block state root + [[ "$output" == *"ffec0913c635baca2f5e57a37aa9fb7b6c9b6e26"* ]] # random hex address existing in genesis + [[ "$output" == *"253319000000000000000"* ]] # random address balance existing in genesis +} +@test "dump 0 fff7ac99c8e4feb60c9750054bdc14ce1857f181 | exit 0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump 0 fff7ac99c8e4feb60c9750054bdc14ce1857f181 + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" == *"root"* ]] # block state root + [[ "$output" == *"balance"* ]] + [[ "$output" == *"accounts"* ]] + [[ "$output" == *"d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"* ]] # block state root + [[ "$output" == *"fff7ac99c8e4feb60c9750054bdc14ce1857f181"* ]] # hex address + [[ "$output" == *"1000000000000000000000"* ]] # address balance +} +@test "dump 0 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f | exit 0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump 0 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" == *"root"* ]] # block state root + [[ "$output" == *"balance"* ]] + [[ "$output" == *"accounts"* ]] + [[ "$output" == *"d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"* ]] # block 0 state root + + [[ "$output" == *"fff7ac99c8e4feb60c9750054bdc14ce1857f181"* ]] # hex address + [[ "$output" == *"1000000000000000000000"* ]] # address balance + + [[ "$output" == *"ffe8cbc1681e5e9db74a0f93f8ed25897519120f"* ]] # hex address + [[ "$output" == *"1507000000000000000000"* ]] # address balance +} + +@test "dump 0,1 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f | exit 0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump 0,1 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" == *"root"* ]] # block state root + [[ "$output" == *"balance"* ]] + [[ "$output" == *"accounts"* ]] + + [[ "$output" == *"d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"* ]] # block 0 state root + [[ "$output" == *"d67e4d450343046425ae4271474353857ab860dbc0a1dde64b41b5cd3a532bf3"* ]] # block 1 state root + + [[ "$output" == *"fff7ac99c8e4feb60c9750054bdc14ce1857f181"* ]] # hex address + [[ "$output" == *"1000000000000000000000"* ]] # address balance + + [[ "$output" == *"ffe8cbc1681e5e9db74a0f93f8ed25897519120f"* ]] # hex address + [[ "$output" == *"1507000000000000000000"* ]] # address balance +} +@test "dump 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f | exit 0" { + cp -a $BATS_TEST_DIRNAME/../../cmd/geth/testdata/testdatadir/. $DATA_DIR/ + run $GETH_CMD --data-dir $DATA_DIR dump 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3 fff7ac99c8e4feb60c9750054bdc14ce1857f181,0xffe8cbc1681e5e9db74a0f93f8ed25897519120f + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" == *"root"* ]] # block state root + [[ "$output" == *"balance"* ]] + [[ "$output" == *"accounts"* ]] + + [[ "$output" == *"d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"* ]] # block 0 state root + + [[ "$output" == *"fff7ac99c8e4feb60c9750054bdc14ce1857f181"* ]] # hex address + [[ "$output" == *"1000000000000000000000"* ]] # address balance + + [[ "$output" == *"ffe8cbc1681e5e9db74a0f93f8ed25897519120f"* ]] # hex address + [[ "$output" == *"1507000000000000000000"* ]] # address balance +} + # Ensure --testnet and --chain=morden/testnet set up respective subdirs with default 'morden' @test "--chain=testnet creates /morden subdir, activating testnet genesis" { # This is kind of weird, but it is expected. run $GETH_CMD --data-dir $DATA_DIR --chain=testnet --exec 'eth.getBlock(0).hash' console @@ -199,3 +285,4 @@ teardown() { [ -d $DATA_DIR/morden ] } + diff --git a/cmd/geth/flag.go b/cmd/geth/flag.go index 07b16f016..8706f8dd5 100644 --- a/cmd/geth/flag.go +++ b/cmd/geth/flag.go @@ -305,7 +305,7 @@ func MakeAccountManager(ctx *cli.Context) *accounts.Manager { keydir = path } - m, err := accounts.NewManager(keydir, scryptN, scryptP) + m, err := accounts.NewManager(keydir, scryptN, scryptP, ctx.GlobalBool(aliasableName(AccountsIndexFlag.Name, ctx))) if err != nil { glog.Fatalf("init account manager at %q: %s", keydir, err) } diff --git a/cmd/geth/flag_test.go b/cmd/geth/flag_test.go index 2515bb464..c18c53380 100644 --- a/cmd/geth/flag_test.go +++ b/cmd/geth/flag_test.go @@ -9,6 +9,8 @@ import ( "github.com/ethereumproject/go-ethereum/common" "gopkg.in/urfave/cli.v1" + "github.com/ethereumproject/go-ethereum/accounts" + "reflect" ) var ogHome string // placeholder @@ -227,3 +229,22 @@ func TestMakeBootstrapNodesFromContext4(t *testing.T) { rmTmpDataDir(t) } +func TestMakeAddress(t *testing.T) { + accAddr := "f466859ead1932d743d622cb74fc058882e8648a" // account[0] address + cachetestdir := filepath.Join("accounts", "testdata", "keystore") + am, err := accounts.NewManager(cachetestdir, accounts.LightScryptN, accounts.LightScryptP, false) + if err != nil { + t.Fatal(err) + } + gotAccount, e := MakeAddress(am, accAddr) + if e != nil { + t.Fatalf("makeaddress: %v", e) + } + wantAccount := accounts.Account{ + Address: common.HexToAddress(accAddr), + } + // compare all + if !reflect.DeepEqual(wantAccount, gotAccount) { + t.Fatalf("want: %v, got: %v", wantAccount, gotAccount) + } +} \ No newline at end of file diff --git a/cmd/geth/flags.go b/cmd/geth/flags.go index 21e4dace1..200dfe2d5 100644 --- a/cmd/geth/flags.go +++ b/cmd/geth/flags.go @@ -12,6 +12,7 @@ import ( "github.com/ethereumproject/go-ethereum/logger/glog" "github.com/ethereumproject/go-ethereum/rpc" "gopkg.in/urfave/cli.v1" + "path/filepath" ) // These are all the command line flags we support. @@ -153,6 +154,11 @@ var ( Usage: "Per-module verbosity: comma-separated list of = (e.g. eth/*=6,p2p=5)", Value: glog.GetVModule(), } + LogDirFlag = DirectoryFlag{ + Name: "log-dir,logdir", + Usage: "Directory in which to write log files", + Value: DirectoryString{filepath.Join(common.DefaultDataDir(), "logs")}, + } BacktraceAtFlag = cli.GenericFlag{ Name: "backtrace", Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\")", diff --git a/cmd/geth/main.go b/cmd/geth/main.go index d2f46bb8a..d2ad1ee29 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -111,6 +111,7 @@ The output of this command is supposed to be machine-readable. IdentityFlag, UnlockedAccountFlag, PasswordFileFlag, + AccountsIndexFlag, BootnodesFlag, DataDirFlag, DocRootFlag, @@ -158,6 +159,7 @@ The output of this command is supposed to be machine-readable. RPCCORSDomainFlag, VerbosityFlag, VModuleFlag, + LogDirFlag, BacktraceAtFlag, MetricsFlag, FakePoWFlag, @@ -193,7 +195,19 @@ The output of this command is supposed to be machine-readable. runtime.GOMAXPROCS(runtime.NumCPU()) glog.CopyStandardLogTo("INFO") - glog.SetToStderr(true) + + if ctx.GlobalIsSet(aliasableName(LogDirFlag.Name, ctx)) { + + if p := ctx.GlobalString(aliasableName(LogDirFlag.Name, ctx)); p != "" { + // mkdir -p /path/to/log_dir + if e := os.MkdirAll(p, os.ModePerm); e != nil { + return e + } + glog.SetLogDir(p) + } + } else { + glog.SetToStderr(true) // I don't know why... + } if s := ctx.String("metrics"); s != "" { go metrics.Collect(s) diff --git a/cmd/gethrpctest/main.go b/cmd/gethrpctest/main.go index 3c7ee2064..1101f0b59 100644 --- a/cmd/gethrpctest/main.go +++ b/cmd/gethrpctest/main.go @@ -118,7 +118,7 @@ func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node return nil, err } // Create the keystore and inject an unlocked account if requested - accman, err := accounts.NewManager(keydir, accounts.LightScryptN, accounts.LightScryptP) + accman, err := accounts.NewManager(keydir, accounts.LightScryptN, accounts.LightScryptP, false) if err != nil { return nil, err } diff --git a/console/console_test.go b/console/console_test.go index 47a770349..b72eed84d 100644 --- a/console/console_test.go +++ b/console/console_test.go @@ -88,7 +88,7 @@ func newTester(t *testing.T, confOverride func(*eth.Config)) *tester { if err != nil { t.Fatalf("failed to create temporary keystore: %v", err) } - accman, err := accounts.NewManager(filepath.Join(workspace, "keystore"), accounts.LightScryptN, accounts.LightScryptP) + accman, err := accounts.NewManager(filepath.Join(workspace, "keystore"), accounts.LightScryptN, accounts.LightScryptP, false) if err != nil { t.Fatalf("failed to create account manager: %s", err) } diff --git a/core/config.go b/core/config.go index 4342bb41e..6b76431ec 100644 --- a/core/config.go +++ b/core/config.go @@ -688,7 +688,7 @@ func MakeGenesisDump(chaindb ethdb.Database) (*GenesisDump, error) { if err != nil { return nil, err } - stateDump := genState.RawDump() + stateDump := genState.RawDump([]common.Address{}) stateAccounts := stateDump.Accounts dump.Alloc = make(map[hex]*GenesisDumpAlloc, len(stateAccounts)) diff --git a/core/config_test.go b/core/config_test.go index b0a6a150a..6ff3e60e2 100644 --- a/core/config_test.go +++ b/core/config_test.go @@ -111,11 +111,16 @@ func TestChainConfig_IsExplosion(t *testing.T) { func sameGenesisDumpAllocationsBalances(gd1, gd2 *GenesisDump) bool { for address, alloc := range gd2.Alloc { - bal1, _ := new(big.Int).SetString(gd1.Alloc[address].Balance, 0) - bal2, _ := new(big.Int).SetString(alloc.Balance, 0) - if bal1.Cmp(bal2) != 0 { + if gd1.Alloc[address] != nil { + bal1, _ := new(big.Int).SetString(gd1.Alloc[address].Balance, 0) + bal2, _ := new(big.Int).SetString(alloc.Balance, 0) + if bal1.Cmp(bal2) != 0 { + return false + } + } else if alloc.Balance != "" { return false } + } return true } diff --git a/core/state/dump.go b/core/state/dump.go index 78ecee147..687287381 100644 --- a/core/state/dump.go +++ b/core/state/dump.go @@ -33,12 +33,24 @@ type DumpAccount struct { Storage map[string]string `json:"storage"` } +type Dumps []Dump + type Dump struct { Root string `json:"root"` Accounts map[string]DumpAccount `json:"accounts"` } -func (self *StateDB) RawDump() Dump { +func lookupAddress(addr common.Address, addresses []common.Address) bool { + for _, add := range addresses { + if add.Hex() == addr.Hex() { + return true + } + } + return false +} + +func (self *StateDB) RawDump(addresses []common.Address) Dump { + dump := Dump{ Root: common.Bytes2Hex(self.trie.Root()), Accounts: make(map[string]DumpAccount), @@ -47,12 +59,22 @@ func (self *StateDB) RawDump() Dump { it := self.trie.Iterator() for it.Next() { addr := self.trie.GetKey(it.Key) + addrA := common.BytesToAddress(addr) + + if addresses != nil && len(addresses) > 0 { + // check if address existing in argued addresses (lookup) + // if it's not one we're looking for, continue + if !lookupAddress(addrA, addresses) { + continue + } + } + var data Account if err := rlp.DecodeBytes(it.Value, &data); err != nil { panic(err) } - obj := newObject(nil, common.BytesToAddress(addr), data, nil) + obj := newObject(nil, addrA, data, nil) account := DumpAccount{ Balance: data.Balance.String(), Nonce: data.Nonce, @@ -70,8 +92,8 @@ func (self *StateDB) RawDump() Dump { return dump } -func (self *StateDB) Dump() []byte { - json, err := json.MarshalIndent(self.RawDump(), "", " ") +func (self *StateDB) Dump(addresses []common.Address) []byte { + json, err := json.MarshalIndent(self.RawDump(addresses), "", " ") if err != nil { fmt.Println("dump err", err) } diff --git a/core/state/state_test.go b/core/state/state_test.go index cc886bd38..73f47a83e 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -51,7 +51,7 @@ func (s *StateSuite) TestDump(c *checker.C) { s.state.Commit() // check that dump contains the state objects that are in trie - got := string(s.state.Dump()) + got := string(s.state.Dump([]common.Address{})) want := `{ "root": "71edff0130dd2385947095001c73d9e28d862fc286fca2b922ca6f6f3cddfdd2", "accounts": { diff --git a/eth/api.go b/eth/api.go index dd7a75811..dc2b43203 100644 --- a/eth/api.go +++ b/eth/api.go @@ -1592,6 +1592,7 @@ func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { } // DumpBlock retrieves the entire state of the database at a given block. +// TODO: update to be able to dump for specific addresses? func (api *PublicDebugAPI) DumpBlock(number uint64) (state.Dump, error) { block := api.eth.BlockChain().GetBlockByNumber(number) if block == nil { @@ -1601,7 +1602,7 @@ func (api *PublicDebugAPI) DumpBlock(number uint64) (state.Dump, error) { if err != nil { return state.Dump{}, err } - return stateDb.RawDump(), nil + return stateDb.RawDump([]common.Address{}), nil } // GetBlockRlp retrieves the RLP encoded for of a single block. diff --git a/logger/glog/glog_file.go b/logger/glog/glog_file.go index 2fc96eb4e..88f364ecb 100644 --- a/logger/glog/glog_file.go +++ b/logger/glog/glog_file.go @@ -38,6 +38,9 @@ var logDirs []string // If non-empty, overrides the choice of directory in which to write logs. // See createLogDirs for the full list of possible destinations. //var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") + + + var logDir *string = new(string) func SetLogDir(str string) {