[
  {
    "path": ".codecov.yml",
    "content": "---\ncodecov:\n  require_ci_to_pass: true\ncomment:\n  behavior: default\n  layout: reach, diff, flags, files, footer\n  require_base: false\n  require_changes: false\n  require_head: true\ncoverage:\n  precision: 2\n  range:\n    - 70\n    - 100\n  round: down\n  status:\n    changes: false\n    patch: true\n    project: true\nparsers:\n  gcov:\n    branch_detection:\n      conditional: true\n      loop: true\n      macro: false\n      method: false\n  javascript:\n    enable_partials: false\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "* @janisz @cristaloleg\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/issue_template.md",
    "content": "---\nname: Bug Report\nabout: Report a bug about BigCache\nlabels: bug\n---\n\n**What is the issue you are having?**\n\n\n\n**What is BigCache doing that it shouldn't?**\n\n\n\n**Minimal, Complete, and Verifiable Example**\n\nWhen asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be...\n\n* ...Minimal – Use as little code as possible that still produces the same problem\n* ...Complete – Provide all parts needed to reproduce the problem\n* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem\n\nFor more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve).\n\n**Environment:**\n- Version (git sha or release):\n- OS (e.g. from `/etc/os-release` or winver.exe):\n- go version: \n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\n\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    labels:\n      - \"enhancement\"\n  - package-ecosystem: \"gomod\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    labels:\n      - \"enhancement\"\n"
  },
  {
    "path": ".github/release-drafter.yml",
    "content": "name-template: \"v$NEXT_PATCH_VERSION 🌈\"\ntag-template: \"v$NEXT_PATCH_VERSION\"\ncategories:\n  - title: \"🚀 Features\"\n    labels:\n      - \"feature\"\n      - \"enhancement\"\n  - title: \"🐛 Bug Fixes\"\n    labels:\n      - \"fix\"\n      - \"bugfix\"\n      - \"bug\"\n  - title: \"🧰 Maintenance\"\n    label: \"chore\"\nchange-template: \"- $TITLE @$AUTHOR (#$NUMBER)\"\ntemplate: |\n  ## Changes\n\n  $CHANGES\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: build\non: [push, pull_request]\nenv:\n  GO111MODULE: on\n  CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}\njobs:\n  build:\n    name: Build\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: true\n      max-parallel: 2\n      matrix:\n        go: [\"stable\", \"oldstable\"]\n\n    steps:\n      - name: Set up Go\n        uses: actions/setup-go@v6\n        with:\n          go-version: ${{matrix.go}}\n        id: go\n\n      - name: Check out code into the Go module directory\n        uses: actions/checkout@v6\n\n      - name: Lint code\n        uses: golangci/golangci-lint-action@e7fa5ac41e1cf5b7d48e45e42232ce7ada589601\n        with:\n          only-new-issues: true\n\n      - name: Test\n        run: |\n          go test -race -count=1 -coverprofile=queue.coverprofile ./queue\n          go test -race -count=1 -coverprofile=server.coverprofile  ./server\n          go test -race -count=1 -coverprofile=main.coverprofile\n\n      - name: Upload coverage to codecov\n        run: |\n          go install github.com/modocache/gover@v0.0.0-20171022184752-b58185e213c5\n          echo \"\" > coverage.txt\n          gover\n          cat gover.coverprofile >> coverage.txt\n          bash <(curl -s https://codecov.io/bash)\n\n      - name: Build\n        run: go build -v .\n"
  },
  {
    "path": ".github/workflows/release-management.yml",
    "content": "name: Release Management\n\non:\n  push:\n    # branches to consider in the event; optional, defaults to all\n    branches:\n      - main\n\njobs:\n  update_draft_release:\n    runs-on: ubuntu-latest\n    steps:\n      # Drafts your next Release notes as Pull Requests are merged into \"main\"\n      - uses: toolmantim/release-drafter@v6.0.0\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea\n.DS_Store\n/server/server.exe\n/server/server\n/server/server_dar*\n/server/server_fre*\n/server/server_win*\n/server/server_net*\n/server/server_ope*\n/server/server_lin*\nCHANGELOG.md\n"
  },
  {
    "path": ".golangci.yaml",
    "content": "version: \"2\"\nlinters:\n  disable:\n    - errcheck\n  settings:\n    staticcheck:\n      checks:\n        - -SA1019\n        - all\n  exclusions:\n    generated: lax\n    presets:\n      - comments\n      - common-false-positives\n      - legacy\n      - std-error-handling\n    paths:\n      - third_party$\n      - builtin$\n      - examples$\nformatters:\n  exclusions:\n    generated: lax\n    paths:\n      - third_party$\n      - builtin$\n      - examples$\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild)&nbsp;[![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main)&nbsp;[![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3)&nbsp;[![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3)\n\nFast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance.\nBigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place,\ntherefore entries (de)serialization in front of the cache will be needed in most use cases.\n\nRequires Go 1.12 or newer.\n\n## Usage\n\n### Simple initialization\n\n```go\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/allegro/bigcache/v3\"\n)\n\ncache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute))\n\ncache.Set(\"my-unique-key\", []byte(\"value\"))\n\nentry, _ := cache.Get(\"my-unique-key\")\nfmt.Println(string(entry))\n```\n\n### Custom initialization\n\nWhen cache load can be predicted in advance then it is better to use custom initialization because additional memory\nallocation can be avoided in that way.\n\n```go\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/allegro/bigcache/v3\"\n)\n\nconfig := bigcache.Config {\n\t\t// number of shards (must be a power of 2)\n\t\tShards: 1024,\n\n\t\t// time after which entry can be evicted\n\t\tLifeWindow: 10 * time.Minute,\n\n\t\t// Interval between removing expired entries (clean up).\n\t\t// If set to <= 0 then no action is performed.\n\t\t// Setting to < 1 second is counterproductive — bigcache has a one second resolution.\n\t\tCleanWindow: 5 * time.Minute,\n\n\t\t// rps * lifeWindow, used only in initial memory allocation\n\t\tMaxEntriesInWindow: 1000 * 10 * 60,\n\n\t\t// max entry size in bytes, used only in initial memory allocation\n\t\tMaxEntrySize: 500,\n\n\t\t// prints information about additional memory allocation\n\t\tVerbose: true,\n\n\t\t// cache will not allocate more memory than this limit, value in MB\n\t\t// if value is reached then the oldest entries can be overridden for the new ones\n\t\t// 0 value means no size limit\n\t\tHardMaxCacheSize: 8192,\n\n\t\t// callback fired when the oldest entry is removed because of its expiration time or no space left\n\t\t// for the new entry, or because delete was called. A bitmask representing the reason will be returned.\n\t\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t\tOnRemove: nil,\n\n\t\t// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left\n\t\t// for the new entry, or because delete was called. A constant representing the reason will be passed through.\n\t\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t\t// Ignored if OnRemove is specified.\n\t\tOnRemoveWithReason: nil,\n\t}\n\ncache, initErr := bigcache.New(context.Background(), config)\nif initErr != nil {\n\tlog.Fatal(initErr)\n}\n\ncache.Set(\"my-unique-key\", []byte(\"value\"))\n\nif entry, err := cache.Get(\"my-unique-key\"); err == nil {\n\tfmt.Println(string(entry))\n}\n```\n\n### `LifeWindow` & `CleanWindow`\n\n1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted.\n\n2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life.\n\n## [Benchmarks](https://github.com/allegro/bigcache-bench)\n\nThree caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map.\nBenchmark tests were made using an\ni7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic).\n\nBenchmarks source code can be found [here](https://github.com/allegro/bigcache-bench)\n\n### Writes and reads\n\n```bash\ngo version\ngo version go1.13 linux/amd64\n\ngo test -bench=. -benchmem -benchtime=4s ./... -timeout 30m\ngoos: linux\ngoarch: amd64\npkg: github.com/allegro/bigcache/v3/caches_bench\nBenchmarkMapSet-8                     \t12999889\t       376 ns/op\t     199 B/op\t       3 allocs/op\nBenchmarkConcurrentMapSet-8           \t 4355726\t      1275 ns/op\t     337 B/op\t       8 allocs/op\nBenchmarkFreeCacheSet-8               \t11068976\t       703 ns/op\t     328 B/op\t       2 allocs/op\nBenchmarkBigCacheSet-8                \t10183717\t       478 ns/op\t     304 B/op\t       2 allocs/op\nBenchmarkMapGet-8                     \t16536015\t       324 ns/op\t      23 B/op\t       1 allocs/op\nBenchmarkConcurrentMapGet-8           \t13165708\t       401 ns/op\t      24 B/op\t       2 allocs/op\nBenchmarkFreeCacheGet-8               \t10137682\t       690 ns/op\t     136 B/op\t       2 allocs/op\nBenchmarkBigCacheGet-8                \t11423854\t       450 ns/op\t     152 B/op\t       4 allocs/op\nBenchmarkBigCacheSetParallel-8        \t34233472\t       148 ns/op\t     317 B/op\t       3 allocs/op\nBenchmarkFreeCacheSetParallel-8       \t34222654\t       268 ns/op\t     350 B/op\t       3 allocs/op\nBenchmarkConcurrentMapSetParallel-8   \t19635688\t       240 ns/op\t     200 B/op\t       6 allocs/op\nBenchmarkBigCacheGetParallel-8        \t60547064\t        86.1 ns/op\t     152 B/op\t       4 allocs/op\nBenchmarkFreeCacheGetParallel-8       \t50701280\t       147 ns/op\t     136 B/op\t       3 allocs/op\nBenchmarkConcurrentMapGetParallel-8   \t27353288\t       175 ns/op\t      24 B/op\t       2 allocs/op\nPASS\nok  \tgithub.com/allegro/bigcache/v3/caches_bench\t256.257s\n```\n\nWrites and reads in bigcache are faster than in freecache.\nWrites to map are the slowest.\n\n### GC pause time\n\n```bash\ngo version\ngo version go1.13 linux/amd64\n\ngo run caches_gc_overhead_comparison.go\n\nNumber of entries:  20000000\nGC pause for bigcache:  1.506077ms\nGC pause for freecache:  5.594416ms\nGC pause for map:  9.347015ms\n```\n\n```\ngo version\ngo version go1.13 linux/arm64\n\ngo run caches_gc_overhead_comparison.go\nNumber of entries:  20000000\nGC pause for bigcache:  22.382827ms\nGC pause for freecache:  41.264651ms\nGC pause for map:  72.236853ms\n```\n\nTest shows how long are the GC pauses for caches filled with 20mln of entries.\nBigcache and freecache have very similar GC pause time.\n\n### Memory usage\n\nYou may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing).\n\n## How it works\n\nBigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)).\nThis optimization states that if map without pointers in keys and values is used then GC will omit its content.\nTherefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries.\n\nEntries are kept in byte slices, to omit GC again.\nByte slices size can grow to gigabytes without impact on performance\nbecause GC will only see single pointer to it.\n\n### Collisions\n\nBigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value.\n\n## Bigcache vs Freecache\n\nBoth caches provide the same core features but they reduce GC overhead in different ways.\nBigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on\nslices to reduce number of pointers.\n\nResults from benchmark tests are presented above.\nOne of the advantage of bigcache over freecache is that you don’t need to know\nthe size of the cache in advance, because when bigcache is full,\nit can allocate additional memory for new entries instead of\noverwriting existing ones as freecache does currently.\nHowever hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config).\n\n## HTTP Server\n\nThis package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package.\n\n## More\n\nBigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html)\n\n## License\n\nBigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE))\n"
  },
  {
    "path": "assert_test.go",
    "content": "package bigcache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"path\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) {\n\tif !objectsAreEqual(expected, actual) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfile = path.Base(file)\n\t\tt.Errorf(fmt.Sprintf(\"\\n%s:%d: Not equal: \\n\"+\n\t\t\t\"expected: %T(%#v)\\n\"+\n\t\t\t\"actual  : %T(%#v)\\n\",\n\t\t\tfile, line, expected, expected, actual, actual), msgAndArgs...)\n\t}\n}\n\nfunc noError(t *testing.T, e error) {\n\tif e != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfile = path.Base(file)\n\t\tt.Errorf(\"\\n%s:%d: Error is not nil: \\n\"+\n\t\t\t\"actual  : %T(%#v)\\n\", file, line, e, e)\n\t}\n}\n\nfunc objectsAreEqual(expected, actual interface{}) bool {\n\tif expected == nil || actual == nil {\n\t\treturn expected == actual\n\t}\n\n\texp, ok := expected.([]byte)\n\tif !ok {\n\t\treturn reflect.DeepEqual(expected, actual)\n\t}\n\n\tact, ok := actual.([]byte)\n\tif !ok {\n\t\treturn false\n\t}\n\tif exp == nil || act == nil {\n\t\treturn exp == nil && act == nil\n\t}\n\treturn bytes.Equal(exp, act)\n}\n"
  },
  {
    "path": "bigcache.go",
    "content": "package bigcache\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n)\n\nconst (\n\tminimumEntriesInShard = 10 // Minimum number of entries in single shard\n)\n\n// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance.\n// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays,\n// therefore entries (de)serialization in front of the cache will be needed in most use cases.\ntype BigCache struct {\n\tshards     []*cacheShard\n\tlifeWindow uint64\n\tclock      clock\n\thash       Hasher\n\tconfig     Config\n\tshardMask  uint64\n\tclose      chan struct{}\n}\n\n// Response will contain metadata about the entry for which GetWithInfo(key) was called\ntype Response struct {\n\tEntryStatus RemoveReason\n}\n\n// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback.\ntype RemoveReason uint32\n\nconst (\n\t_ RemoveReason = iota\n\t// Expired means the key is past its LifeWindow.\n\tExpired\n\t// NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the\n\t// entry exceeded the maximum shard size.\n\tNoSpace\n\t// Deleted means Delete was called and this key was removed as a result.\n\tDeleted\n)\n\n// New initialize new instance of BigCache\nfunc New(ctx context.Context, config Config) (*BigCache, error) {\n\treturn newBigCache(ctx, config, &systemClock{})\n}\n\n// NewBigCache initialize new instance of BigCache\n//\n// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead,\n// New takes in context and can gracefully\n// shutdown with context cancellations\nfunc NewBigCache(config Config) (*BigCache, error) {\n\treturn newBigCache(context.Background(), config, &systemClock{})\n}\n\nfunc newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) {\n\tif !isPowerOfTwo(config.Shards) {\n\t\treturn nil, errors.New(\"Shards number must be power of two\") //nolint:staticcheck // keep for backward compatibility\n\t}\n\tif config.MaxEntrySize < 0 {\n\t\treturn nil, errors.New(\"MaxEntrySize must be >= 0\")\n\t}\n\tif config.MaxEntriesInWindow < 0 {\n\t\treturn nil, errors.New(\"MaxEntriesInWindow must be >= 0\")\n\t}\n\tif config.HardMaxCacheSize < 0 {\n\t\treturn nil, errors.New(\"HardMaxCacheSize must be >= 0\")\n\t}\n\n\tlifeWindowSeconds := uint64(config.LifeWindow.Seconds())\n\tif config.CleanWindow > 0 && lifeWindowSeconds == 0 {\n\t\treturn nil, errors.New(\"LifeWindow must be >= 1s when CleanWindow is set\")\n\t}\n\n\tif config.Hasher == nil {\n\t\tconfig.Hasher = newDefaultHasher()\n\t}\n\n\tcache := &BigCache{\n\t\tshards:     make([]*cacheShard, config.Shards),\n\t\tlifeWindow: lifeWindowSeconds,\n\t\tclock:      clock,\n\t\thash:       config.Hasher,\n\t\tconfig:     config,\n\t\tshardMask:  uint64(config.Shards - 1),\n\t\tclose:      make(chan struct{}),\n\t}\n\n\tvar onRemove func(wrappedEntry []byte, reason RemoveReason)\n\tif config.OnRemoveWithMetadata != nil {\n\t\tonRemove = cache.providedOnRemoveWithMetadata\n\t} else if config.OnRemove != nil {\n\t\tonRemove = cache.providedOnRemove\n\t} else if config.OnRemoveWithReason != nil {\n\t\tonRemove = cache.providedOnRemoveWithReason\n\t} else {\n\t\tonRemove = cache.notProvidedOnRemove\n\t}\n\n\tfor i := 0; i < config.Shards; i++ {\n\t\tcache.shards[i] = initNewShard(config, onRemove, clock)\n\t}\n\n\tif config.CleanWindow > 0 {\n\t\tgo func() {\n\t\t\tticker := time.NewTicker(config.CleanWindow)\n\t\t\tdefer ticker.Stop()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase t := <-ticker.C:\n\t\t\t\t\tcache.cleanUp(uint64(t.Unix()))\n\t\t\t\tcase <-cache.close:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn cache, nil\n}\n\n// Close is used to signal a shutdown of the cache when you are done with it.\n// This allows the cleaning goroutines to exit and ensures references are not\n// kept to the cache preventing GC of the entire cache.\nfunc (c *BigCache) Close() error {\n\tclose(c.close)\n\treturn nil\n}\n\n// Get reads entry for the key.\n// It returns an ErrEntryNotFound when\n// no entry exists for the given key.\nfunc (c *BigCache) Get(key string) ([]byte, error) {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.get(key, hashedKey)\n}\n\n// GetWithInfo reads entry for the key with Response info.\n// It returns an ErrEntryNotFound when\n// no entry exists for the given key.\nfunc (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.getWithInfo(key, hashedKey)\n}\n\n// Set saves entry under the key\nfunc (c *BigCache) Set(key string, entry []byte) error {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.set(key, hashedKey, entry)\n}\n\n// Append appends entry under the key if key exists, otherwise\n// it will set the key (same behaviour as Set()). With Append() you can\n// concatenate multiple entries under the same key in a lock-optimized way.\nfunc (c *BigCache) Append(key string, entry []byte) error {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.append(key, hashedKey, entry)\n}\n\n// Delete removes the key\nfunc (c *BigCache) Delete(key string) error {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.del(hashedKey)\n}\n\n// Reset empties all cache shards\nfunc (c *BigCache) Reset() error {\n\tfor _, shard := range c.shards {\n\t\tshard.reset(c.config)\n\t}\n\treturn nil\n}\n\n// ResetStats resets cache stats\nfunc (c *BigCache) ResetStats() error {\n\tfor _, shard := range c.shards {\n\t\tshard.resetStats()\n\t}\n\treturn nil\n}\n\n// Len computes the number of entries in the cache.\nfunc (c *BigCache) Len() int {\n\tvar len int\n\tfor _, shard := range c.shards {\n\t\tlen += shard.len()\n\t}\n\treturn len\n}\n\n// Capacity returns the amount of bytes stored in the cache.\nfunc (c *BigCache) Capacity() int {\n\tvar len int\n\tfor _, shard := range c.shards {\n\t\tlen += shard.capacity()\n\t}\n\treturn len\n}\n\n// Stats returns cache's statistics\nfunc (c *BigCache) Stats() Stats {\n\tvar s Stats\n\tfor _, shard := range c.shards {\n\t\ttmp := shard.getStats()\n\t\ts.Hits += tmp.Hits\n\t\ts.Misses += tmp.Misses\n\t\ts.DelHits += tmp.DelHits\n\t\ts.DelMisses += tmp.DelMisses\n\t\ts.Collisions += tmp.Collisions\n\t}\n\treturn s\n}\n\n// KeyMetadata returns number of times a cached resource was requested.\nfunc (c *BigCache) KeyMetadata(key string) Metadata {\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\treturn shard.getKeyMetadataWithLock(hashedKey)\n}\n\n// Iterator returns iterator function to iterate over EntryInfo's from whole cache.\nfunc (c *BigCache) Iterator() *EntryInfoIterator {\n\treturn newIterator(c)\n}\n\nfunc (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {\n\toldestTimestamp := readTimestampFromEntry(oldestEntry)\n\tif currentTimestamp < oldestTimestamp {\n\t\treturn false\n\t}\n\tif currentTimestamp-oldestTimestamp > c.lifeWindow {\n\t\tevict(Expired)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *BigCache) cleanUp(currentTimestamp uint64) {\n\tfor _, shard := range c.shards {\n\t\tshard.cleanUp(currentTimestamp)\n\t}\n}\n\nfunc (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) {\n\treturn c.shards[hashedKey&c.shardMask]\n}\n\nfunc (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) {\n\tc.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry))\n}\n\nfunc (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) {\n\tif c.config.onRemoveFilter == 0 || (1<<uint(reason))&c.config.onRemoveFilter > 0 {\n\t\tc.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason)\n\t}\n}\n\nfunc (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) {\n}\n\nfunc (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) {\n\tkey := readKeyFromEntry(wrappedEntry)\n\n\thashedKey := c.hash.Sum64(key)\n\tshard := c.getShard(hashedKey)\n\tc.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey))\n}\n"
  },
  {
    "path": "bigcache_bench_test.go",
    "content": "package bigcache\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar message = blob('a', 256)\n\nfunc BenchmarkWriteToCacheWith1Shard(b *testing.B) {\n\twriteToCache(b, 1, 100*time.Second, b.N)\n}\n\nfunc BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) {\n\tm := blob('a', 1024)\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         100 * time.Second,\n\t\tMaxEntriesInWindow: 100,\n\t\tMaxEntrySize:       256,\n\t\tHardMaxCacheSize:   1,\n\t})\n\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key-%d\", i), m)\n\t}\n}\n\nfunc BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) {\n\tm := blob('a', 1024)\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         100 * time.Second,\n\t\tMaxEntriesInWindow: 100,\n\t\tMaxEntrySize:       256,\n\t})\n\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key-%d\", i), m)\n\t}\n}\n\nfunc BenchmarkWriteToCache(b *testing.B) {\n\tfor _, shards := range []int{1, 512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\twriteToCache(b, shards, 100*time.Second, b.N)\n\t\t})\n\t}\n}\nfunc BenchmarkAppendToCache(b *testing.B) {\n\tfor _, shards := range []int{1, 512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\tappendToCache(b, shards, 100*time.Second, b.N)\n\t\t})\n\t}\n}\n\nfunc BenchmarkReadFromCache(b *testing.B) {\n\tfor _, shards := range []int{1, 512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\treadFromCache(b, shards, false)\n\t\t})\n\t}\n}\n\nfunc BenchmarkReadFromCacheWithInfo(b *testing.B) {\n\tfor _, shards := range []int{1, 512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\treadFromCache(b, shards, true)\n\t\t})\n\t}\n}\nfunc BenchmarkIterateOverCache(b *testing.B) {\n\n\tm := blob('a', 1)\n\n\tfor _, shards := range []int{512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\tcache, _ := New(context.Background(), Config{\n\t\t\t\tShards:             shards,\n\t\t\t\tLifeWindow:         1000 * time.Second,\n\t\t\t\tMaxEntriesInWindow: max(b.N, 100),\n\t\t\t\tMaxEntrySize:       500,\n\t\t\t})\n\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tcache.Set(fmt.Sprintf(\"key-%d\", i), m)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tit := cache.Iterator()\n\n\t\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\t\tb.ReportAllocs()\n\n\t\t\t\tfor pb.Next() {\n\t\t\t\t\tif it.SetNext() {\n\t\t\t\t\t\tit.Value()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) {\n\twriteToCache(b, 1024, 100*time.Second, 100)\n}\n\nfunc BenchmarkReadFromCacheNonExistentKeys(b *testing.B) {\n\tfor _, shards := range []int{1, 512, 1024, 8192} {\n\t\tb.Run(fmt.Sprintf(\"%d-shards\", shards), func(b *testing.B) {\n\t\t\treadFromCacheNonExistentKeys(b, 1024)\n\t\t})\n\t}\n}\n\nfunc writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) {\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             shards,\n\t\tLifeWindow:         lifeWindow,\n\t\tMaxEntriesInWindow: max(requestsInLifeWindow, 100),\n\t\tMaxEntrySize:       500,\n\t})\n\trand.Seed(time.Now().Unix())\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tid := rand.Int()\n\t\tcounter := 0\n\n\t\tb.ReportAllocs()\n\t\tfor pb.Next() {\n\t\t\tcache.Set(fmt.Sprintf(\"key-%d-%d\", id, counter), message)\n\t\t\tcounter = counter + 1\n\t\t}\n\t})\n}\n\nfunc appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) {\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             shards,\n\t\tLifeWindow:         lifeWindow,\n\t\tMaxEntriesInWindow: max(requestsInLifeWindow, 100),\n\t\tMaxEntrySize:       2000,\n\t})\n\trand.Seed(time.Now().Unix())\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tid := rand.Int()\n\t\tcounter := 0\n\n\t\tb.ReportAllocs()\n\t\tfor pb.Next() {\n\t\t\tkey := fmt.Sprintf(\"key-%d-%d\", id, counter)\n\t\t\tfor j := 0; j < 7; j++ {\n\t\t\t\tcache.Append(key, message)\n\t\t\t}\n\t\t\tcounter = counter + 1\n\t\t}\n\t})\n}\n\nfunc readFromCache(b *testing.B, shards int, info bool) {\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             shards,\n\t\tLifeWindow:         1000 * time.Second,\n\t\tMaxEntriesInWindow: max(b.N, 100),\n\t\tMaxEntrySize:       500,\n\t})\n\tfor i := 0; i < b.N; i++ {\n\t\tcache.Set(strconv.Itoa(i), message)\n\t}\n\tb.ResetTimer()\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tb.ReportAllocs()\n\n\t\tfor pb.Next() {\n\t\t\tif info {\n\t\t\t\tcache.GetWithInfo(strconv.Itoa(rand.Intn(b.N)))\n\t\t\t} else {\n\t\t\t\tcache.Get(strconv.Itoa(rand.Intn(b.N)))\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc readFromCacheNonExistentKeys(b *testing.B, shards int) {\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             shards,\n\t\tLifeWindow:         1000 * time.Second,\n\t\tMaxEntriesInWindow: max(b.N, 100),\n\t\tMaxEntrySize:       500,\n\t})\n\tb.ResetTimer()\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tb.ReportAllocs()\n\n\t\tfor pb.Next() {\n\t\t\tcache.Get(strconv.Itoa(rand.Intn(b.N)))\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "bigcache_test.go",
    "content": "package bigcache\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/rand\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWriteAndGetOnCache(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), DefaultConfig(5*time.Second))\n\tvalue := []byte(\"value\")\n\n\t// when\n\tcache.Set(\"key\", value)\n\tcachedValue, err := cache.Get(\"key\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, value, cachedValue)\n}\n\nfunc TestAppendAndGetOnCache(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), DefaultConfig(5*time.Second))\n\tkey := \"key\"\n\tvalue1 := make([]byte, 50)\n\trand.Read(value1)\n\tvalue2 := make([]byte, 50)\n\trand.Read(value2)\n\tvalue3 := make([]byte, 50)\n\trand.Read(value3)\n\n\t// when\n\t_, err := cache.Get(key)\n\n\t// then\n\tassertEqual(t, ErrEntryNotFound, err)\n\n\t// when\n\tcache.Append(key, value1)\n\tcachedValue, err := cache.Get(key)\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, value1, cachedValue)\n\n\t// when\n\tcache.Append(key, value2)\n\tcachedValue, err = cache.Get(key)\n\n\t// then\n\tnoError(t, err)\n\texpectedValue := value1\n\texpectedValue = append(expectedValue, value2...)\n\tassertEqual(t, expectedValue, cachedValue)\n\n\t// when\n\tcache.Append(key, value3)\n\tcachedValue, err = cache.Get(key)\n\n\t// then\n\tnoError(t, err)\n\texpectedValue = value1\n\texpectedValue = append(expectedValue, value2...)\n\texpectedValue = append(expectedValue, value3...)\n\tassertEqual(t, expectedValue, cachedValue)\n}\n\n// TestAppendRandomly does simultaneous appends to check for corruption errors.\nfunc TestAppendRandomly(t *testing.T) {\n\tt.Parallel()\n\n\tc := Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tCleanWindow:        1 * time.Second,\n\t\tMaxEntriesInWindow: 1000 * 10 * 60,\n\t\tMaxEntrySize:       500,\n\t\tStatsEnabled:       true,\n\t\tVerbose:            true,\n\t\tHasher:             newDefaultHasher(),\n\t\tHardMaxCacheSize:   1,\n\t\tLogger:             DefaultLogger(),\n\t}\n\tcache, err := New(context.Background(), c)\n\tnoError(t, err)\n\n\tnKeys := 5\n\tnAppendsPerKey := 2000\n\tnWorker := 10\n\tvar keys []string\n\tfor i := 0; i < nKeys; i++ {\n\t\tfor j := 0; j < nAppendsPerKey; j++ {\n\t\t\tkeys = append(keys, fmt.Sprintf(\"key%d\", i))\n\t\t}\n\t}\n\trand.Shuffle(len(keys), func(i, j int) {\n\t\tkeys[i], keys[j] = keys[j], keys[i]\n\t})\n\n\tjobs := make(chan string, len(keys))\n\tfor _, key := range keys {\n\t\tjobs <- key\n\t}\n\tclose(jobs)\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < nWorker; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tkey, ok := <-jobs\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcache.Append(key, []byte(key))\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n\tassertEqual(t, nKeys, cache.Len())\n\tfor i := 0; i < nKeys; i++ {\n\t\tkey := fmt.Sprintf(\"key%d\", i)\n\t\texpectedValue := []byte(strings.Repeat(key, nAppendsPerKey))\n\t\tcachedValue, err := cache.Get(key)\n\t\tnoError(t, err)\n\t\tassertEqual(t, expectedValue, cachedValue)\n\t}\n}\n\nfunc TestAppendCollision(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t\tVerbose:            true,\n\t\tHasher:             hashStub(5),\n\t})\n\n\t//when\n\tcache.Append(\"a\", []byte(\"1\"))\n\tcachedValue, err := cache.Get(\"a\")\n\n\t//then\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"1\"), cachedValue)\n\n\t// when\n\terr = cache.Append(\"b\", []byte(\"2\"))\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, cache.Stats().Collisions, int64(1))\n\tcachedValue, err = cache.Get(\"b\")\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"2\"), cachedValue)\n\n}\n\nfunc TestConstructCacheWithDefaultHasher(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             16,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t_, ok := cache.hash.(fnv64a)\n\tassertEqual(t, true, ok)\n}\n\nfunc TestNewBigcacheValidation(t *testing.T) {\n\tt.Parallel()\n\n\tfor _, tc := range []struct {\n\t\tcfg  Config\n\t\twant string\n\t}{\n\t\t{\n\t\t\tcfg:  Config{Shards: 18},\n\t\t\twant: \"Shards number must be power of two\",\n\t\t},\n\t\t{\n\t\t\tcfg:  Config{Shards: 16, MaxEntriesInWindow: -1},\n\t\t\twant: \"MaxEntriesInWindow must be >= 0\",\n\t\t},\n\t\t{\n\t\t\tcfg:  Config{Shards: 16, MaxEntrySize: -1},\n\t\t\twant: \"MaxEntrySize must be >= 0\",\n\t\t},\n\t\t{\n\t\t\tcfg:  Config{Shards: 16, HardMaxCacheSize: -1},\n\t\t\twant: \"HardMaxCacheSize must be >= 0\",\n\t\t},\n\t} {\n\t\tt.Run(tc.want, func(t *testing.T) {\n\t\t\tcache, error := New(context.Background(), tc.cfg)\n\n\t\t\tassertEqual(t, (*BigCache)(nil), cache)\n\t\t\tassertEqual(t, tc.want, error.Error())\n\t\t})\n\t}\n}\n\nfunc TestEntryNotFound(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             16,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\t_, err := cache.Get(\"nonExistingKey\")\n\n\t// then\n\tassertEqual(t, ErrEntryNotFound, err)\n}\n\nfunc TestTimingEviction(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t}, &clock)\n\n\tcache.Set(\"key\", []byte(\"value\"))\n\n\t// when\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\t_, err := cache.Get(\"key\")\n\n\t// then\n\tnoError(t, err)\n\n\t// when\n\tclock.set(5)\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\t_, err = cache.Get(\"key\")\n\n\t// then\n\tassertEqual(t, ErrEntryNotFound, err)\n}\n\nfunc TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             4,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t}, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.Set(\"key2\", []byte(\"value 2\"))\n\tvalue, err := cache.Get(\"key\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"value\"), value)\n}\n\nfunc TestCleanShouldEvictAll(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             4,\n\t\tLifeWindow:         time.Second,\n\t\tCleanWindow:        time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\t<-time.After(3 * time.Second)\n\tvalue, err := cache.Get(\"key\")\n\n\t// then\n\tassertEqual(t, ErrEntryNotFound, err)\n\tassertEqual(t, value, []byte(nil))\n}\n\nfunc TestOnRemoveCallback(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tonRemoveInvoked := false\n\tonRemoveExtInvoked := false\n\tonRemove := func(key string, entry []byte) {\n\t\tonRemoveInvoked = true\n\t\tassertEqual(t, \"key\", key)\n\t\tassertEqual(t, []byte(\"value\"), entry)\n\t}\n\tonRemoveExt := func(key string, entry []byte, reason RemoveReason) {\n\t\tonRemoveExtInvoked = true\n\t}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t\tOnRemove:           onRemove,\n\t\tOnRemoveWithReason: onRemoveExt,\n\t}, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\n\t// then\n\tassertEqual(t, true, onRemoveInvoked)\n\tassertEqual(t, false, onRemoveExtInvoked)\n}\n\nfunc TestOnRemoveWithReasonCallback(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tonRemoveInvoked := false\n\tonRemove := func(key string, entry []byte, reason RemoveReason) {\n\t\tonRemoveInvoked = true\n\t\tassertEqual(t, \"key\", key)\n\t\tassertEqual(t, []byte(\"value\"), entry)\n\t\tassertEqual(t, reason, RemoveReason(Expired))\n\t}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t\tOnRemoveWithReason: onRemove,\n\t}, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\n\t// then\n\tassertEqual(t, true, onRemoveInvoked)\n}\n\nfunc TestOnRemoveFilter(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tonRemoveInvoked := false\n\tonRemove := func(key string, entry []byte, reason RemoveReason) {\n\t\tonRemoveInvoked = true\n\t}\n\tc := Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t\tOnRemoveWithReason: onRemove,\n\t}.OnRemoveFilterSet(Deleted, NoSpace)\n\n\tcache, _ := newBigCache(context.Background(), c, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\n\t// then\n\tassertEqual(t, false, onRemoveInvoked)\n\n\t// and when\n\tcache.Delete(\"key2\")\n\n\t// then\n\tassertEqual(t, true, onRemoveInvoked)\n}\n\nfunc TestOnRemoveFilterExpired(t *testing.T) {\n\t// t.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tonRemoveDeleted, onRemoveExpired := false, false\n\tvar err error\n\tonRemove := func(key string, entry []byte, reason RemoveReason) {\n\t\tswitch reason {\n\n\t\tcase Deleted:\n\t\t\tonRemoveDeleted = true\n\t\tcase Expired:\n\t\t\tonRemoveExpired = true\n\n\t\t}\n\t}\n\tc := Config{\n\t\tShards:             1,\n\t\tLifeWindow:         3 * time.Second,\n\t\tCleanWindow:        0,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t\tOnRemoveWithReason: onRemove,\n\t}\n\n\tcache, err := newBigCache(context.Background(), c, &clock)\n\tassertEqual(t, err, nil)\n\n\t// case 1: key is deleted AFTER expire\n\t// when\n\tonRemoveDeleted, onRemoveExpired = false, false\n\tclock.set(0)\n\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.cleanUp(uint64(clock.Epoch()))\n\n\terr = cache.Delete(\"key\")\n\n\t// then\n\tassertEqual(t, err, ErrEntryNotFound)\n\tassertEqual(t, false, onRemoveDeleted)\n\tassertEqual(t, true, onRemoveExpired)\n\n\t// case 1: key is deleted BEFORE expire\n\t// when\n\tonRemoveDeleted, onRemoveExpired = false, false\n\tclock.set(0)\n\n\tcache.Set(\"key2\", []byte(\"value2\"))\n\terr = cache.Delete(\"key2\")\n\tclock.set(5)\n\tcache.cleanUp(uint64(clock.Epoch()))\n\t// then\n\n\tassertEqual(t, err, nil)\n\tassertEqual(t, true, onRemoveDeleted)\n\tassertEqual(t, false, onRemoveExpired)\n}\n\nfunc TestOnRemoveGetEntryStats(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcount := uint32(0)\n\tonRemove := func(key string, entry []byte, keyMetadata Metadata) {\n\t\tcount = keyMetadata.RequestCount\n\t}\n\tc := Config{\n\t\tShards:               1,\n\t\tLifeWindow:           time.Second,\n\t\tMaxEntriesInWindow:   1,\n\t\tMaxEntrySize:         256,\n\t\tOnRemoveWithMetadata: onRemove,\n\t\tStatsEnabled:         true,\n\t}.OnRemoveFilterSet(Deleted, NoSpace)\n\n\tcache, _ := newBigCache(context.Background(), c, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\n\tfor i := 0; i < 100; i++ {\n\t\tcache.Get(\"key\")\n\t}\n\n\tcache.Delete(\"key\")\n\n\t// then\n\tassertEqual(t, uint32(100), count)\n}\n\nfunc TestCacheLen(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tkeys := 1337\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\t// then\n\tassertEqual(t, keys, cache.Len())\n}\n\nfunc TestCacheCapacity(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tkeys := 1337\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\t// then\n\tassertEqual(t, keys, cache.Len())\n\tassertEqual(t, 40960, cache.Capacity())\n}\n\nfunc TestCacheInitialCapacity(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 2 * 1024,\n\t\tHardMaxCacheSize:   1,\n\t\tMaxEntrySize:       1024,\n\t})\n\n\tassertEqual(t, 0, cache.Len())\n\tassertEqual(t, 1024*1024, cache.Capacity())\n\n\tkeys := 1024 * 1024\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\t// then\n\tassertEqual(t, true, cache.Len() < keys)\n\tassertEqual(t, 1024*1024, cache.Capacity())\n}\n\nfunc TestRemoveEntriesWhenShardIsFull(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         100 * time.Second,\n\t\tMaxEntriesInWindow: 100,\n\t\tMaxEntrySize:       256,\n\t\tHardMaxCacheSize:   1,\n\t})\n\n\tvalue := blob('a', 1024*300)\n\n\t// when\n\tcache.Set(\"key\", value)\n\tcache.Set(\"key\", value)\n\tcache.Set(\"key\", value)\n\tcache.Set(\"key\", value)\n\tcache.Set(\"key\", value)\n\tcachedValue, err := cache.Get(\"key\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, value, cachedValue)\n}\n\nfunc TestCacheStats(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\tfor i := 0; i < 100; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tvalue, err := cache.Get(fmt.Sprintf(\"key%d\", i))\n\t\tnoError(t, err)\n\t\tassertEqual(t, string(value), \"value\")\n\t}\n\tfor i := 100; i < 110; i++ {\n\t\t_, err := cache.Get(fmt.Sprintf(\"key%d\", i))\n\t\tassertEqual(t, ErrEntryNotFound, err)\n\t}\n\tfor i := 10; i < 20; i++ {\n\t\terr := cache.Delete(fmt.Sprintf(\"key%d\", i))\n\t\tnoError(t, err)\n\t}\n\tfor i := 110; i < 120; i++ {\n\t\terr := cache.Delete(fmt.Sprintf(\"key%d\", i))\n\t\tassertEqual(t, ErrEntryNotFound, err)\n\t}\n\n\t// then\n\tstats := cache.Stats()\n\tassertEqual(t, stats.Hits, int64(10))\n\tassertEqual(t, stats.Misses, int64(10))\n\tassertEqual(t, stats.DelHits, int64(10))\n\tassertEqual(t, stats.DelMisses, int64(10))\n}\nfunc TestCacheEntryStats(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t\tStatsEnabled:       true,\n\t})\n\n\tcache.Set(\"key0\", []byte(\"value\"))\n\n\tfor i := 0; i < 10; i++ {\n\t\t_, err := cache.Get(\"key0\")\n\t\tnoError(t, err)\n\t}\n\n\t// then\n\tkeyMetadata := cache.KeyMetadata(\"key0\")\n\tassertEqual(t, uint32(10), keyMetadata.RequestCount)\n}\n\nfunc TestCacheRestStats(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\tfor i := 0; i < 100; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tvalue, err := cache.Get(fmt.Sprintf(\"key%d\", i))\n\t\tnoError(t, err)\n\t\tassertEqual(t, string(value), \"value\")\n\t}\n\tfor i := 100; i < 110; i++ {\n\t\t_, err := cache.Get(fmt.Sprintf(\"key%d\", i))\n\t\tassertEqual(t, ErrEntryNotFound, err)\n\t}\n\tfor i := 10; i < 20; i++ {\n\t\terr := cache.Delete(fmt.Sprintf(\"key%d\", i))\n\t\tnoError(t, err)\n\t}\n\tfor i := 110; i < 120; i++ {\n\t\terr := cache.Delete(fmt.Sprintf(\"key%d\", i))\n\t\tassertEqual(t, ErrEntryNotFound, err)\n\t}\n\n\tstats := cache.Stats()\n\tassertEqual(t, stats.Hits, int64(10))\n\tassertEqual(t, stats.Misses, int64(10))\n\tassertEqual(t, stats.DelHits, int64(10))\n\tassertEqual(t, stats.DelMisses, int64(10))\n\n\t//then\n\tcache.ResetStats()\n\tstats = cache.Stats()\n\tassertEqual(t, stats.Hits, int64(0))\n\tassertEqual(t, stats.Misses, int64(0))\n\tassertEqual(t, stats.DelHits, int64(0))\n\tassertEqual(t, stats.DelMisses, int64(0))\n}\n\nfunc TestCacheDel(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), DefaultConfig(time.Second))\n\n\t// when\n\terr := cache.Delete(\"nonExistingKey\")\n\n\t// then\n\tassertEqual(t, err, ErrEntryNotFound)\n\n\t// and when\n\tcache.Set(\"existingKey\", nil)\n\terr = cache.Delete(\"existingKey\")\n\tcachedValue, _ := cache.Get(\"existingKey\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, 0, len(cachedValue))\n}\n\n// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors.\nfunc TestCacheDelRandomly(t *testing.T) {\n\tt.Parallel()\n\n\tc := Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tCleanWindow:        0,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       10,\n\t\tVerbose:            false,\n\t\tHasher:             newDefaultHasher(),\n\t\tHardMaxCacheSize:   1,\n\t\tStatsEnabled:       true,\n\t\tLogger:             DefaultLogger(),\n\t}\n\n\tcache, _ := New(context.Background(), c)\n\tvar wg sync.WaitGroup\n\tvar ntest = 800000\n\twg.Add(3)\n\tgo func() {\n\t\tfor i := 0; i < ntest; i++ {\n\t\t\tr := uint8(rand.Int())\n\t\t\tkey := fmt.Sprintf(\"thekey%d\", r)\n\n\t\t\tcache.Delete(key)\n\t\t}\n\t\twg.Done()\n\t}()\n\tvalueLen := 1024\n\tgo func() {\n\t\tval := make([]byte, valueLen)\n\t\tfor i := 0; i < ntest; i++ {\n\t\t\tr := byte(rand.Int())\n\t\t\tkey := fmt.Sprintf(\"thekey%d\", r)\n\n\t\t\tfor j := 0; j < len(val); j++ {\n\t\t\t\tval[j] = r\n\t\t\t}\n\t\t\tcache.Set(key, val)\n\t\t}\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tval := make([]byte, valueLen)\n\t\tfor i := 0; i < ntest; i++ {\n\t\t\tr := byte(rand.Int())\n\t\t\tkey := fmt.Sprintf(\"thekey%d\", r)\n\n\t\t\tfor j := 0; j < len(val); j++ {\n\t\t\t\tval[j] = r\n\t\t\t}\n\t\t\tif got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) {\n\t\t\t\tt.Errorf(\"got %s ->\\n %x\\n expected:\\n %x\\n \", key, got, val)\n\t\t\t}\n\t\t}\n\t\twg.Done()\n\t}()\n\twg.Wait()\n}\n\nfunc TestWriteAndReadParallelSameKeyWithStats(t *testing.T) {\n\tt.Parallel()\n\n\tc := DefaultConfig(10 * time.Second)\n\tc.StatsEnabled = true\n\n\tcache, _ := New(context.Background(), c)\n\tvar wg sync.WaitGroup\n\tntest := 1000\n\tn := 10\n\twg.Add(n)\n\tkey := \"key\"\n\tvalue := blob('a', 1024)\n\tfor i := 0; i < ntest; i++ {\n\t\tassertEqual(t, nil, cache.Set(key, value))\n\t}\n\tfor j := 0; j < n; j++ {\n\t\tgo func() {\n\t\t\tfor i := 0; i < ntest; i++ {\n\t\t\t\tv, err := cache.Get(key)\n\t\t\t\tassertEqual(t, nil, err)\n\t\t\t\tassertEqual(t, value, v)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\twg.Wait()\n\n\tassertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats())\n\tassertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount))\n}\n\nfunc TestCacheReset(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tkeys := 1337\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\t// then\n\tassertEqual(t, keys, cache.Len())\n\n\t// and when\n\tcache.Reset()\n\n\t// then\n\tassertEqual(t, 0, cache.Len())\n\n\t// and when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\t// then\n\tassertEqual(t, keys, cache.Len())\n}\n\nfunc TestIterateOnResetCache(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tkeys := 1337\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\tcache.Reset()\n\n\t// then\n\titerator := cache.Iterator()\n\n\tassertEqual(t, false, iterator.SetNext())\n}\n\nfunc TestGetOnResetCache(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tkeys := 1337\n\n\t// when\n\tfor i := 0; i < keys; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), []byte(\"value\"))\n\t}\n\n\tcache.Reset()\n\n\t// then\n\tvalue, err := cache.Get(\"key1\")\n\n\tassertEqual(t, err, ErrEntryNotFound)\n\tassertEqual(t, value, []byte(nil))\n}\n\nfunc TestEntryUpdate(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         6 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t}, &clock)\n\n\t// when\n\tcache.Set(\"key\", []byte(\"value\"))\n\tclock.set(5)\n\tcache.Set(\"key\", []byte(\"value2\"))\n\tclock.set(7)\n\tcache.Set(\"key2\", []byte(\"value3\"))\n\tcachedValue, _ := cache.Get(\"key\")\n\n\t// then\n\tassertEqual(t, []byte(\"value2\"), cachedValue)\n}\n\nfunc TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t})\n\n\t// when\n\tcache.Set(\"key1\", blob('a', 1024*400))\n\tcache.Set(\"key2\", blob('b', 1024*400))\n\tcache.Set(\"key3\", blob('c', 1024*800))\n\n\t_, key1Err := cache.Get(\"key1\")\n\t_, key2Err := cache.Get(\"key2\")\n\tentry3, _ := cache.Get(\"key3\")\n\n\t// then\n\tassertEqual(t, key1Err, ErrEntryNotFound)\n\tassertEqual(t, key2Err, ErrEntryNotFound)\n\tassertEqual(t, blob('c', 1024*800), entry3)\n}\n\nfunc TestRetrievingEntryShouldCopy(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t})\n\tcache.Set(\"key1\", blob('a', 1024*400))\n\tvalue, key1Err := cache.Get(\"key1\")\n\n\t// when\n\t// override queue\n\tcache.Set(\"key2\", blob('b', 1024*400))\n\tcache.Set(\"key3\", blob('c', 1024*400))\n\tcache.Set(\"key4\", blob('d', 1024*400))\n\tcache.Set(\"key5\", blob('d', 1024*400))\n\n\t// then\n\tnoError(t, key1Err)\n\tassertEqual(t, blob('a', 1024*400), value)\n}\n\nfunc TestEntryBiggerThanMaxShardSizeError(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t})\n\n\t// when\n\terr := cache.Set(\"key1\", blob('a', 1024*1025))\n\n\t// then\n\tassertEqual(t, \"entry is bigger than max shard size\", err.Error())\n}\n\nfunc TestHashCollision(t *testing.T) {\n\tt.Parallel()\n\n\tml := &mockedLogger{}\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             16,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t\tVerbose:            true,\n\t\tHasher:             hashStub(5),\n\t\tLogger:             ml,\n\t})\n\n\t// when\n\tcache.Set(\"liquid\", []byte(\"value\"))\n\tcachedValue, err := cache.Get(\"liquid\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"value\"), cachedValue)\n\n\t// when\n\tcache.Set(\"costarring\", []byte(\"value 2\"))\n\tcachedValue, err = cache.Get(\"costarring\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"value 2\"), cachedValue)\n\n\t// when\n\tcachedValue, err = cache.Get(\"liquid\")\n\n\t// then\n\tassertEqual(t, ErrEntryNotFound, err)\n\tassertEqual(t, []byte(nil), cachedValue)\n\n\tassertEqual(t, \"Collision detected. Both %q and %q have the same hash %x\", ml.lastFormat)\n\tassertEqual(t, cache.Stats().Collisions, int64(1))\n}\n\nfunc TestNilValueCaching(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t})\n\n\t// when\n\tcache.Set(\"Kierkegaard\", []byte{})\n\tcachedValue, err := cache.Get(\"Kierkegaard\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte{}, cachedValue)\n\n\t// when\n\tcache.Set(\"Sartre\", nil)\n\tcachedValue, err = cache.Get(\"Sartre\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte{}, cachedValue)\n\n\t// when\n\tcache.Set(\"Nietzsche\", []byte(nil))\n\tcachedValue, err = cache.Get(\"Nietzsche\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte{}, cachedValue)\n}\n\nfunc TestClosing(t *testing.T) {\n\t// given\n\tconfig := Config{\n\t\tCleanWindow: time.Minute,\n\t\tShards:      1,\n\t\tLifeWindow:  1 * time.Second,\n\t}\n\tstartGR := runtime.NumGoroutine()\n\n\t// when\n\tfor i := 0; i < 100; i++ {\n\t\tcache, _ := New(context.Background(), config)\n\t\tcache.Close()\n\t}\n\n\t// wait till all goroutines are stopped.\n\ttime.Sleep(200 * time.Millisecond)\n\n\t// then\n\tendGR := runtime.NumGoroutine()\n\tassertEqual(t, true, endGR >= startGR)\n\tassertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25)\n}\n\nfunc TestEntryNotPresent(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t}, &clock)\n\n\t// when\n\tvalue, resp, err := cache.GetWithInfo(\"blah\")\n\tassertEqual(t, ErrEntryNotFound, err)\n\tassertEqual(t, resp.EntryStatus, RemoveReason(0))\n\tassertEqual(t, cache.Stats().Misses, int64(1))\n\tassertEqual(t, []byte(nil), value)\n}\n\nfunc TestBigCache_GetWithInfo(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tCleanWindow:        5 * time.Minute,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       1,\n\t\tHardMaxCacheSize:   1,\n\t\tVerbose:            true,\n\t}, &clock)\n\tkey := \"deadEntryKey\"\n\tvalue := \"100\"\n\tcache.Set(key, []byte(value))\n\n\tfor _, tc := range []struct {\n\t\tname     string\n\t\tclock    int64\n\t\twantData string\n\t\twantResp Response\n\t}{\n\t\t{\n\t\t\tname:     \"zero\",\n\t\t\tclock:    0,\n\t\t\twantData: value,\n\t\t\twantResp: Response{},\n\t\t},\n\t\t{\n\t\t\tname:     \"Before Expired\",\n\t\t\tclock:    4,\n\t\t\twantData: value,\n\t\t\twantResp: Response{},\n\t\t},\n\t\t{\n\t\t\tname:     \"Expired\",\n\t\t\tclock:    5,\n\t\t\twantData: value,\n\t\t\twantResp: Response{EntryStatus: Expired},\n\t\t},\n\t\t{\n\t\t\tname:     \"After Expired\",\n\t\t\tclock:    6,\n\t\t\twantData: value,\n\t\t\twantResp: Response{EntryStatus: Expired},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tclock.set(tc.clock)\n\t\t\tdata, resp, err := cache.GetWithInfo(key)\n\n\t\t\tassertEqual(t, []byte(tc.wantData), data)\n\t\t\tnoError(t, err)\n\t\t\tassertEqual(t, tc.wantResp, resp)\n\t\t})\n\t}\n}\n\nfunc TestBigCache_GetWithInfoCollision(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         5 * time.Second,\n\t\tMaxEntriesInWindow: 10,\n\t\tMaxEntrySize:       256,\n\t\tVerbose:            true,\n\t\tHasher:             hashStub(5),\n\t})\n\n\t//when\n\tcache.Set(\"a\", []byte(\"1\"))\n\tcachedValue, resp, err := cache.GetWithInfo(\"a\")\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, []byte(\"1\"), cachedValue)\n\tassertEqual(t, Response{}, resp)\n\n\t// when\n\tcachedValue, resp, err = cache.GetWithInfo(\"b\")\n\n\t// then\n\tassertEqual(t, []byte(nil), cachedValue)\n\tassertEqual(t, Response{}, resp)\n\tassertEqual(t, ErrEntryNotFound, err)\n\tassertEqual(t, cache.Stats().Collisions, int64(1))\n\n}\n\ntype mockedLogger struct {\n\tlastFormat string\n\tlastArgs   []interface{}\n}\n\nfunc (ml *mockedLogger) Printf(format string, v ...interface{}) {\n\tml.lastFormat = format\n\tml.lastArgs = v\n}\n\ntype mockedClock struct {\n\tvalue int64\n}\n\nfunc (mc *mockedClock) Epoch() int64 {\n\treturn mc.value\n}\n\nfunc (mc *mockedClock) set(value int64) {\n\tmc.value = value\n}\n\nfunc blob(char byte, len int) []byte {\n\treturn bytes.Repeat([]byte{char}, len)\n}\n\nfunc TestCache_SetWithoutCleanWindow(t *testing.T) {\n\n\topt := DefaultConfig(time.Second)\n\topt.CleanWindow = 0\n\topt.HardMaxCacheSize = 1\n\tbc, _ := New(context.Background(), opt)\n\n\terr := bc.Set(\"2225\", make([]byte, 200))\n\tif nil != err {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestCache_RepeatedSetWithBiggerEntry(t *testing.T) {\n\n\topt := DefaultConfig(time.Second)\n\topt.Shards = 2 << 10\n\topt.MaxEntriesInWindow = 1024\n\topt.MaxEntrySize = 1\n\topt.HardMaxCacheSize = 1\n\tbc, _ := New(context.Background(), opt)\n\n\terr := bc.Set(\"2225\", make([]byte, 200))\n\tif nil != err {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\terr = bc.Set(\"8573\", make([]byte, 100))\n\tif nil != err {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\n\terr = bc.Set(\"8573\", make([]byte, 450))\n\tif nil != err {\n\t\t// occur error but go next\n\t\tt.Logf(\"%v\", err)\n\t}\n\n\terr = bc.Set(\"7327\", make([]byte, 300))\n\tif nil != err {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\n\terr = bc.Set(\"8573\", make([]byte, 200))\n\tif nil != err {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\n}\n\n// TestBigCache_allocateAdditionalMemoryLeadPanic\n// The new commit 16df11e change the encoding method,it can fix issue #300\nfunc TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) {\n\tt.Parallel()\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:       1,\n\t\tLifeWindow:   3 * time.Second,\n\t\tMaxEntrySize: 52,\n\t}, &clock)\n\tts := time.Now().Unix()\n\tclock.set(ts)\n\tcache.Set(\"a\", blob(0xff, 235))\n\tts += 2\n\tclock.set(ts)\n\tcache.Set(\"b\", blob(0xff, 235))\n\t// expire the key \"a\"\n\tts += 2\n\tclock.set(ts)\n\t// move tail to leftMargin,insert before head\n\tcache.Set(\"c\", blob(0xff, 108))\n\t// reallocate memory,fill the tail to head with zero byte,move head to leftMargin\n\tcache.Set(\"d\", blob(0xff, 1024))\n\tts += 4\n\tclock.set(ts)\n\t// expire the key \"c\"\n\tcache.Set(\"e\", blob(0xff, 3))\n\t// expire the zero bytes\n\tcache.Set(\"f\", blob(0xff, 3))\n\t// expire the key \"b\"\n\tcache.Set(\"g\", blob(0xff, 3))\n\t_, err := cache.Get(\"b\")\n\tassertEqual(t, err, ErrEntryNotFound)\n\tdata, _ := cache.Get(\"g\")\n\tassertEqual(t, []byte{0xff, 0xff, 0xff}, data)\n}\n\nfunc TestRemoveNonExpiredData(t *testing.T) {\n\tonRemove := func(key string, entry []byte, reason RemoveReason) {\n\t\tif reason != Deleted {\n\t\t\tif reason == Expired {\n\t\t\t\tt.Errorf(\"[%d]Expired OnRemove [%s]\\n\", reason, key)\n\t\t\t\tt.FailNow()\n\t\t\t} else {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}\n\t}\n\n\tconfig := DefaultConfig(10 * time.Minute)\n\tconfig.HardMaxCacheSize = 1\n\tconfig.MaxEntrySize = 1024\n\tconfig.MaxEntriesInWindow = 1024\n\tconfig.OnRemoveWithReason = onRemove\n\tcache, err := New(context.Background(), config)\n\tnoError(t, err)\n\tdefer func() {\n\t\terr := cache.Close()\n\t\tnoError(t, err)\n\t}()\n\n\tdata := func(l int) []byte {\n\t\tm := make([]byte, l)\n\t\t_, err := rand.Read(m)\n\t\tnoError(t, err)\n\t\treturn m\n\t}\n\n\tfor i := 0; i < 50; i++ {\n\t\tkey := fmt.Sprintf(\"key_%d\", i)\n\t\t//key := \"key1\"\n\t\terr := cache.Set(key, data(800))\n\t\tnoError(t, err)\n\t}\n}\n"
  },
  {
    "path": "bytes.go",
    "content": "//go:build !appengine\n// +build !appengine\n\npackage bigcache\n\nimport (\n\t\"unsafe\"\n)\n\nfunc bytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}\n"
  },
  {
    "path": "bytes_appengine.go",
    "content": "//go:build appengine\n\npackage bigcache\n\nfunc bytesToString(b []byte) string {\n\treturn string(b)\n}\n"
  },
  {
    "path": "clock.go",
    "content": "package bigcache\n\nimport \"time\"\n\ntype clock interface {\n\tEpoch() int64\n}\n\ntype systemClock struct {\n}\n\nfunc (c systemClock) Epoch() int64 {\n\treturn time.Now().Unix()\n}\n"
  },
  {
    "path": "config.go",
    "content": "package bigcache\n\nimport \"time\"\n\n// Config for BigCache\ntype Config struct {\n\t// Number of cache shards, value must be a power of two\n\tShards int\n\t// Time after which entry can be evicted\n\tLifeWindow time.Duration\n\t// Interval between removing expired entries (clean up).\n\t// If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution.\n\tCleanWindow time.Duration\n\t// Max number of entries in life window. Used only to calculate initial size for cache shards.\n\t// When proper value is set then additional memory allocation does not occur.\n\tMaxEntriesInWindow int\n\t// Max size of entry in bytes. Used only to calculate initial size for cache shards.\n\tMaxEntrySize int\n\t// StatsEnabled if true calculate the number of times a cached resource was requested.\n\tStatsEnabled bool\n\t// Verbose mode prints information about new memory allocation\n\tVerbose bool\n\t// Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used.\n\tHasher Hasher\n\t// HardMaxCacheSize is a limit for BytesQueue size in MB.\n\t// It can protect application from consuming all available memory on machine, therefore from running OOM Killer.\n\t// Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then\n\t// the oldest entries are overridden for the new ones. The max memory consumption will be bigger than\n\t// HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys\n\t// and statistics (map[uint64]uint32) the size of this map is equal to number of entries in\n\t// cache ~ 2×(64+32)×n bits + overhead or map itself.\n\tHardMaxCacheSize int\n\t// OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left\n\t// for the new entry, or because delete was called.\n\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t// ignored if OnRemoveWithMetadata is specified.\n\tOnRemove func(key string, entry []byte)\n\t// OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left\n\t// for the new entry, or because delete was called. A structure representing details about that specific entry.\n\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\tOnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata)\n\t// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left\n\t// for the new entry, or because delete was called. A constant representing the reason will be passed through.\n\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t// Ignored if OnRemove is specified.\n\tOnRemoveWithReason func(key string, entry []byte, reason RemoveReason)\n\n\tonRemoveFilter int\n\n\t// Logger is a logging interface and used in combination with `Verbose`\n\t// Defaults to `DefaultLogger()`\n\tLogger Logger\n}\n\n// DefaultConfig initializes config with default values.\n// When load for BigCache can be predicted in advance then it is better to use custom config.\nfunc DefaultConfig(eviction time.Duration) Config {\n\treturn Config{\n\t\tShards:             1024,\n\t\tLifeWindow:         eviction,\n\t\tCleanWindow:        1 * time.Second,\n\t\tMaxEntriesInWindow: 1000 * 10 * 60,\n\t\tMaxEntrySize:       500,\n\t\tStatsEnabled:       false,\n\t\tVerbose:            true,\n\t\tHasher:             newDefaultHasher(),\n\t\tHardMaxCacheSize:   0,\n\t\tLogger:             DefaultLogger(),\n\t}\n}\n\n// initialShardSize computes initial shard size\nfunc (c Config) initialShardSize() int {\n\treturn max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard)\n}\n\n// maximumShardSizeInBytes computes maximum shard size in bytes\nfunc (c Config) maximumShardSizeInBytes() int {\n\tmaxShardSize := 0\n\n\tif c.HardMaxCacheSize > 0 {\n\t\tmaxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards\n\t}\n\n\treturn maxShardSize\n}\n\n// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason.\n// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu.\nfunc (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config {\n\tc.onRemoveFilter = 0\n\tfor i := range reasons {\n\t\tc.onRemoveFilter |= 1 << uint(reasons[i])\n\t}\n\n\treturn c\n}\n"
  },
  {
    "path": "encoding.go",
    "content": "package bigcache\n\nimport (\n\t\"encoding/binary\"\n)\n\nconst (\n\ttimestampSizeInBytes = 8                                                       // Number of bytes used for timestamp\n\thashSizeInBytes      = 8                                                       // Number of bytes used for hash\n\tkeySizeInBytes       = 2                                                       // Number of bytes used for size of entry key\n\theadersSizeInBytes   = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers\n)\n\nfunc wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {\n\tkeyLength := len(key)\n\tblobLength := len(entry) + headersSizeInBytes + keyLength\n\n\tif blobLength > len(*buffer) {\n\t\t*buffer = make([]byte, blobLength)\n\t}\n\tblob := *buffer\n\n\tbinary.LittleEndian.PutUint64(blob, timestamp)\n\tbinary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash)\n\tbinary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength))\n\tcopy(blob[headersSizeInBytes:], key)\n\tcopy(blob[headersSizeInBytes+keyLength:], entry)\n\n\treturn blob[:blobLength]\n}\n\nfunc appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte {\n\tblobLength := len(wrappedEntry) + len(entry)\n\tif blobLength > len(*buffer) {\n\t\t*buffer = make([]byte, blobLength)\n\t}\n\n\tblob := *buffer\n\n\tbinary.LittleEndian.PutUint64(blob, timestamp)\n\tcopy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:])\n\tcopy(blob[len(wrappedEntry):], entry)\n\n\treturn blob[:blobLength]\n}\n\nfunc readEntry(data []byte) []byte {\n\tlength := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])\n\n\t// copy on read\n\tdst := make([]byte, len(data)-int(headersSizeInBytes+length))\n\tcopy(dst, data[headersSizeInBytes+length:])\n\n\treturn dst\n}\n\nfunc readTimestampFromEntry(data []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(data)\n}\n\nfunc readKeyFromEntry(data []byte) string {\n\tlength := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])\n\n\t// copy on read\n\tdst := make([]byte, length)\n\tcopy(dst, data[headersSizeInBytes:headersSizeInBytes+length])\n\n\treturn bytesToString(dst)\n}\n\nfunc compareKeyFromEntry(data []byte, key string) bool {\n\tlength := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])\n\n\treturn bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key\n}\n\nfunc readHashFromEntry(data []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(data[timestampSizeInBytes:])\n}\n\nfunc resetHashFromEntry(data []byte) {\n\tbinary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0)\n}\n"
  },
  {
    "path": "encoding_test.go",
    "content": "package bigcache\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestEncodeDecode(t *testing.T) {\n\t// given\n\tnow := uint64(time.Now().Unix())\n\thash := uint64(42)\n\tkey := \"key\"\n\tdata := []byte(\"data\")\n\tbuffer := make([]byte, 100)\n\n\t// when\n\twrapped := wrapEntry(now, hash, key, data, &buffer)\n\n\t// then\n\tassertEqual(t, key, readKeyFromEntry(wrapped))\n\tassertEqual(t, hash, readHashFromEntry(wrapped))\n\tassertEqual(t, now, readTimestampFromEntry(wrapped))\n\tassertEqual(t, data, readEntry(wrapped))\n\tassertEqual(t, 100, len(buffer))\n}\n\nfunc TestAllocateBiggerBuffer(t *testing.T) {\n\t//given\n\tnow := uint64(time.Now().Unix())\n\thash := uint64(42)\n\tkey := \"1\"\n\tdata := []byte(\"2\")\n\tbuffer := make([]byte, 1)\n\n\t// when\n\twrapped := wrapEntry(now, hash, key, data, &buffer)\n\n\t// then\n\tassertEqual(t, key, readKeyFromEntry(wrapped))\n\tassertEqual(t, hash, readHashFromEntry(wrapped))\n\tassertEqual(t, now, readTimestampFromEntry(wrapped))\n\tassertEqual(t, data, readEntry(wrapped))\n\tassertEqual(t, 2+headersSizeInBytes, len(buffer))\n}\n"
  },
  {
    "path": "entry_not_found_error.go",
    "content": "package bigcache\n\nimport \"errors\"\n\nvar (\n\t// ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key\n\tErrEntryNotFound = errors.New(\"Entry not found\") //nolint:staticcheck // keep for backward compatibility\n)\n"
  },
  {
    "path": "examples_test.go",
    "content": "package bigcache_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/allegro/bigcache/v3\"\n)\n\nfunc Example() {\n\tcache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute))\n\n\tcache.Set(\"my-unique-key\", []byte(\"value\"))\n\n\tentry, _ := cache.Get(\"my-unique-key\")\n\tfmt.Println(string(entry))\n\t// Output: value\n}\n\nfunc Example_custom() {\n\t// When cache load can be predicted in advance then it is better to use custom initialization\n\t// because additional memory allocation can be avoided in that way.\n\tconfig := bigcache.Config{\n\t\t// number of shards (must be a power of 2)\n\t\tShards: 1024,\n\n\t\t// time after which entry can be evicted\n\t\tLifeWindow: 10 * time.Minute,\n\n\t\t// Interval between removing expired entries (clean up).\n\t\t// If set to <= 0 then no action is performed.\n\t\t// Setting to < 1 second is counterproductive — bigcache has a one second resolution.\n\t\tCleanWindow: 5 * time.Minute,\n\n\t\t// rps * lifeWindow, used only in initial memory allocation\n\t\tMaxEntriesInWindow: 1000 * 10 * 60,\n\n\t\t// max entry size in bytes, used only in initial memory allocation\n\t\tMaxEntrySize: 500,\n\n\t\t// prints information about additional memory allocation\n\t\tVerbose: true,\n\n\t\t// cache will not allocate more memory than this limit, value in MB\n\t\t// if value is reached then the oldest entries can be overridden for the new ones\n\t\t// 0 value means no size limit\n\t\tHardMaxCacheSize: 8192,\n\n\t\t// callback fired when the oldest entry is removed because of its expiration time or no space left\n\t\t// for the new entry, or because delete was called. A bitmask representing the reason will be returned.\n\t\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t\tOnRemove: nil,\n\n\t\t// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left\n\t\t// for the new entry, or because delete was called. A constant representing the reason will be passed through.\n\t\t// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.\n\t\t// Ignored if OnRemove is specified.\n\t\tOnRemoveWithReason: nil,\n\t}\n\n\tcache, initErr := bigcache.New(context.Background(), config)\n\tif initErr != nil {\n\t\tlog.Fatal(initErr)\n\t}\n\n\terr := cache.Set(\"my-unique-key\", []byte(\"value\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tentry, err := cache.Get(\"my-unique-key\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(string(entry))\n\t// Output: value\n}\n"
  },
  {
    "path": "fnv.go",
    "content": "package bigcache\n\n// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations.\n// Its Sum64 method will lay the value out in big-endian byte order.\n// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function\nfunc newDefaultHasher() Hasher {\n\treturn fnv64a{}\n}\n\ntype fnv64a struct{}\n\nconst (\n\t// offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash\n\toffset64 = 14695981039346656037\n\t// prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash\n\tprime64 = 1099511628211\n)\n\n// Sum64 gets the string and returns its uint64 hash value.\nfunc (f fnv64a) Sum64(key string) uint64 {\n\tvar hash uint64 = offset64\n\tfor i := 0; i < len(key); i++ {\n\t\thash ^= uint64(key[i])\n\t\thash *= prime64\n\t}\n\n\treturn hash\n}\n"
  },
  {
    "path": "fnv_bench_test.go",
    "content": "package bigcache\n\nimport \"testing\"\n\nvar text = \"abcdefg\"\n\nfunc BenchmarkFnvHashSum64(b *testing.B) {\n\th := newDefaultHasher()\n\tfor i := 0; i < b.N; i++ {\n\t\th.Sum64(text)\n\t}\n}\n\nfunc BenchmarkFnvHashStdLibSum64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tstdLibFnvSum64(text)\n\t}\n}\n"
  },
  {
    "path": "fnv_test.go",
    "content": "package bigcache\n\nimport (\n\t\"hash/fnv\"\n\t\"testing\"\n)\n\ntype testCase struct {\n\ttext         string\n\texpectedHash uint64\n}\n\nvar testCases = []testCase{\n\t{\"\", stdLibFnvSum64(\"\")},\n\t{\"a\", stdLibFnvSum64(\"a\")},\n\t{\"ab\", stdLibFnvSum64(\"ab\")},\n\t{\"abc\", stdLibFnvSum64(\"abc\")},\n\t{\"some longer and more complicated text\", stdLibFnvSum64(\"some longer and more complicated text\")},\n}\n\nfunc TestFnvHashSum64(t *testing.T) {\n\th := newDefaultHasher()\n\tfor _, testCase := range testCases {\n\t\thashed := h.Sum64(testCase.text)\n\t\tif hashed != testCase.expectedHash {\n\t\t\tt.Errorf(\"hash(%q) = %d want %d\", testCase.text, hashed, testCase.expectedHash)\n\t\t}\n\t}\n}\n\nfunc stdLibFnvSum64(key string) uint64 {\n\th := fnv.New64a()\n\th.Write([]byte(key))\n\treturn h.Sum64()\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/allegro/bigcache/v3\n\ngo 1.16\n"
  },
  {
    "path": "go.sum",
    "content": ""
  },
  {
    "path": "hash.go",
    "content": "package bigcache\n\n// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions\n// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e.\n// you can use FarmHash family).\ntype Hasher interface {\n\tSum64(string) uint64\n}\n"
  },
  {
    "path": "hash_test.go",
    "content": "package bigcache\n\ntype hashStub uint64\n\nfunc (stub hashStub) Sum64(_ string) uint64 {\n\treturn uint64(stub)\n}\n"
  },
  {
    "path": "iterator.go",
    "content": "package bigcache\n\nimport (\n\t\"sync\"\n)\n\ntype iteratorError string\n\nfunc (e iteratorError) Error() string {\n\treturn string(e)\n}\n\n// ErrInvalidIteratorState is reported when iterator is in invalid state\nconst ErrInvalidIteratorState = iteratorError(\"Iterator is in invalid state. Use SetNext() to move to next position\")\n\n// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying\nconst ErrCannotRetrieveEntry = iteratorError(\"Could not retrieve entry from cache\")\n\nvar emptyEntryInfo = EntryInfo{}\n\n// EntryInfo holds informations about entry in the cache\ntype EntryInfo struct {\n\ttimestamp uint64\n\thash      uint64\n\tkey       string\n\tvalue     []byte\n\terr       error\n}\n\n// Key returns entry's underlying key\nfunc (e EntryInfo) Key() string {\n\treturn e.key\n}\n\n// Hash returns entry's hash value\nfunc (e EntryInfo) Hash() uint64 {\n\treturn e.hash\n}\n\n// Timestamp returns entry's timestamp (time of insertion)\nfunc (e EntryInfo) Timestamp() uint64 {\n\treturn e.timestamp\n}\n\n// Value returns entry's underlying value\nfunc (e EntryInfo) Value() []byte {\n\treturn e.value\n}\n\n// EntryInfoIterator allows to iterate over entries in the cache\ntype EntryInfoIterator struct {\n\tmutex            sync.Mutex\n\tcache            *BigCache\n\tcurrentShard     int\n\tcurrentIndex     int\n\tcurrentEntryInfo EntryInfo\n\telements         []uint64\n\telementsCount    int\n\tvalid            bool\n}\n\n// SetNext moves to next element and returns true if it exists.\nfunc (it *EntryInfoIterator) SetNext() bool {\n\tit.mutex.Lock()\n\n\tit.valid = false\n\tit.currentIndex++\n\n\tif it.elementsCount > it.currentIndex {\n\t\tit.valid = true\n\n\t\tempty := it.setCurrentEntry()\n\t\tit.mutex.Unlock()\n\n\t\tif empty {\n\t\t\treturn it.SetNext()\n\t\t}\n\t\treturn true\n\t}\n\n\tfor i := it.currentShard + 1; i < it.cache.config.Shards; i++ {\n\t\tit.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys()\n\n\t\t// Non empty shard - stick with it\n\t\tif it.elementsCount > 0 {\n\t\t\tit.currentIndex = 0\n\t\t\tit.currentShard = i\n\t\t\tit.valid = true\n\n\t\t\tempty := it.setCurrentEntry()\n\t\t\tit.mutex.Unlock()\n\n\t\t\tif empty {\n\t\t\t\treturn it.SetNext()\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\tit.mutex.Unlock()\n\treturn false\n}\n\nfunc (it *EntryInfoIterator) setCurrentEntry() bool {\n\tvar entryNotFound = false\n\tentry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex])\n\n\tif err == ErrEntryNotFound {\n\t\tit.currentEntryInfo = emptyEntryInfo\n\t\tentryNotFound = true\n\t} else if err != nil {\n\t\tit.currentEntryInfo = EntryInfo{\n\t\t\terr: err,\n\t\t}\n\t} else {\n\t\tit.currentEntryInfo = EntryInfo{\n\t\t\ttimestamp: readTimestampFromEntry(entry),\n\t\t\thash:      readHashFromEntry(entry),\n\t\t\tkey:       readKeyFromEntry(entry),\n\t\t\tvalue:     readEntry(entry),\n\t\t\terr:       err,\n\t\t}\n\t}\n\n\treturn entryNotFound\n}\n\nfunc newIterator(cache *BigCache) *EntryInfoIterator {\n\telements, count := cache.shards[0].copyHashedKeys()\n\n\treturn &EntryInfoIterator{\n\t\tcache:         cache,\n\t\tcurrentShard:  0,\n\t\tcurrentIndex:  -1,\n\t\telements:      elements,\n\t\telementsCount: count,\n\t}\n}\n\n// Value returns current value from the iterator\nfunc (it *EntryInfoIterator) Value() (EntryInfo, error) {\n\tif !it.valid {\n\t\treturn emptyEntryInfo, ErrInvalidIteratorState\n\t}\n\n\treturn it.currentEntryInfo, it.currentEntryInfo.err\n}\n"
  },
  {
    "path": "iterator_test.go",
    "content": "package bigcache\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestEntriesIterator(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tkeysCount := 1000\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         6 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\tvalue := []byte(\"value\")\n\n\tfor i := 0; i < keysCount; i++ {\n\t\tcache.Set(fmt.Sprintf(\"key%d\", i), value)\n\t}\n\n\t// when\n\tkeys := make(map[string]struct{})\n\titerator := cache.Iterator()\n\n\tfor iterator.SetNext() {\n\t\tcurrent, err := iterator.Value()\n\n\t\tif err == nil {\n\t\t\tkeys[current.Key()] = struct{}{}\n\t\t}\n\t}\n\n\t// then\n\tassertEqual(t, keysCount, len(keys))\n}\n\nfunc TestEntriesIteratorWithMostShardsEmpty(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tclock := mockedClock{value: 0}\n\tcache, _ := newBigCache(context.Background(), Config{\n\t\tShards:             8,\n\t\tLifeWindow:         6 * time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t}, &clock)\n\n\tcache.Set(\"key\", []byte(\"value\"))\n\n\t// when\n\titerator := cache.Iterator()\n\n\t// then\n\tif !iterator.SetNext() {\n\t\tt.Errorf(\"Iterator should contain at least single element\")\n\t}\n\n\tcurrent, err := iterator.Value()\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, \"key\", current.Key())\n\tassertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash())\n\tassertEqual(t, []byte(\"value\"), current.Value())\n\tassertEqual(t, uint64(0), current.Timestamp())\n}\n\nfunc TestEntriesIteratorWithConcurrentUpdate(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\tcache.Set(\"key\", []byte(\"value\"))\n\n\t// when\n\titerator := cache.Iterator()\n\n\t// then\n\tif !iterator.SetNext() {\n\t\tt.Errorf(\"Iterator should contain at least single element\")\n\t}\n\n\tgetOldestEntry := func(s *cacheShard) ([]byte, error) {\n\t\ts.lock.RLock()\n\t\tdefer s.lock.RUnlock()\n\t\treturn s.entries.Peek()\n\t}\n\n\t// Quite ugly but works\n\tfor i := 0; i < cache.config.Shards; i++ {\n\t\tif oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil {\n\t\t\tcache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry)\n\t\t}\n\t}\n\n\tcurrent, err := iterator.Value()\n\tassertEqual(t, nil, err)\n\tassertEqual(t, []byte(\"value\"), current.Value())\n\n\tnext := iterator.SetNext()\n\tassertEqual(t, false, next)\n}\n\nfunc TestEntriesIteratorWithAllShardsEmpty(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\titerator := cache.Iterator()\n\n\t// then\n\tif iterator.SetNext() {\n\t\tt.Errorf(\"Iterator should not contain any elements\")\n\t}\n}\n\nfunc TestEntriesIteratorInInvalidState(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 1,\n\t\tMaxEntrySize:       256,\n\t})\n\n\t// when\n\titerator := cache.Iterator()\n\n\t// then\n\t_, err := iterator.Value()\n\tassertEqual(t, ErrInvalidIteratorState, err)\n\tassertEqual(t, \"Iterator is in invalid state. Use SetNext() to move to next position\", err.Error())\n}\n\nfunc TestEntriesIteratorParallelAdd(t *testing.T) {\n\tbc, err := New(context.Background(), DefaultConfig(1*time.Minute))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tfor i := 0; i < 10000; i++ {\n\t\t\terr := bc.Set(strconv.Itoa(i), []byte(\"aaaaaaa\"))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\truntime.Gosched()\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tfor i := 0; i < 100; i++ {\n\t\titer := bc.Iterator()\n\t\tfor iter.SetNext() {\n\t\t\t_, _ = iter.Value()\n\t\t}\n\t}\n\twg.Wait()\n}\n\nfunc TestParallelSetAndIteration(t *testing.T) {\n\tt.Parallel()\n\n\trand.Seed(0)\n\n\tcache, _ := New(context.Background(), Config{\n\t\tShards:             1,\n\t\tLifeWindow:         time.Second,\n\t\tMaxEntriesInWindow: 100,\n\t\tMaxEntrySize:       256,\n\t\tHardMaxCacheSize:   1,\n\t\tVerbose:            true,\n\t})\n\n\tentrySize := 1024 * 100\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\twg := sync.WaitGroup{}\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\terr := recover()\n\t\t\t// no panic\n\t\t\tassertEqual(t, err, nil)\n\t\t}()\n\n\t\tdefer wg.Done()\n\n\t\tisTimeout := false\n\n\t\tfor !isTimeout {\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tisTimeout = true\n\t\t\tdefault:\n\t\t\t\terr := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize))\n\t\t\t\tnoError(t, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\terr := recover()\n\t\t\t// no panic\n\t\t\tassertEqual(t, nil, err)\n\t\t}()\n\n\t\tdefer wg.Done()\n\n\t\tisTimeout := false\n\n\t\tfor !isTimeout {\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tisTimeout = true\n\t\t\tdefault:\n\t\t\t\titer := cache.Iterator()\n\t\t\t\tfor iter.SetNext() {\n\t\t\t\t\tentry, err := iter.Value()\n\n\t\t\t\t\t// then\n\t\t\t\t\tnoError(t, err)\n\t\t\t\t\tassertEqual(t, entrySize, len(entry.Value()))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n"
  },
  {
    "path": "logger.go",
    "content": "package bigcache\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n// Logger is invoked when `Config.Verbose=true`\ntype Logger interface {\n\tPrintf(format string, v ...interface{})\n}\n\n// this is a safeguard, breaking on compile time in case\n// `log.Logger` does not adhere to our `Logger` interface.\n// see https://golang.org/doc/faq#guarantee_satisfies_interface\nvar _ Logger = &log.Logger{}\n\n// DefaultLogger returns a `Logger` implementation\n// backed by stdlib's log\nfunc DefaultLogger() *log.Logger {\n\treturn log.New(os.Stdout, \"\", log.LstdFlags)\n}\n\nfunc newLogger(custom Logger) Logger {\n\tif custom != nil {\n\t\treturn custom\n\t}\n\n\treturn DefaultLogger()\n}\n"
  },
  {
    "path": "queue/bytes_queue.go",
    "content": "package queue\n\nimport (\n\t\"encoding/binary\"\n\t\"log\"\n\t\"time\"\n)\n\nconst (\n\t// Number of bytes to encode 0 in uvarint format\n\tminimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes\n\t// Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index\n\tleftMarginIndex = 1\n)\n\nvar (\n\terrEmptyQueue       = &queueError{\"Empty queue\"}\n\terrInvalidIndex     = &queueError{\"Index must be greater than zero. Invalid index.\"}\n\terrIndexOutOfBounds = &queueError{\"Index out of range\"}\n\terrFullQueue        = &queueError{\"Full queue. Maximum size limit reached.\"}\n)\n\n// BytesQueue is a non-thread safe queue type of fifo based on bytes array.\n// For every push operation index of entry is returned. It can be used to read the entry later\ntype BytesQueue struct {\n\tfull         bool\n\tarray        []byte\n\tcapacity     int\n\tmaxCapacity  int\n\thead         int\n\ttail         int\n\tcount        int\n\trightMargin  int\n\theaderBuffer []byte\n\tverbose      bool\n}\n\ntype queueError struct {\n\tmessage string\n}\n\n// getNeededSize returns the number of bytes an entry of length need in the queue\nfunc getNeededSize(length int) int {\n\tvar header int\n\tswitch {\n\tcase length < 127: // 1<<7-1\n\t\theader = 1\n\tcase length < 16382: // 1<<14-2\n\t\theader = 2\n\tcase length < 2097149: // 1<<21 -3\n\t\theader = 3\n\tcase length < 268435452: // 1<<28 -4\n\t\theader = 4\n\tdefault:\n\t\theader = 5\n\t}\n\n\treturn length + header\n}\n\n// NewBytesQueue initialize new bytes queue.\n// capacity is used in bytes array allocation\n// When verbose flag is set then information about memory allocation are printed\nfunc NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue {\n\treturn &BytesQueue{\n\t\tarray:        make([]byte, capacity),\n\t\tcapacity:     capacity,\n\t\tmaxCapacity:  maxCapacity,\n\t\theaderBuffer: make([]byte, binary.MaxVarintLen32),\n\t\ttail:         leftMarginIndex,\n\t\thead:         leftMarginIndex,\n\t\trightMargin:  leftMarginIndex,\n\t\tverbose:      verbose,\n\t}\n}\n\n// Reset removes all entries from queue\nfunc (q *BytesQueue) Reset() {\n\t// Just reset indexes\n\tq.tail = leftMarginIndex\n\tq.head = leftMarginIndex\n\tq.rightMargin = leftMarginIndex\n\tq.count = 0\n\tq.full = false\n}\n\n// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed.\n// Returns index for pushed data or error if maximum size queue limit is reached.\nfunc (q *BytesQueue) Push(data []byte) (int, error) {\n\tneededSize := getNeededSize(len(data))\n\n\tif !q.canInsertAfterTail(neededSize) {\n\t\tif q.canInsertBeforeHead(neededSize) {\n\t\t\tq.tail = leftMarginIndex\n\t\t} else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 {\n\t\t\treturn -1, errFullQueue\n\t\t} else {\n\t\t\tq.allocateAdditionalMemory(neededSize)\n\t\t}\n\t}\n\n\tindex := q.tail\n\n\tq.push(data, neededSize)\n\n\treturn index, nil\n}\n\nfunc (q *BytesQueue) allocateAdditionalMemory(minimum int) {\n\tstart := time.Now()\n\tif q.capacity < minimum {\n\t\tq.capacity += minimum\n\t}\n\tq.capacity = q.capacity * 2\n\tif q.capacity > q.maxCapacity && q.maxCapacity > 0 {\n\t\tq.capacity = q.maxCapacity\n\t}\n\n\toldArray := q.array\n\tq.array = make([]byte, q.capacity)\n\n\tif leftMarginIndex != q.rightMargin {\n\t\tcopy(q.array, oldArray[:q.rightMargin])\n\n\t\tif q.tail <= q.head {\n\t\t\tif q.tail != q.head {\n\t\t\t\t// created slice is slightly larger than need but this is fine after only the needed bytes are copied\n\t\t\t\tq.push(make([]byte, q.head-q.tail), q.head-q.tail)\n\t\t\t}\n\n\t\t\tq.head = leftMarginIndex\n\t\t\tq.tail = q.rightMargin\n\t\t}\n\t}\n\n\tq.full = false\n\n\tif q.verbose {\n\t\tlog.Printf(\"Allocated new queue in %s; Capacity: %d \\n\", time.Since(start), q.capacity)\n\t}\n}\n\nfunc (q *BytesQueue) push(data []byte, len int) {\n\theaderEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len))\n\tq.copy(q.headerBuffer, headerEntrySize)\n\n\tq.copy(data, len-headerEntrySize)\n\n\tif q.tail > q.head {\n\t\tq.rightMargin = q.tail\n\t}\n\tif q.tail == q.head {\n\t\tq.full = true\n\t}\n\n\tq.count++\n}\n\nfunc (q *BytesQueue) copy(data []byte, len int) {\n\tq.tail += copy(q.array[q.tail:], data[:len])\n}\n\n// Pop reads the oldest entry from queue and moves head pointer to the next one\nfunc (q *BytesQueue) Pop() ([]byte, error) {\n\tdata, blockSize, err := q.peek(q.head)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.head += blockSize\n\tq.count--\n\n\tif q.head == q.rightMargin {\n\t\tq.head = leftMarginIndex\n\t\tif q.tail == q.rightMargin {\n\t\t\tq.tail = leftMarginIndex\n\t\t}\n\t\tq.rightMargin = q.tail\n\t}\n\n\tq.full = false\n\n\treturn data, nil\n}\n\n// Peek reads the oldest entry from list without moving head pointer\nfunc (q *BytesQueue) Peek() ([]byte, error) {\n\tdata, _, err := q.peek(q.head)\n\treturn data, err\n}\n\n// Get reads entry from index\nfunc (q *BytesQueue) Get(index int) ([]byte, error) {\n\tdata, _, err := q.peek(index)\n\treturn data, err\n}\n\n// CheckGet checks if an entry can be read from index\nfunc (q *BytesQueue) CheckGet(index int) error {\n\treturn q.peekCheckErr(index)\n}\n\n// Capacity returns number of allocated bytes for queue\nfunc (q *BytesQueue) Capacity() int {\n\treturn q.capacity\n}\n\n// Len returns number of entries kept in queue\nfunc (q *BytesQueue) Len() int {\n\treturn q.count\n}\n\n// Error returns error message\nfunc (e *queueError) Error() string {\n\treturn e.message\n}\n\n// peekCheckErr is identical to peek, but does not actually return any data\nfunc (q *BytesQueue) peekCheckErr(index int) error {\n\n\tif q.count == 0 {\n\t\treturn errEmptyQueue\n\t}\n\n\tif index <= 0 {\n\t\treturn errInvalidIndex\n\t}\n\n\tif index >= len(q.array) {\n\t\treturn errIndexOutOfBounds\n\t}\n\treturn nil\n}\n\n// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format\nfunc (q *BytesQueue) peek(index int) ([]byte, int, error) {\n\terr := q.peekCheckErr(index)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tblockSize, n := binary.Uvarint(q.array[index:])\n\treturn q.array[index+n : index+int(blockSize)], int(blockSize), nil\n}\n\n// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue\nfunc (q *BytesQueue) canInsertAfterTail(need int) bool {\n\tif q.full {\n\t\treturn false\n\t}\n\tif q.tail >= q.head {\n\t\treturn q.capacity-q.tail >= need\n\t}\n\t// 1. there is exactly need bytes between head and tail, so we do not need\n\t// to reserve extra space for a potential empty entry when realloc this queue\n\t// 2. still have unused space between tail and head, then we must reserve\n\t// at least headerEntrySize bytes so we can put an empty entry\n\treturn q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize\n}\n\n// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue\nfunc (q *BytesQueue) canInsertBeforeHead(need int) bool {\n\tif q.full {\n\t\treturn false\n\t}\n\tif q.tail >= q.head {\n\t\treturn q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize\n\t}\n\treturn q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize\n}\n"
  },
  {
    "path": "queue/bytes_queue_test.go",
    "content": "package queue\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"path\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc TestPushAndPop(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(10, 0, true)\n\tentry := []byte(\"hello\")\n\n\t// when\n\t_, err := queue.Pop()\n\n\t// then\n\tassertEqual(t, \"Empty queue\", err.Error())\n\n\t// when\n\tqueue.Push(entry)\n\n\t// then\n\tassertEqual(t, entry, pop(queue))\n}\n\nfunc TestLen(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\tentry := []byte(\"hello\")\n\tassertEqual(t, 0, queue.Len())\n\n\t// when\n\tqueue.Push(entry)\n\n\t// then\n\tassertEqual(t, queue.Len(), 1)\n}\n\nfunc TestPeek(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\tentry := []byte(\"hello\")\n\n\t// when\n\tread, err := queue.Peek()\n\terr2 := queue.peekCheckErr(queue.head)\n\t// then\n\tassertEqual(t, err, err2)\n\tassertEqual(t, \"Empty queue\", err.Error())\n\tassertEqual(t, 0, len(read))\n\n\t// when\n\tqueue.Push(entry)\n\tread, err = queue.Peek()\n\terr2 = queue.peekCheckErr(queue.head)\n\n\t// then\n\tassertEqual(t, err, err2)\n\tnoError(t, err)\n\tassertEqual(t, pop(queue), read)\n\tassertEqual(t, entry, read)\n}\n\nfunc TestResetFullQueue(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(10, 20, false)\n\n\t// when\n\tqueue.Push(blob('a', 3))\n\tqueue.Push(blob('b', 4))\n\n\t// when\n\tassertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning\n\t_, err := queue.Push(blob('a', 3))       // will set q.full to true\n\n\t// then\n\tassertEqual(t, err, nil)\n\n\t// when\n\tqueue.Reset()\n\tqueue.Push(blob('c', 8)) // should not trigger a re-allocation\n\n\t// then\n\tassertEqual(t, blob('c', 8), pop(queue))\n\tassertEqual(t, queue.Capacity(), 10)\n}\n\nfunc TestReset(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\tentry := []byte(\"hello\")\n\n\t// when\n\tqueue.Push(entry)\n\tqueue.Push(entry)\n\tqueue.Push(entry)\n\n\tqueue.Reset()\n\tread, err := queue.Peek()\n\n\t// then\n\tassertEqual(t, \"Empty queue\", err.Error())\n\tassertEqual(t, 0, len(read))\n\n\t// when\n\tqueue.Push(entry)\n\tread, err = queue.Peek()\n\n\t// then\n\tnoError(t, err)\n\tassertEqual(t, pop(queue), read)\n\tassertEqual(t, entry, read)\n\n\t// when\n\tread, err = queue.Peek()\n\n\t// then\n\tassertEqual(t, \"Empty queue\", err.Error())\n\tassertEqual(t, 0, len(read))\n}\n\nfunc TestReuseAvailableSpace(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 70))\n\tqueue.Push(blob('b', 20))\n\tqueue.Pop()\n\tqueue.Push(blob('c', 20))\n\n\t// then\n\tassertEqual(t, 100, queue.Capacity())\n\tassertEqual(t, blob('b', 20), pop(queue))\n}\n\nfunc TestAllocateAdditionalSpace(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(11, 0, false)\n\n\t// when\n\tqueue.Push([]byte(\"hello1\"))\n\tqueue.Push([]byte(\"hello2\"))\n\n\t// then\n\tassertEqual(t, 22, queue.Capacity())\n}\n\nfunc TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(25, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes\n\tqueue.Push(blob('b', 6)) // additional 7 bytes\n\tqueue.Pop()              // space freed, 4 bytes available at the beginning\n\tqueue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail\n\n\t// then\n\tassertEqual(t, 25, queue.Capacity())\n\tassertEqual(t, blob('b', 6), pop(queue))\n\tassertEqual(t, blob('c', 6), pop(queue))\n}\n\nfunc TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(25, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 3))                   // header + entry + left margin = 5 bytes\n\tindex, _ := queue.Push(blob('b', 6))       // additional 7 bytes\n\tqueue.Pop()                                // space freed, 4 bytes available at the beginning\n\tnewestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail\n\n\t// then\n\tassertEqual(t, 25, queue.Capacity())\n\tassertEqual(t, blob('b', 6), get(queue, index))\n\tassertEqual(t, blob('c', 6), get(queue, newestIndex))\n}\n\nfunc TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes\n\tqueue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes\n\tqueue.Pop()               // space freed at the beginning\n\tqueue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer\n\tqueue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory\n\n\t// then\n\tassertEqual(t, 200, queue.Capacity())\n\tassertEqual(t, blob('c', 30), pop(queue))\n\t// empty blob fills space between tail and head,\n\t// created when additional memory was allocated,\n\t// it keeps current entries indexes unchanged\n\tassertEqual(t, blob(0, 39), pop(queue))\n\tassertEqual(t, blob('b', 10), pop(queue))\n\tassertEqual(t, blob('d', 40), pop(queue))\n}\n\nfunc TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(200, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 30))  //  header + entry + left margin = 32 bytes\n\tqueue.Push(blob('b', 1))   // 32 + 128 + 1 = 161 bytes\n\tqueue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes\n\tqueue.Push(blob('c', 20))  //  160 + 20 + 1 = 182\n\tqueue.Pop()                // space freed at the beginning\n\tqueue.Pop()                // free 2 bytes\n\tqueue.Pop()                // free 126\n\tqueue.Push(blob('d', 30))  // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes\n\tqueue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled)\n\n\t// then\n\tassertEqual(t, 400, queue.Capacity())\n\tassertEqual(t, blob('d', 30), pop(queue))\n\tassertEqual(t, blob(0, 126), pop(queue))  //126 bytes data with 2bytes header only possible as empty entry\n\tassertEqual(t, blob('c', 20), pop(queue)) //The data is not expected\n\tassertEqual(t, blob('e', 160), pop(queue))\n}\n\nfunc TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(100, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 70))                   // header + entry + left margin = 72 bytes\n\tindex, _ := queue.Push(blob('b', 10))       // 72 + 10 + 1 = 83 bytes\n\tqueue.Pop()                                 // space freed at the beginning\n\tqueue.Push(blob('c', 30))                   // 31 bytes used at the beginning, tail pointer is before head pointer\n\tnewestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory\n\n\t// then\n\tassertEqual(t, 200, queue.Capacity())\n\tassertEqual(t, blob('b', 10), get(queue, index))\n\tassertEqual(t, blob('d', 40), get(queue, newestIndex))\n}\n\nfunc TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(11, 0, false)\n\n\t// when\n\tqueue.Push(blob('a', 100))\n\t// then\n\tassertEqual(t, blob('a', 100), pop(queue))\n\t// 224 = (101 + 11) * 2\n\tassertEqual(t, 224, queue.Capacity())\n}\n\nfunc TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(21, 0, false)\n\n\t// when\n\tqueue.Push(make([]byte, 2))\n\tqueue.Push(make([]byte, 2))\n\tqueue.Push(make([]byte, 100))\n\n\t// then\n\tqueue.Pop()\n\tqueue.Pop()\n\tassertEqual(t, make([]byte, 100), pop(queue))\n\t// 244 = (101 + 21) * 2\n\tassertEqual(t, 244, queue.Capacity())\n}\n\nfunc TestPopWholeQueue(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(13, 0, false)\n\n\t// when\n\tqueue.Push([]byte(\"a\"))\n\tqueue.Push([]byte(\"b\"))\n\tqueue.Pop()\n\tqueue.Pop()\n\tqueue.Push([]byte(\"c\"))\n\n\t// then\n\tassertEqual(t, 13, queue.Capacity())\n\tassertEqual(t, []byte(\"c\"), pop(queue))\n}\n\nfunc TestGetEntryFromIndex(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(20, 0, false)\n\n\t// when\n\tqueue.Push([]byte(\"a\"))\n\tindex, _ := queue.Push([]byte(\"b\"))\n\tqueue.Push([]byte(\"c\"))\n\tresult, _ := queue.Get(index)\n\n\t// then\n\tassertEqual(t, []byte(\"b\"), result)\n}\n\nfunc TestGetEntryFromInvalidIndex(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(1, 0, false)\n\tqueue.Push([]byte(\"a\"))\n\n\t// when\n\tresult, err := queue.Get(0)\n\terr2 := queue.CheckGet(0)\n\n\t// then\n\tassertEqual(t, err, err2)\n\tassertEqual(t, []byte(nil), result)\n\tassertEqual(t, \"Index must be greater than zero. Invalid index.\", err.Error())\n}\n\nfunc TestGetEntryFromIndexOutOfRange(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(1, 0, false)\n\tqueue.Push([]byte(\"a\"))\n\n\t// when\n\tresult, err := queue.Get(42)\n\terr2 := queue.CheckGet(42)\n\n\t// then\n\tassertEqual(t, err, err2)\n\tassertEqual(t, []byte(nil), result)\n\tassertEqual(t, \"Index out of range\", err.Error())\n}\n\nfunc TestGetEntryFromEmptyQueue(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(13, 0, false)\n\n\t// when\n\tresult, err := queue.Get(1)\n\terr2 := queue.CheckGet(1)\n\n\t// then\n\tassertEqual(t, err, err2)\n\tassertEqual(t, []byte(nil), result)\n\tassertEqual(t, \"Empty queue\", err.Error())\n}\n\nfunc TestMaxSizeLimit(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(30, 50, false)\n\n\t// when\n\tqueue.Push(blob('a', 25))\n\tqueue.Push(blob('b', 5))\n\tcapacity := queue.Capacity()\n\t_, err := queue.Push(blob('c', 20))\n\n\t// then\n\tassertEqual(t, 50, capacity)\n\tassertEqual(t, \"Full queue. Maximum size limit reached.\", err.Error())\n\tassertEqual(t, blob('a', 25), pop(queue))\n\tassertEqual(t, blob('b', 5), pop(queue))\n}\n\nfunc TestPushEntryAfterAllocateAdditionMemory(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(9, 20, true)\n\n\t// when\n\tqueue.Push([]byte(\"aaa\"))\n\tqueue.Push([]byte(\"bb\"))\n\tqueue.Pop()\n\n\t// allocate more memory\n\tassertEqual(t, 9, queue.Capacity())\n\tqueue.Push([]byte(\"c\"))\n\tassertEqual(t, 18, queue.Capacity())\n\n\t// push after allocate\n\t_, err := queue.Push([]byte(\"d\"))\n\tnoError(t, err)\n}\n\nfunc TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) {\n\tt.Parallel()\n\n\t// given\n\tqueue := NewBytesQueue(9, 40, true)\n\n\t// when\n\tqueue.Push([]byte(\"aaa\"))\n\tqueue.Push([]byte(\"bb\"))\n\t_, err := queue.Pop()\n\tnoError(t, err)\n\n\tqueue.Push([]byte(\"c\"))\n\tqueue.Push([]byte(\"d\"))\n\tqueue.Push([]byte(\"e\"))\n\t_, err = queue.Pop()\n\tnoError(t, err)\n\t_, err = queue.Pop()\n\tnoError(t, err)\n\tqueue.Push([]byte(\"fff\"))\n\t_, err = queue.Pop()\n\tnoError(t, err)\n}\n\nfunc pop(queue *BytesQueue) []byte {\n\tentry, err := queue.Pop()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn entry\n}\n\nfunc get(queue *BytesQueue, index int) []byte {\n\tentry, err := queue.Get(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn entry\n}\n\nfunc blob(char byte, len int) []byte {\n\treturn bytes.Repeat([]byte{char}, len)\n}\n\nfunc assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) {\n\tif !objectsAreEqual(expected, actual) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfile = path.Base(file)\n\t\tt.Errorf(fmt.Sprintf(\"\\n%s:%d: Not equal: \\n\"+\n\t\t\t\"expected: %T(%#v)\\n\"+\n\t\t\t\"actual  : %T(%#v)\\n\",\n\t\t\tfile, line, expected, expected, actual, actual), msgAndArgs...)\n\t}\n}\n\nfunc noError(t *testing.T, e error) {\n\tif e != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfile = path.Base(file)\n\t\tt.Errorf(fmt.Sprintf(\"\\n%s:%d: Error is not nil: \\n\"+\n\t\t\t\"actual  : %T(%#v)\\n\", file, line, e, e))\n\t}\n}\n\nfunc objectsAreEqual(expected, actual interface{}) bool {\n\tif expected == nil || actual == nil {\n\t\treturn expected == actual\n\t}\n\n\texp, ok := expected.([]byte)\n\tif !ok {\n\t\treturn reflect.DeepEqual(expected, actual)\n\t}\n\n\tact, ok := actual.([]byte)\n\tif !ok {\n\t\treturn false\n\t}\n\tif exp == nil || act == nil {\n\t\treturn exp == nil && act == nil\n\t}\n\treturn bytes.Equal(exp, act)\n}\n"
  },
  {
    "path": "server/README.md",
    "content": "# BigCache HTTP Server\n\nThis is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs.\n\n```bash\n# cache API.\nGET         /api/v1/cache/{key}\nPUT         /api/v1/cache/{key}\nDELETE      /api/v1/cache/{key}\n\n# stats API.\nGET         /api/v1/stats\n```\n\nThe cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted.\n\n### Notes for Operators\n\n1. No SSL support, currently.\n1. No authentication, currently.\n1. Stats from the stats API are not persistent.\n1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise.\n1. There is no replication or clustering.\n\n### Command-line Interface\n\n```powershell\nPS C:\\go\\src\\github.com\\mxplusb\\bigcache\\server> .\\server.exe -h\nUsage of C:\\go\\src\\github.com\\mxplusb\\bigcache\\server\\server.exe:\n  -lifetime duration\n        Lifetime of each cache object. (default 10m0s)\n  -logfile string\n        Location of the logfile.\n  -max int\n        Maximum amount of data in the cache in MB. (default 8192)\n  -maxInWindow int\n        Used only in initial memory allocation. (default 600000)\n  -maxShardEntrySize int\n        The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500)\n  -port int\n        The port to listen on. (default 9090)\n  -shards int\n        Number of shards for the cache. (default 1024)\n  -v    Verbose logging.\n  -version\n        Print server version.\n```\n\nExample:\n\n```bash\n$ curl -v -XPUT localhost:9090/api/v1/cache/example -d \"yay!\"\n*   Trying 127.0.0.1...\n* Connected to localhost (127.0.0.1) port 9090 (#0)\n> PUT /api/v1/cache/example HTTP/1.1\n> Host: localhost:9090\n> User-Agent: curl/7.47.0\n> Accept: */*\n> Content-Length: 4\n> Content-Type: application/x-www-form-urlencoded\n>\n* upload completely sent off: 4 out of 4 bytes\n< HTTP/1.1 201 Created\n< Date: Fri, 17 Nov 2017 03:50:07 GMT\n< Content-Length: 0\n< Content-Type: text/plain; charset=utf-8\n<\n* Connection #0 to host localhost left intact\n$ \n$ curl -v -XGET localhost:9090/api/v1/cache/example\nNote: Unnecessary use of -X or --request, GET is already inferred.\n*   Trying 127.0.0.1...\n* Connected to localhost (127.0.0.1) port 9090 (#0)\n> GET /api/v1/cache/example HTTP/1.1\n> Host: localhost:9090\n> User-Agent: curl/7.47.0\n> Accept: */*\n>\n< HTTP/1.1 200 OK\n< Date: Fri, 17 Nov 2017 03:50:23 GMT\n< Content-Length: 4\n< Content-Type: text/plain; charset=utf-8\n<\n* Connection #0 to host localhost left intact\nyay!\n```\n\nThe server does log basic metrics:\n\n```bash\n$ ./server\n2017/11/16 22:49:22 cache initialised.\n2017/11/16 22:49:22 starting server on :9090\n2017/11/16 22:50:07 stored \"example\" in cache.\n2017/11/16 22:50:07 request took 277000ns.\n2017/11/16 22:50:23 request took 9000ns.\n```\n\n### Acquiring Natively\n\nThis is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build:\n\n```bash\ngo build server.go\n```\n"
  },
  {
    "path": "server/cache_handlers.go",
    "content": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc cacheIndexHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\tgetCacheHandler(w, r)\n\t\tcase http.MethodPut:\n\t\t\tputCacheHandler(w, r)\n\t\tcase http.MethodDelete:\n\t\t\tdeleteCacheHandler(w, r)\n\t\t}\n\t})\n}\n\nfunc cacheClearHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tclearCache(w, r)\n\t})\n}\n\nfunc clearCache(w http.ResponseWriter, r *http.Request) {\n\tif err := cache.Reset(); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Printf(\"internal cache error: %s\", err)\n\t}\n\tlog.Println(\"cache is successfully cleared\")\n\tw.WriteHeader(http.StatusOK)\n}\n\n// handles get requests.\nfunc getCacheHandler(w http.ResponseWriter, r *http.Request) {\n\ttarget := r.URL.Path[len(cachePath):]\n\tif target == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"can't get a key if there is no key.\"))\n\t\tlog.Print(\"empty request.\")\n\t\treturn\n\t}\n\tentry, err := cache.Get(target)\n\tif err != nil {\n\t\terrMsg := (err).Error()\n\t\tif strings.Contains(errMsg, \"not found\") {\n\t\t\tlog.Print(err)\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Write(entry)\n}\n\nfunc putCacheHandler(w http.ResponseWriter, r *http.Request) {\n\ttarget := r.URL.Path[len(cachePath):]\n\tif target == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"can't put a key if there is no key.\"))\n\t\tlog.Print(\"empty request.\")\n\t\treturn\n\t}\n\n\tentry, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := cache.Set(target, []byte(entry)); err != nil {\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlog.Printf(\"stored \\\"%s\\\" in cache.\", target)\n\tw.WriteHeader(http.StatusCreated)\n}\n\n// delete cache objects.\nfunc deleteCacheHandler(w http.ResponseWriter, r *http.Request) {\n\ttarget := r.URL.Path[len(cachePath):]\n\tif err := cache.Delete(target); err != nil {\n\t\tif strings.Contains((err).Error(), \"not found\") {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tlog.Printf(\"%s not found.\", target)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Printf(\"internal cache error: %s\", err)\n\t}\n\t// this is what the RFC says to use when calling DELETE.\n\tw.WriteHeader(http.StatusOK)\n}\n"
  },
  {
    "path": "server/middleware.go",
    "content": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\n// our base middleware implementation.\ntype service func(http.Handler) http.Handler\n\n// chain load middleware services.\nfunc serviceLoader(h http.Handler, svcs ...service) http.Handler {\n\tfor _, svc := range svcs {\n\t\th = svc(h)\n\t}\n\treturn h\n}\n\n// middleware for request length metrics.\nfunc requestMetrics(l *log.Logger) service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\th.ServeHTTP(w, r)\n\t\t\tl.Printf(\"%s request to %s took %vns.\", r.Method, r.URL.Path, time.Since(start).Nanoseconds())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "server/middleware_test.go",
    "content": "package main\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc emptyTestHandler() service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(http.StatusAccepted)\n\t\t})\n\t}\n}\n\nfunc TestServiceLoader(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"/api/v1/stats\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\trr := httptest.NewRecorder()\n\ttestHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler())\n\ttestHandlers.ServeHTTP(rr, req)\n\tif status := rr.Code; status != http.StatusAccepted {\n\t\tt.Errorf(\"handlers not loading properly. want: 202, got: %d\", rr.Code)\n\t}\n}\n\nfunc TestRequestMetrics(t *testing.T) {\n\tvar b bytes.Buffer\n\tlogger := log.New(&b, \"\", log.LstdFlags)\n\treq, err := http.NewRequest(\"GET\", \"/api/v1/cache/empty\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\trr := httptest.NewRecorder()\n\ttestHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger))\n\ttestHandlers.ServeHTTP(rr, req)\n\ttargetTestString := b.String()\n\tif len(targetTestString) == 0 {\n\t\tt.Errorf(\"we are not logging request length strings.\")\n\t}\n\tt.Log(targetTestString)\n}\n"
  },
  {
    "path": "server/server.go",
    "content": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com/allegro/bigcache/v3\"\n)\n\nconst (\n\t// base HTTP paths.\n\tapiVersion  = \"v1\"\n\tapiBasePath = \"/api/\" + apiVersion + \"/\"\n\n\t// path to cache.\n\tcachePath      = apiBasePath + \"cache/\"\n\tstatsPath      = apiBasePath + \"stats\"\n\tcacheClearPath = apiBasePath + \"cache/clear\"\n\t// server version.\n\tversion = \"1.0.0\"\n)\n\nvar (\n\tport    int\n\tlogfile string\n\tver     bool\n\n\t// cache-specific settings.\n\tcache  *bigcache.BigCache\n\tconfig = bigcache.Config{}\n)\n\nfunc init() {\n\tflag.BoolVar(&config.Verbose, \"v\", false, \"Verbose logging.\")\n\tflag.IntVar(&config.Shards, \"shards\", 1024, \"Number of shards for the cache.\")\n\tflag.IntVar(&config.MaxEntriesInWindow, \"maxInWindow\", 1000*10*60, \"Used only in initial memory allocation.\")\n\tflag.DurationVar(&config.LifeWindow, \"lifetime\", 100000*100000*60, \"Lifetime of each cache object.\")\n\tflag.IntVar(&config.HardMaxCacheSize, \"max\", 8192, \"Maximum amount of data in the cache in MB.\")\n\tflag.IntVar(&config.MaxEntrySize, \"maxShardEntrySize\", 500, \"The maximum size of each object stored in a shard. Used only in initial memory allocation.\")\n\tflag.IntVar(&port, \"port\", 9090, \"The port to listen on.\")\n\tflag.StringVar(&logfile, \"logfile\", \"\", \"Location of the logfile.\")\n\tflag.BoolVar(&ver, \"version\", false, \"Print server version.\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif ver {\n\t\tfmt.Printf(\"BigCache HTTP Server v%s\", version)\n\t\tos.Exit(0)\n\t}\n\n\tvar logger *log.Logger\n\n\tif logfile == \"\" {\n\t\tlogger = log.New(os.Stdout, \"\", log.LstdFlags)\n\t} else {\n\t\tf, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlogger = log.New(f, \"\", log.LstdFlags)\n\t}\n\n\tvar err error\n\tcache, err = bigcache.New(context.Background(), config)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tlogger.Print(\"cache initialised.\")\n\n\t// let the middleware log.\n\thttp.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger)))\n\thttp.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger)))\n\thttp.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger)))\n\n\tlogger.Printf(\"starting server on :%d\", port)\n\n\tstrPort := \":\" + strconv.Itoa(port)\n\tlog.Fatal(\"ListenAndServe: \", http.ListenAndServe(strPort, nil))\n}\n"
  },
  {
    "path": "server/server_test.go",
    "content": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/allegro/bigcache/v3\"\n)\n\nconst (\n\ttestBaseString = \"http://bigcache.org\"\n)\n\nfunc testCacheSetup() {\n\tcache, _ = bigcache.New(context.Background(), bigcache.Config{\n\t\tShards:             1024,\n\t\tLifeWindow:         10 * time.Minute,\n\t\tMaxEntriesInWindow: 1000 * 10 * 60,\n\t\tMaxEntrySize:       500,\n\t\tVerbose:            true,\n\t\tHardMaxCacheSize:   8192,\n\t\tOnRemove:           nil,\n\t})\n}\n\nfunc TestMain(m *testing.M) {\n\ttestCacheSetup()\n\tm.Run()\n}\n\nfunc TestGetWithNoKey(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/cache/\", nil)\n\trr := httptest.NewRecorder()\n\n\tgetCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 400 {\n\t\tt.Errorf(\"want: 400; got: %d\", resp.StatusCode)\n\t}\n}\n\nfunc TestGetWithMissingKey(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/cache/doesNotExist\", nil)\n\trr := httptest.NewRecorder()\n\n\tgetCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 404 {\n\t\tt.Errorf(\"want: 404; got: %d\", resp.StatusCode)\n\t}\n}\n\nfunc TestGetKey(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/cache/getKey\", nil)\n\trr := httptest.NewRecorder()\n\n\t// set something.\n\tcache.Set(\"getKey\", []byte(\"123\"))\n\n\tgetCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Errorf(\"cannot deserialise test response: %s\", err)\n\t}\n\n\tif string(body) != \"123\" {\n\t\tt.Errorf(\"want: 123; got: %s.\\n\\tcan't get existing key getKey.\", string(body))\n\t}\n}\n\nfunc TestPutKey(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/putKey\", bytes.NewBuffer([]byte(\"123\")))\n\trr := httptest.NewRecorder()\n\n\tputCacheHandler(rr, req)\n\n\ttestPutKeyResult, err := cache.Get(\"putKey\")\n\tif err != nil {\n\t\tt.Errorf(\"error returning cache entry: %s\", err)\n\t}\n\n\tif string(testPutKeyResult) != \"123\" {\n\t\tt.Errorf(\"want: 123; got: %s.\\n\\tcan't get PUT key putKey.\", string(testPutKeyResult))\n\t}\n}\n\nfunc TestPutEmptyKey(t *testing.T) {\n\tt.Parallel()\n\n\treq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/\", bytes.NewBuffer([]byte(\"123\")))\n\trr := httptest.NewRecorder()\n\n\tputCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 400 {\n\t\tt.Errorf(\"want: 400; got: %d.\\n\\tempty key insertion should return with 400\", resp.StatusCode)\n\t}\n}\n\nfunc TestDeleteEmptyKey(t *testing.T) {\n\tt.Parallel()\n\n\treq := httptest.NewRequest(\"DELETE\", testBaseString+\"/api/v1/cache/\", bytes.NewBuffer([]byte(\"123\")))\n\trr := httptest.NewRecorder()\n\n\tdeleteCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 404 {\n\t\tt.Errorf(\"want: 404; got: %d.\\n\\tapparently we're trying to delete empty keys.\", resp.StatusCode)\n\t}\n}\n\nfunc TestDeleteInvalidKey(t *testing.T) {\n\tt.Parallel()\n\n\treq := httptest.NewRequest(\"DELETE\", testBaseString+\"/api/v1/cache/invalidDeleteKey\", bytes.NewBuffer([]byte(\"123\")))\n\trr := httptest.NewRecorder()\n\n\tdeleteCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 404 {\n\t\tt.Errorf(\"want: 404; got: %d.\\n\\tapparently we're trying to delete invalid keys.\", resp.StatusCode)\n\t}\n}\n\nfunc TestDeleteKey(t *testing.T) {\n\tt.Parallel()\n\n\treq := httptest.NewRequest(\"DELETE\", testBaseString+\"/api/v1/cache/testDeleteKey\", bytes.NewBuffer([]byte(\"123\")))\n\trr := httptest.NewRecorder()\n\n\tif err := cache.Set(\"testDeleteKey\", []byte(\"123\")); err != nil {\n\t\tt.Errorf(\"can't set key for testing. %s\", err)\n\t}\n\n\tdeleteCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"want: 200; got: %d.\\n\\tcan't delete keys.\", resp.StatusCode)\n\t}\n}\n\nfunc TestClearCache(t *testing.T) {\n\tt.Parallel()\n\n\tputRequest := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/putKey\", bytes.NewBuffer([]byte(\"123\")))\n\tputResponseRecorder := httptest.NewRecorder()\n\n\tputCacheHandler(putResponseRecorder, putRequest)\n\n\trequestClear := httptest.NewRequest(\"DELETE\", testBaseString+\"/api/v1/cache/clear\", nil)\n\trr := httptest.NewRecorder()\n\n\tif err := cache.Set(\"testDeleteKey\", []byte(\"123\")); err != nil {\n\t\tt.Errorf(\"can't set key for testing. %s\", err)\n\t}\n\n\tclearCache(rr, requestClear)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"want: 200; got: %d.\\n\\tcan't delete keys.\", resp.StatusCode)\n\t}\n}\nfunc TestGetStats(t *testing.T) {\n\tt.Parallel()\n\tvar testStats bigcache.Stats\n\n\treq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/stats\", nil)\n\trr := httptest.NewRecorder()\n\n\t// manually enter a key so there are some stats. get it so there's at least 1 hit.\n\tif err := cache.Set(\"incrementStats\", []byte(\"123\")); err != nil {\n\t\tt.Errorf(\"error setting cache value. error %s\", err)\n\t}\n\t// it's okay if this fails, since we'll catch it downstream.\n\tif _, err := cache.Get(\"incrementStats\"); err != nil {\n\t\tt.Errorf(\"can't find incrementStats. error: %s\", err)\n\t}\n\n\tgetCacheStatsHandler(rr, req)\n\tresp := rr.Result()\n\n\tif err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil {\n\t\tt.Errorf(\"error decoding cache stats. error: %s\", err)\n\t}\n\n\tif testStats.Hits == 0 {\n\t\tt.Errorf(\"want: > 0; got: 0.\\n\\thandler not properly returning stats info.\")\n\t}\n}\n\nfunc TestGetStatsIndex(t *testing.T) {\n\tt.Parallel()\n\tvar testStats bigcache.Stats\n\n\tgetreq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/stats\", nil)\n\tputreq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/stats\", nil)\n\trr := httptest.NewRecorder()\n\n\t// manually enter a key so there are some stats. get it so there's at least 1 hit.\n\tif err := cache.Set(\"incrementStats\", []byte(\"123\")); err != nil {\n\t\tt.Errorf(\"error setting cache value. error %s\", err)\n\t}\n\t// it's okay if this fails, since we'll catch it downstream.\n\tif _, err := cache.Get(\"incrementStats\"); err != nil {\n\t\tt.Errorf(\"can't find incrementStats. error: %s\", err)\n\t}\n\n\ttestHandlers := statsIndexHandler()\n\ttestHandlers.ServeHTTP(rr, getreq)\n\tresp := rr.Result()\n\n\tif err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil {\n\t\tt.Errorf(\"error decoding cache stats. error: %s\", err)\n\t}\n\n\tif testStats.Hits == 0 {\n\t\tt.Errorf(\"want: > 0; got: 0.\\n\\thandler not properly returning stats info.\")\n\t}\n\n\ttestHandlers = statsIndexHandler()\n\ttestHandlers.ServeHTTP(rr, putreq)\n\tresp = rr.Result()\n\t_, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Errorf(\"cannot deserialise test response: %s\", err)\n\t}\n}\n\nfunc TestCacheIndexHandler(t *testing.T) {\n\tgetreq := httptest.NewRequest(\"GET\", testBaseString+\"/api/v1/cache/testkey\", nil)\n\tputreq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/testkey\", bytes.NewBuffer([]byte(\"123\")))\n\tdelreq := httptest.NewRequest(\"DELETE\", testBaseString+\"/api/v1/cache/testkey\", bytes.NewBuffer([]byte(\"123\")))\n\n\tgetrr := httptest.NewRecorder()\n\tputrr := httptest.NewRecorder()\n\tdelrr := httptest.NewRecorder()\n\ttestHandlers := cacheIndexHandler()\n\n\ttestHandlers.ServeHTTP(putrr, putreq)\n\tresp := putrr.Result()\n\tif resp.StatusCode != 201 {\n\t\tt.Errorf(\"want: 201; got: %d.\\n\\tcan't put keys.\", resp.StatusCode)\n\t}\n\ttestHandlers.ServeHTTP(getrr, getreq)\n\tresp = getrr.Result()\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"want: 200; got: %d.\\n\\tcan't get keys.\", resp.StatusCode)\n\t}\n\ttestHandlers.ServeHTTP(delrr, delreq)\n\tresp = delrr.Result()\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"want: 200; got: %d.\\n\\tcan't delete keys.\", resp.StatusCode)\n\t}\n}\n\nfunc TestInvalidPutWhenExceedShardCap(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/putKey\", bytes.NewBuffer(bytes.Repeat([]byte(\"a\"), 8*1024*1024)))\n\trr := httptest.NewRecorder()\n\n\tputCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 500 {\n\t\tt.Errorf(\"want: 500; got: %d\", resp.StatusCode)\n\t}\n}\n\nfunc TestInvalidPutWhenReading(t *testing.T) {\n\tt.Parallel()\n\treq := httptest.NewRequest(\"PUT\", testBaseString+\"/api/v1/cache/putKey\", errReader(0))\n\trr := httptest.NewRecorder()\n\n\tputCacheHandler(rr, req)\n\tresp := rr.Result()\n\n\tif resp.StatusCode != 500 {\n\t\tt.Errorf(\"want: 500; got: %d\", resp.StatusCode)\n\t}\n}\n\ntype errReader int\n\nfunc (errReader) Read([]byte) (int, error) {\n\treturn 0, errors.New(\"test read error\")\n}\n"
  },
  {
    "path": "server/stats_handler.go",
    "content": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n)\n\n// index for stats handle\nfunc statsIndexHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\tgetCacheStatsHandler(w, r)\n\t\tdefault:\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t}\n\t})\n}\n\n// returns the cache's statistics.\nfunc getCacheStatsHandler(w http.ResponseWriter, r *http.Request) {\n\ttarget, err := json.Marshal(cache.Stats())\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Printf(\"cannot marshal cache stats. error: %s\", err)\n\t\treturn\n\t}\n\t// since we're sending a struct, make it easy for consumers to interface.\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Write(target)\n}\n"
  },
  {
    "path": "shard.go",
    "content": "package bigcache\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/allegro/bigcache/v3/queue\"\n)\n\ntype onRemoveCallback func(wrappedEntry []byte, reason RemoveReason)\n\n// Metadata contains information of a specific entry\ntype Metadata struct {\n\tRequestCount uint32\n}\n\ntype cacheShard struct {\n\thashmap     map[uint64]uint64\n\tentries     queue.BytesQueue\n\tlock        sync.RWMutex\n\tentryBuffer []byte\n\tonRemove    onRemoveCallback\n\n\tisVerbose    bool\n\tstatsEnabled bool\n\tlogger       Logger\n\tclock        clock\n\tlifeWindow   uint64\n\n\thashmapStats map[uint64]uint32\n\tstats        Stats\n\tcleanEnabled bool\n}\n\nfunc (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) {\n\tcurrentTime := uint64(s.clock.Epoch())\n\ts.lock.RLock()\n\twrappedEntry, err := s.getWrappedEntry(hashedKey)\n\tif err != nil {\n\t\ts.lock.RUnlock()\n\t\treturn nil, resp, err\n\t}\n\tif entryKey := readKeyFromEntry(wrappedEntry); key != entryKey {\n\t\ts.lock.RUnlock()\n\t\ts.collision()\n\t\tif s.isVerbose {\n\t\t\ts.logger.Printf(\"Collision detected. Both %q and %q have the same hash %x\", key, entryKey, hashedKey)\n\t\t}\n\t\treturn nil, resp, ErrEntryNotFound\n\t}\n\n\tentry = readEntry(wrappedEntry)\n\tif s.isExpired(wrappedEntry, currentTime) {\n\t\tresp.EntryStatus = Expired\n\t}\n\ts.lock.RUnlock()\n\ts.hit(hashedKey)\n\treturn entry, resp, nil\n}\n\nfunc (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) {\n\ts.lock.RLock()\n\twrappedEntry, err := s.getWrappedEntry(hashedKey)\n\tif err != nil {\n\t\ts.lock.RUnlock()\n\t\treturn nil, err\n\t}\n\tif entryKey := readKeyFromEntry(wrappedEntry); key != entryKey {\n\t\ts.lock.RUnlock()\n\t\ts.collision()\n\t\tif s.isVerbose {\n\t\t\ts.logger.Printf(\"Collision detected. Both %q and %q have the same hash %x\", key, entryKey, hashedKey)\n\t\t}\n\t\treturn nil, ErrEntryNotFound\n\t}\n\tentry := readEntry(wrappedEntry)\n\ts.lock.RUnlock()\n\ts.hit(hashedKey)\n\n\treturn entry, nil\n}\n\nfunc (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) {\n\titemIndex := s.hashmap[hashedKey]\n\n\tif itemIndex == 0 {\n\t\ts.miss()\n\t\treturn nil, ErrEntryNotFound\n\t}\n\n\twrappedEntry, err := s.entries.Get(int(itemIndex))\n\tif err != nil {\n\t\ts.miss()\n\t\treturn nil, err\n\t}\n\n\treturn wrappedEntry, err\n}\n\nfunc (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) {\n\twrappedEntry, err := s.getWrappedEntry(hashedKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !compareKeyFromEntry(wrappedEntry, key) {\n\t\ts.collision()\n\t\tif s.isVerbose {\n\t\t\ts.logger.Printf(\"Collision detected. Both %q and %q have the same hash %x\", key, readKeyFromEntry(wrappedEntry), hashedKey)\n\t\t}\n\n\t\treturn nil, ErrEntryNotFound\n\t}\n\ts.hitWithoutLock(hashedKey)\n\n\treturn wrappedEntry, nil\n}\n\nfunc (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error {\n\tcurrentTimestamp := uint64(s.clock.Epoch())\n\n\ts.lock.Lock()\n\n\tif previousIndex := s.hashmap[hashedKey]; previousIndex != 0 {\n\t\tif previousEntry, err := s.entries.Get(int(previousIndex)); err == nil {\n\t\t\tresetHashFromEntry(previousEntry)\n\t\t\t//remove hashkey\n\t\t\tdelete(s.hashmap, hashedKey)\n\t\t}\n\t}\n\n\tif !s.cleanEnabled {\n\t\tif oldestEntry, err := s.entries.Peek(); err == nil {\n\t\t\ts.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)\n\t\t}\n\t}\n\n\tw := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer)\n\n\tfor {\n\t\tif index, err := s.entries.Push(w); err == nil {\n\t\t\ts.hashmap[hashedKey] = uint64(index)\n\t\t\ts.lock.Unlock()\n\t\t\treturn nil\n\t\t}\n\t\tif s.removeOldestEntry(NoSpace) != nil {\n\t\t\ts.lock.Unlock()\n\t\t\treturn errors.New(\"entry is bigger than max shard size\")\n\t\t}\n\t}\n}\n\nfunc (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error {\n\tcurrentTimestamp := uint64(s.clock.Epoch())\n\n\tif !s.cleanEnabled {\n\t\tif oldestEntry, err := s.entries.Peek(); err == nil {\n\t\t\ts.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)\n\t\t}\n\t}\n\n\tw := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer)\n\n\tfor {\n\t\tif index, err := s.entries.Push(w); err == nil {\n\t\t\ts.hashmap[hashedKey] = uint64(index)\n\t\t\treturn nil\n\t\t}\n\t\tif s.removeOldestEntry(NoSpace) != nil {\n\t\t\treturn errors.New(\"entry is bigger than max shard size\")\n\t\t}\n\t}\n}\n\nfunc (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error {\n\tif previousIndex := s.hashmap[hashedKey]; previousIndex != 0 {\n\t\tif previousEntry, err := s.entries.Get(int(previousIndex)); err == nil {\n\t\t\tresetHashFromEntry(previousEntry)\n\t\t}\n\t}\n\n\tif !s.cleanEnabled {\n\t\tif oldestEntry, err := s.entries.Peek(); err == nil {\n\t\t\ts.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)\n\t\t}\n\t}\n\n\tfor {\n\t\tif index, err := s.entries.Push(w); err == nil {\n\t\t\ts.hashmap[hashedKey] = uint64(index)\n\t\t\treturn nil\n\t\t}\n\t\tif s.removeOldestEntry(NoSpace) != nil {\n\t\t\treturn errors.New(\"entry is bigger than max shard size\")\n\t\t}\n\t}\n}\n\nfunc (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error {\n\ts.lock.Lock()\n\twrappedEntry, err := s.getValidWrapEntry(key, hashedKey)\n\n\tif err == ErrEntryNotFound {\n\t\terr = s.addNewWithoutLock(key, hashedKey, entry)\n\t\ts.lock.Unlock()\n\t\treturn err\n\t}\n\tif err != nil {\n\t\ts.lock.Unlock()\n\t\treturn err\n\t}\n\n\tcurrentTimestamp := uint64(s.clock.Epoch())\n\n\tw := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer)\n\n\terr = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey)\n\ts.lock.Unlock()\n\n\treturn err\n}\n\nfunc (s *cacheShard) del(hashedKey uint64) error {\n\t// Optimistic pre-check using only readlock\n\ts.lock.RLock()\n\t{\n\t\titemIndex := s.hashmap[hashedKey]\n\n\t\tif itemIndex == 0 {\n\t\t\ts.lock.RUnlock()\n\t\t\ts.delmiss()\n\t\t\treturn ErrEntryNotFound\n\t\t}\n\n\t\tif err := s.entries.CheckGet(int(itemIndex)); err != nil {\n\t\t\ts.lock.RUnlock()\n\t\t\ts.delmiss()\n\t\t\treturn err\n\t\t}\n\t}\n\ts.lock.RUnlock()\n\n\ts.lock.Lock()\n\t{\n\t\t// After obtaining the writelock, we need to read the same again,\n\t\t// since the data delivered earlier may be stale now\n\t\titemIndex := s.hashmap[hashedKey]\n\n\t\tif itemIndex == 0 {\n\t\t\ts.lock.Unlock()\n\t\t\ts.delmiss()\n\t\t\treturn ErrEntryNotFound\n\t\t}\n\n\t\twrappedEntry, err := s.entries.Get(int(itemIndex))\n\t\tif err != nil {\n\t\t\ts.lock.Unlock()\n\t\t\ts.delmiss()\n\t\t\treturn err\n\t\t}\n\n\t\tdelete(s.hashmap, hashedKey)\n\t\ts.onRemove(wrappedEntry, Deleted)\n\t\tif s.statsEnabled {\n\t\t\tdelete(s.hashmapStats, hashedKey)\n\t\t}\n\t\tresetHashFromEntry(wrappedEntry)\n\t}\n\ts.lock.Unlock()\n\n\ts.delhit()\n\treturn nil\n}\n\nfunc (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {\n\tif s.isExpired(oldestEntry, currentTimestamp) {\n\t\tevict(Expired)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool {\n\toldestTimestamp := readTimestampFromEntry(oldestEntry)\n\tif currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits;\n\t\treturn false\n\t}\n\treturn currentTimestamp-oldestTimestamp >= s.lifeWindow\n}\n\nfunc (s *cacheShard) cleanUp(currentTimestamp uint64) {\n\ts.lock.Lock()\n\tfor {\n\t\tif oldestEntry, err := s.entries.Peek(); err != nil {\n\t\t\tbreak\n\t\t} else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted {\n\t\t\tbreak\n\t\t}\n\t}\n\ts.lock.Unlock()\n}\n\nfunc (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) {\n\ts.lock.RLock()\n\n\tentry, err := s.getWrappedEntry(hashedKey)\n\t// copy entry\n\tnewEntry := make([]byte, len(entry))\n\tcopy(newEntry, entry)\n\n\ts.lock.RUnlock()\n\n\treturn newEntry, err\n}\n\nfunc (s *cacheShard) copyHashedKeys() (keys []uint64, next int) {\n\ts.lock.RLock()\n\tkeys = make([]uint64, len(s.hashmap))\n\n\tfor key := range s.hashmap {\n\t\tkeys[next] = key\n\t\tnext++\n\t}\n\n\ts.lock.RUnlock()\n\treturn keys, next\n}\n\nfunc (s *cacheShard) removeOldestEntry(reason RemoveReason) error {\n\toldest, err := s.entries.Pop()\n\tif err == nil {\n\t\thash := readHashFromEntry(oldest)\n\t\tif hash == 0 {\n\t\t\t// entry has been explicitly deleted with resetHashFromEntry, ignore\n\t\t\treturn nil\n\t\t}\n\t\tdelete(s.hashmap, hash)\n\t\ts.onRemove(oldest, reason)\n\t\tif s.statsEnabled {\n\t\t\tdelete(s.hashmapStats, hash)\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}\n\nfunc (s *cacheShard) reset(config Config) {\n\ts.lock.Lock()\n\ts.hashmap = make(map[uint64]uint64, config.initialShardSize())\n\ts.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes)\n\ts.entries.Reset()\n\ts.lock.Unlock()\n}\n\nfunc (s *cacheShard) resetStats() {\n\ts.lock.Lock()\n\ts.stats = Stats{}\n\ts.lock.Unlock()\n}\n\nfunc (s *cacheShard) len() int {\n\ts.lock.RLock()\n\tres := len(s.hashmap)\n\ts.lock.RUnlock()\n\treturn res\n}\n\nfunc (s *cacheShard) capacity() int {\n\ts.lock.RLock()\n\tres := s.entries.Capacity()\n\ts.lock.RUnlock()\n\treturn res\n}\n\nfunc (s *cacheShard) getStats() Stats {\n\tvar stats = Stats{\n\t\tHits:       atomic.LoadInt64(&s.stats.Hits),\n\t\tMisses:     atomic.LoadInt64(&s.stats.Misses),\n\t\tDelHits:    atomic.LoadInt64(&s.stats.DelHits),\n\t\tDelMisses:  atomic.LoadInt64(&s.stats.DelMisses),\n\t\tCollisions: atomic.LoadInt64(&s.stats.Collisions),\n\t}\n\treturn stats\n}\n\nfunc (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata {\n\ts.lock.RLock()\n\tc := s.hashmapStats[key]\n\ts.lock.RUnlock()\n\treturn Metadata{\n\t\tRequestCount: c,\n\t}\n}\n\nfunc (s *cacheShard) getKeyMetadata(key uint64) Metadata {\n\treturn Metadata{\n\t\tRequestCount: s.hashmapStats[key],\n\t}\n}\n\nfunc (s *cacheShard) hit(key uint64) {\n\tatomic.AddInt64(&s.stats.Hits, 1)\n\tif s.statsEnabled {\n\t\ts.lock.Lock()\n\t\ts.hashmapStats[key]++\n\t\ts.lock.Unlock()\n\t}\n}\n\nfunc (s *cacheShard) hitWithoutLock(key uint64) {\n\tatomic.AddInt64(&s.stats.Hits, 1)\n\tif s.statsEnabled {\n\t\ts.hashmapStats[key]++\n\t}\n}\n\nfunc (s *cacheShard) miss() {\n\tatomic.AddInt64(&s.stats.Misses, 1)\n}\n\nfunc (s *cacheShard) delhit() {\n\tatomic.AddInt64(&s.stats.DelHits, 1)\n}\n\nfunc (s *cacheShard) delmiss() {\n\tatomic.AddInt64(&s.stats.DelMisses, 1)\n}\n\nfunc (s *cacheShard) collision() {\n\tatomic.AddInt64(&s.stats.Collisions, 1)\n}\n\nfunc initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard {\n\tbytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize\n\tmaximumShardSizeInBytes := config.maximumShardSizeInBytes()\n\tif maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes {\n\t\tbytesQueueInitialCapacity = maximumShardSizeInBytes\n\t}\n\tvar hashmapStatsCapacity int\n\tif config.StatsEnabled {\n\t\thashmapStatsCapacity = config.initialShardSize()\n\t}\n\treturn &cacheShard{\n\t\thashmap:      make(map[uint64]uint64, config.initialShardSize()),\n\t\thashmapStats: make(map[uint64]uint32, hashmapStatsCapacity),\n\t\tentries:      *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose),\n\t\tentryBuffer:  make([]byte, config.MaxEntrySize+headersSizeInBytes),\n\t\tonRemove:     callback,\n\n\t\tisVerbose:    config.Verbose,\n\t\tlogger:       newLogger(config.Logger),\n\t\tclock:        clock,\n\t\tlifeWindow:   uint64(config.LifeWindow.Seconds()),\n\t\tstatsEnabled: config.StatsEnabled,\n\t\tcleanEnabled: config.CleanWindow > 0,\n\t}\n}\n"
  },
  {
    "path": "stats.go",
    "content": "package bigcache\n\n// Stats stores cache statistics\ntype Stats struct {\n\t// Hits is a number of successfully found keys\n\tHits int64 `json:\"hits\"`\n\t// Misses is a number of not found keys\n\tMisses int64 `json:\"misses\"`\n\t// DelHits is a number of successfully deleted keys\n\tDelHits int64 `json:\"delete_hits\"`\n\t// DelMisses is a number of not deleted keys\n\tDelMisses int64 `json:\"delete_misses\"`\n\t// Collisions is a number of happened key-collisions\n\tCollisions int64 `json:\"collisions\"`\n}\n"
  },
  {
    "path": "utils.go",
    "content": "package bigcache\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc convertMBToBytes(value int) int {\n\treturn value * 1024 * 1024\n}\n\nfunc isPowerOfTwo(number int) bool {\n\treturn (number != 0) && (number&(number-1)) == 0\n}\n"
  }
]