Full Code of allegro/bigcache for AI

main 532eb6410aef cached
45 files
135.9 KB
39.4k tokens
286 symbols
1 requests
Download .txt
Repository: allegro/bigcache
Branch: main
Commit: 532eb6410aef
Files: 45
Total size: 135.9 KB

Directory structure:
gitextract_z3iltele/

├── .codecov.yml
├── .github/
│   ├── CODEOWNERS
│   ├── ISSUE_TEMPLATE/
│   │   └── issue_template.md
│   ├── dependabot.yml
│   ├── release-drafter.yml
│   └── workflows/
│       ├── build.yml
│       └── release-management.yml
├── .gitignore
├── .golangci.yaml
├── LICENSE
├── README.md
├── assert_test.go
├── bigcache.go
├── bigcache_bench_test.go
├── bigcache_test.go
├── bytes.go
├── bytes_appengine.go
├── clock.go
├── config.go
├── encoding.go
├── encoding_test.go
├── entry_not_found_error.go
├── examples_test.go
├── fnv.go
├── fnv_bench_test.go
├── fnv_test.go
├── go.mod
├── go.sum
├── hash.go
├── hash_test.go
├── iterator.go
├── iterator_test.go
├── logger.go
├── queue/
│   ├── bytes_queue.go
│   └── bytes_queue_test.go
├── server/
│   ├── README.md
│   ├── cache_handlers.go
│   ├── middleware.go
│   ├── middleware_test.go
│   ├── server.go
│   ├── server_test.go
│   └── stats_handler.go
├── shard.go
├── stats.go
└── utils.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .codecov.yml
================================================
---
codecov:
  require_ci_to_pass: true
comment:
  behavior: default
  layout: reach, diff, flags, files, footer
  require_base: false
  require_changes: false
  require_head: true
coverage:
  precision: 2
  range:
    - 70
    - 100
  round: down
  status:
    changes: false
    patch: true
    project: true
parsers:
  gcov:
    branch_detection:
      conditional: true
      loop: true
      macro: false
      method: false
  javascript:
    enable_partials: false


================================================
FILE: .github/CODEOWNERS
================================================
* @janisz @cristaloleg


================================================
FILE: .github/ISSUE_TEMPLATE/issue_template.md
================================================
---
name: Bug Report
about: Report a bug about BigCache
labels: bug
---

**What is the issue you are having?**



**What is BigCache doing that it shouldn't?**



**Minimal, Complete, and Verifiable Example**

When 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...

* ...Minimal – Use as little code as possible that still produces the same problem
* ...Complete – Provide all parts needed to reproduce the problem
* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem

For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve).

**Environment:**
- Version (git sha or release):
- OS (e.g. from `/etc/os-release` or winver.exe):
- go version: 


================================================
FILE: .github/dependabot.yml
================================================
version: 2

updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    labels:
      - "enhancement"
  - package-ecosystem: "gomod"
    directory: "/"
    schedule:
      interval: "weekly"
    labels:
      - "enhancement"


================================================
FILE: .github/release-drafter.yml
================================================
name-template: "v$NEXT_PATCH_VERSION 🌈"
tag-template: "v$NEXT_PATCH_VERSION"
categories:
  - title: "🚀 Features"
    labels:
      - "feature"
      - "enhancement"
  - title: "🐛 Bug Fixes"
    labels:
      - "fix"
      - "bugfix"
      - "bug"
  - title: "🧰 Maintenance"
    label: "chore"
change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
template: |
  ## Changes

  $CHANGES


================================================
FILE: .github/workflows/build.yml
================================================
name: build
on: [push, pull_request]
env:
  GO111MODULE: on
  CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    strategy:
      fail-fast: true
      max-parallel: 2
      matrix:
        go: ["stable", "oldstable"]

    steps:
      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version: ${{matrix.go}}
        id: go

      - name: Check out code into the Go module directory
        uses: actions/checkout@v6

      - name: Lint code
        uses: golangci/golangci-lint-action@e7fa5ac41e1cf5b7d48e45e42232ce7ada589601
        with:
          only-new-issues: true

      - name: Test
        run: |
          go test -race -count=1 -coverprofile=queue.coverprofile ./queue
          go test -race -count=1 -coverprofile=server.coverprofile  ./server
          go test -race -count=1 -coverprofile=main.coverprofile

      - name: Upload coverage to codecov
        run: |
          go install github.com/modocache/gover@v0.0.0-20171022184752-b58185e213c5
          echo "" > coverage.txt
          gover
          cat gover.coverprofile >> coverage.txt
          bash <(curl -s https://codecov.io/bash)

      - name: Build
        run: go build -v .


================================================
FILE: .github/workflows/release-management.yml
================================================
name: Release Management

on:
  push:
    # branches to consider in the event; optional, defaults to all
    branches:
      - main

jobs:
  update_draft_release:
    runs-on: ubuntu-latest
    steps:
      # Drafts your next Release notes as Pull Requests are merged into "main"
      - uses: toolmantim/release-drafter@v6.0.0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .gitignore
================================================
.idea
.DS_Store
/server/server.exe
/server/server
/server/server_dar*
/server/server_fre*
/server/server_win*
/server/server_net*
/server/server_ope*
/server/server_lin*
CHANGELOG.md


================================================
FILE: .golangci.yaml
================================================
version: "2"
linters:
  disable:
    - errcheck
  settings:
    staticcheck:
      checks:
        - -SA1019
        - all
  exclusions:
    generated: lax
    presets:
      - comments
      - common-false-positives
      - legacy
      - std-error-handling
    paths:
      - third_party$
      - builtin$
      - examples$
formatters:
  exclusions:
    generated: lax
    paths:
      - third_party$
      - builtin$
      - examples$


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# 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)

Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance.
BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place,
therefore entries (de)serialization in front of the cache will be needed in most use cases.

Requires Go 1.12 or newer.

## Usage

### Simple initialization

```go
import (
	"context"
	"fmt"
	"time"
	"github.com/allegro/bigcache/v3"
)

cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute))

cache.Set("my-unique-key", []byte("value"))

entry, _ := cache.Get("my-unique-key")
fmt.Println(string(entry))
```

### Custom initialization

When cache load can be predicted in advance then it is better to use custom initialization because additional memory
allocation can be avoided in that way.

```go
import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/allegro/bigcache/v3"
)

config := bigcache.Config {
		// number of shards (must be a power of 2)
		Shards: 1024,

		// time after which entry can be evicted
		LifeWindow: 10 * time.Minute,

		// Interval between removing expired entries (clean up).
		// If set to <= 0 then no action is performed.
		// Setting to < 1 second is counterproductive — bigcache has a one second resolution.
		CleanWindow: 5 * time.Minute,

		// rps * lifeWindow, used only in initial memory allocation
		MaxEntriesInWindow: 1000 * 10 * 60,

		// max entry size in bytes, used only in initial memory allocation
		MaxEntrySize: 500,

		// prints information about additional memory allocation
		Verbose: true,

		// cache will not allocate more memory than this limit, value in MB
		// if value is reached then the oldest entries can be overridden for the new ones
		// 0 value means no size limit
		HardMaxCacheSize: 8192,

		// callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A bitmask representing the reason will be returned.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		OnRemove: nil,

		// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A constant representing the reason will be passed through.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		// Ignored if OnRemove is specified.
		OnRemoveWithReason: nil,
	}

cache, initErr := bigcache.New(context.Background(), config)
if initErr != nil {
	log.Fatal(initErr)
}

cache.Set("my-unique-key", []byte("value"))

if entry, err := cache.Get("my-unique-key"); err == nil {
	fmt.Println(string(entry))
}
```

### `LifeWindow` & `CleanWindow`

1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted.

2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life.

## [Benchmarks](https://github.com/allegro/bigcache-bench)

Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map.
Benchmark tests were made using an
i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic).

Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench)

### Writes and reads

```bash
go version
go version go1.13 linux/amd64

go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m
goos: linux
goarch: amd64
pkg: github.com/allegro/bigcache/v3/caches_bench
BenchmarkMapSet-8                     	12999889	       376 ns/op	     199 B/op	       3 allocs/op
BenchmarkConcurrentMapSet-8           	 4355726	      1275 ns/op	     337 B/op	       8 allocs/op
BenchmarkFreeCacheSet-8               	11068976	       703 ns/op	     328 B/op	       2 allocs/op
BenchmarkBigCacheSet-8                	10183717	       478 ns/op	     304 B/op	       2 allocs/op
BenchmarkMapGet-8                     	16536015	       324 ns/op	      23 B/op	       1 allocs/op
BenchmarkConcurrentMapGet-8           	13165708	       401 ns/op	      24 B/op	       2 allocs/op
BenchmarkFreeCacheGet-8               	10137682	       690 ns/op	     136 B/op	       2 allocs/op
BenchmarkBigCacheGet-8                	11423854	       450 ns/op	     152 B/op	       4 allocs/op
BenchmarkBigCacheSetParallel-8        	34233472	       148 ns/op	     317 B/op	       3 allocs/op
BenchmarkFreeCacheSetParallel-8       	34222654	       268 ns/op	     350 B/op	       3 allocs/op
BenchmarkConcurrentMapSetParallel-8   	19635688	       240 ns/op	     200 B/op	       6 allocs/op
BenchmarkBigCacheGetParallel-8        	60547064	        86.1 ns/op	     152 B/op	       4 allocs/op
BenchmarkFreeCacheGetParallel-8       	50701280	       147 ns/op	     136 B/op	       3 allocs/op
BenchmarkConcurrentMapGetParallel-8   	27353288	       175 ns/op	      24 B/op	       2 allocs/op
PASS
ok  	github.com/allegro/bigcache/v3/caches_bench	256.257s
```

Writes and reads in bigcache are faster than in freecache.
Writes to map are the slowest.

### GC pause time

```bash
go version
go version go1.13 linux/amd64

go run caches_gc_overhead_comparison.go

Number of entries:  20000000
GC pause for bigcache:  1.506077ms
GC pause for freecache:  5.594416ms
GC pause for map:  9.347015ms
```

```
go version
go version go1.13 linux/arm64

go run caches_gc_overhead_comparison.go
Number of entries:  20000000
GC pause for bigcache:  22.382827ms
GC pause for freecache:  41.264651ms
GC pause for map:  72.236853ms
```

Test shows how long are the GC pauses for caches filled with 20mln of entries.
Bigcache and freecache have very similar GC pause time.

### Memory usage

You 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).

## How it works

BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)).
This optimization states that if map without pointers in keys and values is used then GC will omit its content.
Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries.

Entries are kept in byte slices, to omit GC again.
Byte slices size can grow to gigabytes without impact on performance
because GC will only see single pointer to it.

### Collisions

BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value.

## Bigcache vs Freecache

Both caches provide the same core features but they reduce GC overhead in different ways.
Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on
slices to reduce number of pointers.

Results from benchmark tests are presented above.
One of the advantage of bigcache over freecache is that you don’t need to know
the size of the cache in advance, because when bigcache is full,
it can allocate additional memory for new entries instead of
overwriting existing ones as freecache does currently.
However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config).

## HTTP Server

This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package.

## More

Bigcache 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)

## License

BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE))


================================================
FILE: assert_test.go
================================================
package bigcache

import (
	"bytes"
	"fmt"
	"path"
	"reflect"
	"runtime"
	"testing"
)

func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) {
	if !objectsAreEqual(expected, actual) {
		_, file, line, _ := runtime.Caller(1)
		file = path.Base(file)
		t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+
			"expected: %T(%#v)\n"+
			"actual  : %T(%#v)\n",
			file, line, expected, expected, actual, actual), msgAndArgs...)
	}
}

func noError(t *testing.T, e error) {
	if e != nil {
		_, file, line, _ := runtime.Caller(1)
		file = path.Base(file)
		t.Errorf("\n%s:%d: Error is not nil: \n"+
			"actual  : %T(%#v)\n", file, line, e, e)
	}
}

func objectsAreEqual(expected, actual interface{}) bool {
	if expected == nil || actual == nil {
		return expected == actual
	}

	exp, ok := expected.([]byte)
	if !ok {
		return reflect.DeepEqual(expected, actual)
	}

	act, ok := actual.([]byte)
	if !ok {
		return false
	}
	if exp == nil || act == nil {
		return exp == nil && act == nil
	}
	return bytes.Equal(exp, act)
}


================================================
FILE: bigcache.go
================================================
package bigcache

import (
	"context"
	"errors"
	"time"
)

const (
	minimumEntriesInShard = 10 // Minimum number of entries in single shard
)

// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance.
// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays,
// therefore entries (de)serialization in front of the cache will be needed in most use cases.
type BigCache struct {
	shards     []*cacheShard
	lifeWindow uint64
	clock      clock
	hash       Hasher
	config     Config
	shardMask  uint64
	close      chan struct{}
}

// Response will contain metadata about the entry for which GetWithInfo(key) was called
type Response struct {
	EntryStatus RemoveReason
}

// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback.
type RemoveReason uint32

const (
	_ RemoveReason = iota
	// Expired means the key is past its LifeWindow.
	Expired
	// NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the
	// entry exceeded the maximum shard size.
	NoSpace
	// Deleted means Delete was called and this key was removed as a result.
	Deleted
)

// New initialize new instance of BigCache
func New(ctx context.Context, config Config) (*BigCache, error) {
	return newBigCache(ctx, config, &systemClock{})
}

// NewBigCache initialize new instance of BigCache
//
// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead,
// New takes in context and can gracefully
// shutdown with context cancellations
func NewBigCache(config Config) (*BigCache, error) {
	return newBigCache(context.Background(), config, &systemClock{})
}

func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) {
	if !isPowerOfTwo(config.Shards) {
		return nil, errors.New("Shards number must be power of two") //nolint:staticcheck // keep for backward compatibility
	}
	if config.MaxEntrySize < 0 {
		return nil, errors.New("MaxEntrySize must be >= 0")
	}
	if config.MaxEntriesInWindow < 0 {
		return nil, errors.New("MaxEntriesInWindow must be >= 0")
	}
	if config.HardMaxCacheSize < 0 {
		return nil, errors.New("HardMaxCacheSize must be >= 0")
	}

	lifeWindowSeconds := uint64(config.LifeWindow.Seconds())
	if config.CleanWindow > 0 && lifeWindowSeconds == 0 {
		return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set")
	}

	if config.Hasher == nil {
		config.Hasher = newDefaultHasher()
	}

	cache := &BigCache{
		shards:     make([]*cacheShard, config.Shards),
		lifeWindow: lifeWindowSeconds,
		clock:      clock,
		hash:       config.Hasher,
		config:     config,
		shardMask:  uint64(config.Shards - 1),
		close:      make(chan struct{}),
	}

	var onRemove func(wrappedEntry []byte, reason RemoveReason)
	if config.OnRemoveWithMetadata != nil {
		onRemove = cache.providedOnRemoveWithMetadata
	} else if config.OnRemove != nil {
		onRemove = cache.providedOnRemove
	} else if config.OnRemoveWithReason != nil {
		onRemove = cache.providedOnRemoveWithReason
	} else {
		onRemove = cache.notProvidedOnRemove
	}

	for i := 0; i < config.Shards; i++ {
		cache.shards[i] = initNewShard(config, onRemove, clock)
	}

	if config.CleanWindow > 0 {
		go func() {
			ticker := time.NewTicker(config.CleanWindow)
			defer ticker.Stop()
			for {
				select {
				case <-ctx.Done():
					return
				case t := <-ticker.C:
					cache.cleanUp(uint64(t.Unix()))
				case <-cache.close:
					return
				}
			}
		}()
	}

	return cache, nil
}

// Close is used to signal a shutdown of the cache when you are done with it.
// This allows the cleaning goroutines to exit and ensures references are not
// kept to the cache preventing GC of the entire cache.
func (c *BigCache) Close() error {
	close(c.close)
	return nil
}

// Get reads entry for the key.
// It returns an ErrEntryNotFound when
// no entry exists for the given key.
func (c *BigCache) Get(key string) ([]byte, error) {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.get(key, hashedKey)
}

// GetWithInfo reads entry for the key with Response info.
// It returns an ErrEntryNotFound when
// no entry exists for the given key.
func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.getWithInfo(key, hashedKey)
}

// Set saves entry under the key
func (c *BigCache) Set(key string, entry []byte) error {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.set(key, hashedKey, entry)
}

// Append appends entry under the key if key exists, otherwise
// it will set the key (same behaviour as Set()). With Append() you can
// concatenate multiple entries under the same key in a lock-optimized way.
func (c *BigCache) Append(key string, entry []byte) error {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.append(key, hashedKey, entry)
}

// Delete removes the key
func (c *BigCache) Delete(key string) error {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.del(hashedKey)
}

// Reset empties all cache shards
func (c *BigCache) Reset() error {
	for _, shard := range c.shards {
		shard.reset(c.config)
	}
	return nil
}

// ResetStats resets cache stats
func (c *BigCache) ResetStats() error {
	for _, shard := range c.shards {
		shard.resetStats()
	}
	return nil
}

// Len computes the number of entries in the cache.
func (c *BigCache) Len() int {
	var len int
	for _, shard := range c.shards {
		len += shard.len()
	}
	return len
}

// Capacity returns the amount of bytes stored in the cache.
func (c *BigCache) Capacity() int {
	var len int
	for _, shard := range c.shards {
		len += shard.capacity()
	}
	return len
}

// Stats returns cache's statistics
func (c *BigCache) Stats() Stats {
	var s Stats
	for _, shard := range c.shards {
		tmp := shard.getStats()
		s.Hits += tmp.Hits
		s.Misses += tmp.Misses
		s.DelHits += tmp.DelHits
		s.DelMisses += tmp.DelMisses
		s.Collisions += tmp.Collisions
	}
	return s
}

// KeyMetadata returns number of times a cached resource was requested.
func (c *BigCache) KeyMetadata(key string) Metadata {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.getKeyMetadataWithLock(hashedKey)
}

// Iterator returns iterator function to iterate over EntryInfo's from whole cache.
func (c *BigCache) Iterator() *EntryInfoIterator {
	return newIterator(c)
}

func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
	oldestTimestamp := readTimestampFromEntry(oldestEntry)
	if currentTimestamp < oldestTimestamp {
		return false
	}
	if currentTimestamp-oldestTimestamp > c.lifeWindow {
		evict(Expired)
		return true
	}
	return false
}

func (c *BigCache) cleanUp(currentTimestamp uint64) {
	for _, shard := range c.shards {
		shard.cleanUp(currentTimestamp)
	}
}

func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) {
	return c.shards[hashedKey&c.shardMask]
}

func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) {
	c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry))
}

func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) {
	if c.config.onRemoveFilter == 0 || (1<<uint(reason))&c.config.onRemoveFilter > 0 {
		c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason)
	}
}

func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) {
}

func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) {
	key := readKeyFromEntry(wrappedEntry)

	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey))
}


================================================
FILE: bigcache_bench_test.go
================================================
package bigcache

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"testing"
	"time"
)

var message = blob('a', 256)

func BenchmarkWriteToCacheWith1Shard(b *testing.B) {
	writeToCache(b, 1, 100*time.Second, b.N)
}

func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) {
	m := blob('a', 1024)
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         100 * time.Second,
		MaxEntriesInWindow: 100,
		MaxEntrySize:       256,
		HardMaxCacheSize:   1,
	})

	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		cache.Set(fmt.Sprintf("key-%d", i), m)
	}
}

func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) {
	m := blob('a', 1024)
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         100 * time.Second,
		MaxEntriesInWindow: 100,
		MaxEntrySize:       256,
	})

	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		cache.Set(fmt.Sprintf("key-%d", i), m)
	}
}

func BenchmarkWriteToCache(b *testing.B) {
	for _, shards := range []int{1, 512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			writeToCache(b, shards, 100*time.Second, b.N)
		})
	}
}
func BenchmarkAppendToCache(b *testing.B) {
	for _, shards := range []int{1, 512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			appendToCache(b, shards, 100*time.Second, b.N)
		})
	}
}

func BenchmarkReadFromCache(b *testing.B) {
	for _, shards := range []int{1, 512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			readFromCache(b, shards, false)
		})
	}
}

func BenchmarkReadFromCacheWithInfo(b *testing.B) {
	for _, shards := range []int{1, 512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			readFromCache(b, shards, true)
		})
	}
}
func BenchmarkIterateOverCache(b *testing.B) {

	m := blob('a', 1)

	for _, shards := range []int{512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			cache, _ := New(context.Background(), Config{
				Shards:             shards,
				LifeWindow:         1000 * time.Second,
				MaxEntriesInWindow: max(b.N, 100),
				MaxEntrySize:       500,
			})

			for i := 0; i < b.N; i++ {
				cache.Set(fmt.Sprintf("key-%d", i), m)
			}

			b.ResetTimer()
			it := cache.Iterator()

			b.RunParallel(func(pb *testing.PB) {
				b.ReportAllocs()

				for pb.Next() {
					if it.SetNext() {
						it.Value()
					}
				}
			})
		})
	}
}

func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) {
	writeToCache(b, 1024, 100*time.Second, 100)
}

func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) {
	for _, shards := range []int{1, 512, 1024, 8192} {
		b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) {
			readFromCacheNonExistentKeys(b, 1024)
		})
	}
}

func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) {
	cache, _ := New(context.Background(), Config{
		Shards:             shards,
		LifeWindow:         lifeWindow,
		MaxEntriesInWindow: max(requestsInLifeWindow, 100),
		MaxEntrySize:       500,
	})
	rand.Seed(time.Now().Unix())

	b.RunParallel(func(pb *testing.PB) {
		id := rand.Int()
		counter := 0

		b.ReportAllocs()
		for pb.Next() {
			cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message)
			counter = counter + 1
		}
	})
}

func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) {
	cache, _ := New(context.Background(), Config{
		Shards:             shards,
		LifeWindow:         lifeWindow,
		MaxEntriesInWindow: max(requestsInLifeWindow, 100),
		MaxEntrySize:       2000,
	})
	rand.Seed(time.Now().Unix())

	b.RunParallel(func(pb *testing.PB) {
		id := rand.Int()
		counter := 0

		b.ReportAllocs()
		for pb.Next() {
			key := fmt.Sprintf("key-%d-%d", id, counter)
			for j := 0; j < 7; j++ {
				cache.Append(key, message)
			}
			counter = counter + 1
		}
	})
}

func readFromCache(b *testing.B, shards int, info bool) {
	cache, _ := New(context.Background(), Config{
		Shards:             shards,
		LifeWindow:         1000 * time.Second,
		MaxEntriesInWindow: max(b.N, 100),
		MaxEntrySize:       500,
	})
	for i := 0; i < b.N; i++ {
		cache.Set(strconv.Itoa(i), message)
	}
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		b.ReportAllocs()

		for pb.Next() {
			if info {
				cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N)))
			} else {
				cache.Get(strconv.Itoa(rand.Intn(b.N)))
			}
		}
	})
}

func readFromCacheNonExistentKeys(b *testing.B, shards int) {
	cache, _ := New(context.Background(), Config{
		Shards:             shards,
		LifeWindow:         1000 * time.Second,
		MaxEntriesInWindow: max(b.N, 100),
		MaxEntrySize:       500,
	})
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		b.ReportAllocs()

		for pb.Next() {
			cache.Get(strconv.Itoa(rand.Intn(b.N)))
		}
	})
}


================================================
FILE: bigcache_test.go
================================================
package bigcache

import (
	"bytes"
	"context"
	"fmt"
	"math"
	"math/rand"
	"runtime"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestWriteAndGetOnCache(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), DefaultConfig(5*time.Second))
	value := []byte("value")

	// when
	cache.Set("key", value)
	cachedValue, err := cache.Get("key")

	// then
	noError(t, err)
	assertEqual(t, value, cachedValue)
}

func TestAppendAndGetOnCache(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), DefaultConfig(5*time.Second))
	key := "key"
	value1 := make([]byte, 50)
	rand.Read(value1)
	value2 := make([]byte, 50)
	rand.Read(value2)
	value3 := make([]byte, 50)
	rand.Read(value3)

	// when
	_, err := cache.Get(key)

	// then
	assertEqual(t, ErrEntryNotFound, err)

	// when
	cache.Append(key, value1)
	cachedValue, err := cache.Get(key)

	// then
	noError(t, err)
	assertEqual(t, value1, cachedValue)

	// when
	cache.Append(key, value2)
	cachedValue, err = cache.Get(key)

	// then
	noError(t, err)
	expectedValue := value1
	expectedValue = append(expectedValue, value2...)
	assertEqual(t, expectedValue, cachedValue)

	// when
	cache.Append(key, value3)
	cachedValue, err = cache.Get(key)

	// then
	noError(t, err)
	expectedValue = value1
	expectedValue = append(expectedValue, value2...)
	expectedValue = append(expectedValue, value3...)
	assertEqual(t, expectedValue, cachedValue)
}

// TestAppendRandomly does simultaneous appends to check for corruption errors.
func TestAppendRandomly(t *testing.T) {
	t.Parallel()

	c := Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		CleanWindow:        1 * time.Second,
		MaxEntriesInWindow: 1000 * 10 * 60,
		MaxEntrySize:       500,
		StatsEnabled:       true,
		Verbose:            true,
		Hasher:             newDefaultHasher(),
		HardMaxCacheSize:   1,
		Logger:             DefaultLogger(),
	}
	cache, err := New(context.Background(), c)
	noError(t, err)

	nKeys := 5
	nAppendsPerKey := 2000
	nWorker := 10
	var keys []string
	for i := 0; i < nKeys; i++ {
		for j := 0; j < nAppendsPerKey; j++ {
			keys = append(keys, fmt.Sprintf("key%d", i))
		}
	}
	rand.Shuffle(len(keys), func(i, j int) {
		keys[i], keys[j] = keys[j], keys[i]
	})

	jobs := make(chan string, len(keys))
	for _, key := range keys {
		jobs <- key
	}
	close(jobs)

	var wg sync.WaitGroup
	for i := 0; i < nWorker; i++ {
		wg.Add(1)
		go func() {
			for {
				key, ok := <-jobs
				if !ok {
					break
				}
				cache.Append(key, []byte(key))
			}
			wg.Done()
		}()
	}
	wg.Wait()

	assertEqual(t, nKeys, cache.Len())
	for i := 0; i < nKeys; i++ {
		key := fmt.Sprintf("key%d", i)
		expectedValue := []byte(strings.Repeat(key, nAppendsPerKey))
		cachedValue, err := cache.Get(key)
		noError(t, err)
		assertEqual(t, expectedValue, cachedValue)
	}
}

func TestAppendCollision(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
		Verbose:            true,
		Hasher:             hashStub(5),
	})

	//when
	cache.Append("a", []byte("1"))
	cachedValue, err := cache.Get("a")

	//then
	noError(t, err)
	assertEqual(t, []byte("1"), cachedValue)

	// when
	err = cache.Append("b", []byte("2"))

	// then
	noError(t, err)
	assertEqual(t, cache.Stats().Collisions, int64(1))
	cachedValue, err = cache.Get("b")
	noError(t, err)
	assertEqual(t, []byte("2"), cachedValue)

}

func TestConstructCacheWithDefaultHasher(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             16,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
	})

	_, ok := cache.hash.(fnv64a)
	assertEqual(t, true, ok)
}

func TestNewBigcacheValidation(t *testing.T) {
	t.Parallel()

	for _, tc := range []struct {
		cfg  Config
		want string
	}{
		{
			cfg:  Config{Shards: 18},
			want: "Shards number must be power of two",
		},
		{
			cfg:  Config{Shards: 16, MaxEntriesInWindow: -1},
			want: "MaxEntriesInWindow must be >= 0",
		},
		{
			cfg:  Config{Shards: 16, MaxEntrySize: -1},
			want: "MaxEntrySize must be >= 0",
		},
		{
			cfg:  Config{Shards: 16, HardMaxCacheSize: -1},
			want: "HardMaxCacheSize must be >= 0",
		},
	} {
		t.Run(tc.want, func(t *testing.T) {
			cache, error := New(context.Background(), tc.cfg)

			assertEqual(t, (*BigCache)(nil), cache)
			assertEqual(t, tc.want, error.Error())
		})
	}
}

func TestEntryNotFound(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             16,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
	})

	// when
	_, err := cache.Get("nonExistingKey")

	// then
	assertEqual(t, ErrEntryNotFound, err)
}

func TestTimingEviction(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	}, &clock)

	cache.Set("key", []byte("value"))

	// when
	cache.Set("key2", []byte("value2"))
	_, err := cache.Get("key")

	// then
	noError(t, err)

	// when
	clock.set(5)
	cache.Set("key2", []byte("value2"))
	_, err = cache.Get("key")

	// then
	assertEqual(t, ErrEntryNotFound, err)
}

func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             4,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	}, &clock)

	// when
	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.Set("key2", []byte("value 2"))
	value, err := cache.Get("key")

	// then
	noError(t, err)
	assertEqual(t, []byte("value"), value)
}

func TestCleanShouldEvictAll(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             4,
		LifeWindow:         time.Second,
		CleanWindow:        time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	// when
	cache.Set("key", []byte("value"))
	<-time.After(3 * time.Second)
	value, err := cache.Get("key")

	// then
	assertEqual(t, ErrEntryNotFound, err)
	assertEqual(t, value, []byte(nil))
}

func TestOnRemoveCallback(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	onRemoveInvoked := false
	onRemoveExtInvoked := false
	onRemove := func(key string, entry []byte) {
		onRemoveInvoked = true
		assertEqual(t, "key", key)
		assertEqual(t, []byte("value"), entry)
	}
	onRemoveExt := func(key string, entry []byte, reason RemoveReason) {
		onRemoveExtInvoked = true
	}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
		OnRemove:           onRemove,
		OnRemoveWithReason: onRemoveExt,
	}, &clock)

	// when
	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.Set("key2", []byte("value2"))

	// then
	assertEqual(t, true, onRemoveInvoked)
	assertEqual(t, false, onRemoveExtInvoked)
}

func TestOnRemoveWithReasonCallback(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	onRemoveInvoked := false
	onRemove := func(key string, entry []byte, reason RemoveReason) {
		onRemoveInvoked = true
		assertEqual(t, "key", key)
		assertEqual(t, []byte("value"), entry)
		assertEqual(t, reason, RemoveReason(Expired))
	}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
		OnRemoveWithReason: onRemove,
	}, &clock)

	// when
	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.Set("key2", []byte("value2"))

	// then
	assertEqual(t, true, onRemoveInvoked)
}

func TestOnRemoveFilter(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	onRemoveInvoked := false
	onRemove := func(key string, entry []byte, reason RemoveReason) {
		onRemoveInvoked = true
	}
	c := Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
		OnRemoveWithReason: onRemove,
	}.OnRemoveFilterSet(Deleted, NoSpace)

	cache, _ := newBigCache(context.Background(), c, &clock)

	// when
	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.Set("key2", []byte("value2"))

	// then
	assertEqual(t, false, onRemoveInvoked)

	// and when
	cache.Delete("key2")

	// then
	assertEqual(t, true, onRemoveInvoked)
}

func TestOnRemoveFilterExpired(t *testing.T) {
	// t.Parallel()

	// given
	clock := mockedClock{value: 0}
	onRemoveDeleted, onRemoveExpired := false, false
	var err error
	onRemove := func(key string, entry []byte, reason RemoveReason) {
		switch reason {

		case Deleted:
			onRemoveDeleted = true
		case Expired:
			onRemoveExpired = true

		}
	}
	c := Config{
		Shards:             1,
		LifeWindow:         3 * time.Second,
		CleanWindow:        0,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
		OnRemoveWithReason: onRemove,
	}

	cache, err := newBigCache(context.Background(), c, &clock)
	assertEqual(t, err, nil)

	// case 1: key is deleted AFTER expire
	// when
	onRemoveDeleted, onRemoveExpired = false, false
	clock.set(0)

	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.cleanUp(uint64(clock.Epoch()))

	err = cache.Delete("key")

	// then
	assertEqual(t, err, ErrEntryNotFound)
	assertEqual(t, false, onRemoveDeleted)
	assertEqual(t, true, onRemoveExpired)

	// case 1: key is deleted BEFORE expire
	// when
	onRemoveDeleted, onRemoveExpired = false, false
	clock.set(0)

	cache.Set("key2", []byte("value2"))
	err = cache.Delete("key2")
	clock.set(5)
	cache.cleanUp(uint64(clock.Epoch()))
	// then

	assertEqual(t, err, nil)
	assertEqual(t, true, onRemoveDeleted)
	assertEqual(t, false, onRemoveExpired)
}

func TestOnRemoveGetEntryStats(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	count := uint32(0)
	onRemove := func(key string, entry []byte, keyMetadata Metadata) {
		count = keyMetadata.RequestCount
	}
	c := Config{
		Shards:               1,
		LifeWindow:           time.Second,
		MaxEntriesInWindow:   1,
		MaxEntrySize:         256,
		OnRemoveWithMetadata: onRemove,
		StatsEnabled:         true,
	}.OnRemoveFilterSet(Deleted, NoSpace)

	cache, _ := newBigCache(context.Background(), c, &clock)

	// when
	cache.Set("key", []byte("value"))

	for i := 0; i < 100; i++ {
		cache.Get("key")
	}

	cache.Delete("key")

	// then
	assertEqual(t, uint32(100), count)
}

func TestCacheLen(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	keys := 1337

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	// then
	assertEqual(t, keys, cache.Len())
}

func TestCacheCapacity(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	keys := 1337

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	// then
	assertEqual(t, keys, cache.Len())
	assertEqual(t, 40960, cache.Capacity())
}

func TestCacheInitialCapacity(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 2 * 1024,
		HardMaxCacheSize:   1,
		MaxEntrySize:       1024,
	})

	assertEqual(t, 0, cache.Len())
	assertEqual(t, 1024*1024, cache.Capacity())

	keys := 1024 * 1024

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	// then
	assertEqual(t, true, cache.Len() < keys)
	assertEqual(t, 1024*1024, cache.Capacity())
}

func TestRemoveEntriesWhenShardIsFull(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         100 * time.Second,
		MaxEntriesInWindow: 100,
		MaxEntrySize:       256,
		HardMaxCacheSize:   1,
	})

	value := blob('a', 1024*300)

	// when
	cache.Set("key", value)
	cache.Set("key", value)
	cache.Set("key", value)
	cache.Set("key", value)
	cache.Set("key", value)
	cachedValue, err := cache.Get("key")

	// then
	noError(t, err)
	assertEqual(t, value, cachedValue)
}

func TestCacheStats(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	// when
	for i := 0; i < 100; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	for i := 0; i < 10; i++ {
		value, err := cache.Get(fmt.Sprintf("key%d", i))
		noError(t, err)
		assertEqual(t, string(value), "value")
	}
	for i := 100; i < 110; i++ {
		_, err := cache.Get(fmt.Sprintf("key%d", i))
		assertEqual(t, ErrEntryNotFound, err)
	}
	for i := 10; i < 20; i++ {
		err := cache.Delete(fmt.Sprintf("key%d", i))
		noError(t, err)
	}
	for i := 110; i < 120; i++ {
		err := cache.Delete(fmt.Sprintf("key%d", i))
		assertEqual(t, ErrEntryNotFound, err)
	}

	// then
	stats := cache.Stats()
	assertEqual(t, stats.Hits, int64(10))
	assertEqual(t, stats.Misses, int64(10))
	assertEqual(t, stats.DelHits, int64(10))
	assertEqual(t, stats.DelMisses, int64(10))
}
func TestCacheEntryStats(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
		StatsEnabled:       true,
	})

	cache.Set("key0", []byte("value"))

	for i := 0; i < 10; i++ {
		_, err := cache.Get("key0")
		noError(t, err)
	}

	// then
	keyMetadata := cache.KeyMetadata("key0")
	assertEqual(t, uint32(10), keyMetadata.RequestCount)
}

func TestCacheRestStats(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	// when
	for i := 0; i < 100; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	for i := 0; i < 10; i++ {
		value, err := cache.Get(fmt.Sprintf("key%d", i))
		noError(t, err)
		assertEqual(t, string(value), "value")
	}
	for i := 100; i < 110; i++ {
		_, err := cache.Get(fmt.Sprintf("key%d", i))
		assertEqual(t, ErrEntryNotFound, err)
	}
	for i := 10; i < 20; i++ {
		err := cache.Delete(fmt.Sprintf("key%d", i))
		noError(t, err)
	}
	for i := 110; i < 120; i++ {
		err := cache.Delete(fmt.Sprintf("key%d", i))
		assertEqual(t, ErrEntryNotFound, err)
	}

	stats := cache.Stats()
	assertEqual(t, stats.Hits, int64(10))
	assertEqual(t, stats.Misses, int64(10))
	assertEqual(t, stats.DelHits, int64(10))
	assertEqual(t, stats.DelMisses, int64(10))

	//then
	cache.ResetStats()
	stats = cache.Stats()
	assertEqual(t, stats.Hits, int64(0))
	assertEqual(t, stats.Misses, int64(0))
	assertEqual(t, stats.DelHits, int64(0))
	assertEqual(t, stats.DelMisses, int64(0))
}

func TestCacheDel(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), DefaultConfig(time.Second))

	// when
	err := cache.Delete("nonExistingKey")

	// then
	assertEqual(t, err, ErrEntryNotFound)

	// and when
	cache.Set("existingKey", nil)
	err = cache.Delete("existingKey")
	cachedValue, _ := cache.Get("existingKey")

	// then
	noError(t, err)
	assertEqual(t, 0, len(cachedValue))
}

// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors.
func TestCacheDelRandomly(t *testing.T) {
	t.Parallel()

	c := Config{
		Shards:             1,
		LifeWindow:         time.Second,
		CleanWindow:        0,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       10,
		Verbose:            false,
		Hasher:             newDefaultHasher(),
		HardMaxCacheSize:   1,
		StatsEnabled:       true,
		Logger:             DefaultLogger(),
	}

	cache, _ := New(context.Background(), c)
	var wg sync.WaitGroup
	var ntest = 800000
	wg.Add(3)
	go func() {
		for i := 0; i < ntest; i++ {
			r := uint8(rand.Int())
			key := fmt.Sprintf("thekey%d", r)

			cache.Delete(key)
		}
		wg.Done()
	}()
	valueLen := 1024
	go func() {
		val := make([]byte, valueLen)
		for i := 0; i < ntest; i++ {
			r := byte(rand.Int())
			key := fmt.Sprintf("thekey%d", r)

			for j := 0; j < len(val); j++ {
				val[j] = r
			}
			cache.Set(key, val)
		}
		wg.Done()
	}()
	go func() {
		val := make([]byte, valueLen)
		for i := 0; i < ntest; i++ {
			r := byte(rand.Int())
			key := fmt.Sprintf("thekey%d", r)

			for j := 0; j < len(val); j++ {
				val[j] = r
			}
			if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) {
				t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val)
			}
		}
		wg.Done()
	}()
	wg.Wait()
}

func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) {
	t.Parallel()

	c := DefaultConfig(10 * time.Second)
	c.StatsEnabled = true

	cache, _ := New(context.Background(), c)
	var wg sync.WaitGroup
	ntest := 1000
	n := 10
	wg.Add(n)
	key := "key"
	value := blob('a', 1024)
	for i := 0; i < ntest; i++ {
		assertEqual(t, nil, cache.Set(key, value))
	}
	for j := 0; j < n; j++ {
		go func() {
			for i := 0; i < ntest; i++ {
				v, err := cache.Get(key)
				assertEqual(t, nil, err)
				assertEqual(t, value, v)
			}
			wg.Done()
		}()
	}

	wg.Wait()

	assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats())
	assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount))
}

func TestCacheReset(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	keys := 1337

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	// then
	assertEqual(t, keys, cache.Len())

	// and when
	cache.Reset()

	// then
	assertEqual(t, 0, cache.Len())

	// and when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	// then
	assertEqual(t, keys, cache.Len())
}

func TestIterateOnResetCache(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	keys := 1337

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}
	cache.Reset()

	// then
	iterator := cache.Iterator()

	assertEqual(t, false, iterator.SetNext())
}

func TestGetOnResetCache(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	keys := 1337

	// when
	for i := 0; i < keys; i++ {
		cache.Set(fmt.Sprintf("key%d", i), []byte("value"))
	}

	cache.Reset()

	// then
	value, err := cache.Get("key1")

	assertEqual(t, err, ErrEntryNotFound)
	assertEqual(t, value, []byte(nil))
}

func TestEntryUpdate(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         6 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	}, &clock)

	// when
	cache.Set("key", []byte("value"))
	clock.set(5)
	cache.Set("key", []byte("value2"))
	clock.set(7)
	cache.Set("key2", []byte("value3"))
	cachedValue, _ := cache.Get("key")

	// then
	assertEqual(t, []byte("value2"), cachedValue)
}

func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
	})

	// when
	cache.Set("key1", blob('a', 1024*400))
	cache.Set("key2", blob('b', 1024*400))
	cache.Set("key3", blob('c', 1024*800))

	_, key1Err := cache.Get("key1")
	_, key2Err := cache.Get("key2")
	entry3, _ := cache.Get("key3")

	// then
	assertEqual(t, key1Err, ErrEntryNotFound)
	assertEqual(t, key2Err, ErrEntryNotFound)
	assertEqual(t, blob('c', 1024*800), entry3)
}

func TestRetrievingEntryShouldCopy(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
	})
	cache.Set("key1", blob('a', 1024*400))
	value, key1Err := cache.Get("key1")

	// when
	// override queue
	cache.Set("key2", blob('b', 1024*400))
	cache.Set("key3", blob('c', 1024*400))
	cache.Set("key4", blob('d', 1024*400))
	cache.Set("key5", blob('d', 1024*400))

	// then
	noError(t, key1Err)
	assertEqual(t, blob('a', 1024*400), value)
}

func TestEntryBiggerThanMaxShardSizeError(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
	})

	// when
	err := cache.Set("key1", blob('a', 1024*1025))

	// then
	assertEqual(t, "entry is bigger than max shard size", err.Error())
}

func TestHashCollision(t *testing.T) {
	t.Parallel()

	ml := &mockedLogger{}
	// given
	cache, _ := New(context.Background(), Config{
		Shards:             16,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
		Verbose:            true,
		Hasher:             hashStub(5),
		Logger:             ml,
	})

	// when
	cache.Set("liquid", []byte("value"))
	cachedValue, err := cache.Get("liquid")

	// then
	noError(t, err)
	assertEqual(t, []byte("value"), cachedValue)

	// when
	cache.Set("costarring", []byte("value 2"))
	cachedValue, err = cache.Get("costarring")

	// then
	noError(t, err)
	assertEqual(t, []byte("value 2"), cachedValue)

	// when
	cachedValue, err = cache.Get("liquid")

	// then
	assertEqual(t, ErrEntryNotFound, err)
	assertEqual(t, []byte(nil), cachedValue)

	assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat)
	assertEqual(t, cache.Stats().Collisions, int64(1))
}

func TestNilValueCaching(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
	})

	// when
	cache.Set("Kierkegaard", []byte{})
	cachedValue, err := cache.Get("Kierkegaard")

	// then
	noError(t, err)
	assertEqual(t, []byte{}, cachedValue)

	// when
	cache.Set("Sartre", nil)
	cachedValue, err = cache.Get("Sartre")

	// then
	noError(t, err)
	assertEqual(t, []byte{}, cachedValue)

	// when
	cache.Set("Nietzsche", []byte(nil))
	cachedValue, err = cache.Get("Nietzsche")

	// then
	noError(t, err)
	assertEqual(t, []byte{}, cachedValue)
}

func TestClosing(t *testing.T) {
	// given
	config := Config{
		CleanWindow: time.Minute,
		Shards:      1,
		LifeWindow:  1 * time.Second,
	}
	startGR := runtime.NumGoroutine()

	// when
	for i := 0; i < 100; i++ {
		cache, _ := New(context.Background(), config)
		cache.Close()
	}

	// wait till all goroutines are stopped.
	time.Sleep(200 * time.Millisecond)

	// then
	endGR := runtime.NumGoroutine()
	assertEqual(t, true, endGR >= startGR)
	assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25)
}

func TestEntryNotPresent(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
	}, &clock)

	// when
	value, resp, err := cache.GetWithInfo("blah")
	assertEqual(t, ErrEntryNotFound, err)
	assertEqual(t, resp.EntryStatus, RemoveReason(0))
	assertEqual(t, cache.Stats().Misses, int64(1))
	assertEqual(t, []byte(nil), value)
}

func TestBigCache_GetWithInfo(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		CleanWindow:        5 * time.Minute,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       1,
		HardMaxCacheSize:   1,
		Verbose:            true,
	}, &clock)
	key := "deadEntryKey"
	value := "100"
	cache.Set(key, []byte(value))

	for _, tc := range []struct {
		name     string
		clock    int64
		wantData string
		wantResp Response
	}{
		{
			name:     "zero",
			clock:    0,
			wantData: value,
			wantResp: Response{},
		},
		{
			name:     "Before Expired",
			clock:    4,
			wantData: value,
			wantResp: Response{},
		},
		{
			name:     "Expired",
			clock:    5,
			wantData: value,
			wantResp: Response{EntryStatus: Expired},
		},
		{
			name:     "After Expired",
			clock:    6,
			wantData: value,
			wantResp: Response{EntryStatus: Expired},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			clock.set(tc.clock)
			data, resp, err := cache.GetWithInfo(key)

			assertEqual(t, []byte(tc.wantData), data)
			noError(t, err)
			assertEqual(t, tc.wantResp, resp)
		})
	}
}

func TestBigCache_GetWithInfoCollision(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         5 * time.Second,
		MaxEntriesInWindow: 10,
		MaxEntrySize:       256,
		Verbose:            true,
		Hasher:             hashStub(5),
	})

	//when
	cache.Set("a", []byte("1"))
	cachedValue, resp, err := cache.GetWithInfo("a")

	// then
	noError(t, err)
	assertEqual(t, []byte("1"), cachedValue)
	assertEqual(t, Response{}, resp)

	// when
	cachedValue, resp, err = cache.GetWithInfo("b")

	// then
	assertEqual(t, []byte(nil), cachedValue)
	assertEqual(t, Response{}, resp)
	assertEqual(t, ErrEntryNotFound, err)
	assertEqual(t, cache.Stats().Collisions, int64(1))

}

type mockedLogger struct {
	lastFormat string
	lastArgs   []interface{}
}

func (ml *mockedLogger) Printf(format string, v ...interface{}) {
	ml.lastFormat = format
	ml.lastArgs = v
}

type mockedClock struct {
	value int64
}

func (mc *mockedClock) Epoch() int64 {
	return mc.value
}

func (mc *mockedClock) set(value int64) {
	mc.value = value
}

func blob(char byte, len int) []byte {
	return bytes.Repeat([]byte{char}, len)
}

func TestCache_SetWithoutCleanWindow(t *testing.T) {

	opt := DefaultConfig(time.Second)
	opt.CleanWindow = 0
	opt.HardMaxCacheSize = 1
	bc, _ := New(context.Background(), opt)

	err := bc.Set("2225", make([]byte, 200))
	if nil != err {
		t.Error(err)
		t.FailNow()
	}
}

func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) {

	opt := DefaultConfig(time.Second)
	opt.Shards = 2 << 10
	opt.MaxEntriesInWindow = 1024
	opt.MaxEntrySize = 1
	opt.HardMaxCacheSize = 1
	bc, _ := New(context.Background(), opt)

	err := bc.Set("2225", make([]byte, 200))
	if nil != err {
		t.Error(err)
		t.FailNow()
	}
	err = bc.Set("8573", make([]byte, 100))
	if nil != err {
		t.Error(err)
		t.FailNow()
	}

	err = bc.Set("8573", make([]byte, 450))
	if nil != err {
		// occur error but go next
		t.Logf("%v", err)
	}

	err = bc.Set("7327", make([]byte, 300))
	if nil != err {
		t.Error(err)
		t.FailNow()
	}

	err = bc.Set("8573", make([]byte, 200))
	if nil != err {
		t.Error(err)
		t.FailNow()
	}

}

// TestBigCache_allocateAdditionalMemoryLeadPanic
// The new commit 16df11e change the encoding method,it can fix issue #300
func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) {
	t.Parallel()
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:       1,
		LifeWindow:   3 * time.Second,
		MaxEntrySize: 52,
	}, &clock)
	ts := time.Now().Unix()
	clock.set(ts)
	cache.Set("a", blob(0xff, 235))
	ts += 2
	clock.set(ts)
	cache.Set("b", blob(0xff, 235))
	// expire the key "a"
	ts += 2
	clock.set(ts)
	// move tail to leftMargin,insert before head
	cache.Set("c", blob(0xff, 108))
	// reallocate memory,fill the tail to head with zero byte,move head to leftMargin
	cache.Set("d", blob(0xff, 1024))
	ts += 4
	clock.set(ts)
	// expire the key "c"
	cache.Set("e", blob(0xff, 3))
	// expire the zero bytes
	cache.Set("f", blob(0xff, 3))
	// expire the key "b"
	cache.Set("g", blob(0xff, 3))
	_, err := cache.Get("b")
	assertEqual(t, err, ErrEntryNotFound)
	data, _ := cache.Get("g")
	assertEqual(t, []byte{0xff, 0xff, 0xff}, data)
}

func TestRemoveNonExpiredData(t *testing.T) {
	onRemove := func(key string, entry []byte, reason RemoveReason) {
		if reason != Deleted {
			if reason == Expired {
				t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key)
				t.FailNow()
			} else {
				time.Sleep(time.Second)
			}
		}
	}

	config := DefaultConfig(10 * time.Minute)
	config.HardMaxCacheSize = 1
	config.MaxEntrySize = 1024
	config.MaxEntriesInWindow = 1024
	config.OnRemoveWithReason = onRemove
	cache, err := New(context.Background(), config)
	noError(t, err)
	defer func() {
		err := cache.Close()
		noError(t, err)
	}()

	data := func(l int) []byte {
		m := make([]byte, l)
		_, err := rand.Read(m)
		noError(t, err)
		return m
	}

	for i := 0; i < 50; i++ {
		key := fmt.Sprintf("key_%d", i)
		//key := "key1"
		err := cache.Set(key, data(800))
		noError(t, err)
	}
}


================================================
FILE: bytes.go
================================================
//go:build !appengine
// +build !appengine

package bigcache

import (
	"unsafe"
)

func bytesToString(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}


================================================
FILE: bytes_appengine.go
================================================
//go:build appengine

package bigcache

func bytesToString(b []byte) string {
	return string(b)
}


================================================
FILE: clock.go
================================================
package bigcache

import "time"

type clock interface {
	Epoch() int64
}

type systemClock struct {
}

func (c systemClock) Epoch() int64 {
	return time.Now().Unix()
}


================================================
FILE: config.go
================================================
package bigcache

import "time"

// Config for BigCache
type Config struct {
	// Number of cache shards, value must be a power of two
	Shards int
	// Time after which entry can be evicted
	LifeWindow time.Duration
	// Interval between removing expired entries (clean up).
	// If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution.
	CleanWindow time.Duration
	// Max number of entries in life window. Used only to calculate initial size for cache shards.
	// When proper value is set then additional memory allocation does not occur.
	MaxEntriesInWindow int
	// Max size of entry in bytes. Used only to calculate initial size for cache shards.
	MaxEntrySize int
	// StatsEnabled if true calculate the number of times a cached resource was requested.
	StatsEnabled bool
	// Verbose mode prints information about new memory allocation
	Verbose bool
	// Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used.
	Hasher Hasher
	// HardMaxCacheSize is a limit for BytesQueue size in MB.
	// It can protect application from consuming all available memory on machine, therefore from running OOM Killer.
	// Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then
	// the oldest entries are overridden for the new ones. The max memory consumption will be bigger than
	// HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys
	// and statistics (map[uint64]uint32) the size of this map is equal to number of entries in
	// cache ~ 2×(64+32)×n bits + overhead or map itself.
	HardMaxCacheSize int
	// OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// ignored if OnRemoveWithMetadata is specified.
	OnRemove func(key string, entry []byte)
	// OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A structure representing details about that specific entry.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata)
	// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A constant representing the reason will be passed through.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// Ignored if OnRemove is specified.
	OnRemoveWithReason func(key string, entry []byte, reason RemoveReason)

	onRemoveFilter int

	// Logger is a logging interface and used in combination with `Verbose`
	// Defaults to `DefaultLogger()`
	Logger Logger
}

// DefaultConfig initializes config with default values.
// When load for BigCache can be predicted in advance then it is better to use custom config.
func DefaultConfig(eviction time.Duration) Config {
	return Config{
		Shards:             1024,
		LifeWindow:         eviction,
		CleanWindow:        1 * time.Second,
		MaxEntriesInWindow: 1000 * 10 * 60,
		MaxEntrySize:       500,
		StatsEnabled:       false,
		Verbose:            true,
		Hasher:             newDefaultHasher(),
		HardMaxCacheSize:   0,
		Logger:             DefaultLogger(),
	}
}

// initialShardSize computes initial shard size
func (c Config) initialShardSize() int {
	return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard)
}

// maximumShardSizeInBytes computes maximum shard size in bytes
func (c Config) maximumShardSizeInBytes() int {
	maxShardSize := 0

	if c.HardMaxCacheSize > 0 {
		maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards
	}

	return maxShardSize
}

// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason.
// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu.
func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config {
	c.onRemoveFilter = 0
	for i := range reasons {
		c.onRemoveFilter |= 1 << uint(reasons[i])
	}

	return c
}


================================================
FILE: encoding.go
================================================
package bigcache

import (
	"encoding/binary"
)

const (
	timestampSizeInBytes = 8                                                       // Number of bytes used for timestamp
	hashSizeInBytes      = 8                                                       // Number of bytes used for hash
	keySizeInBytes       = 2                                                       // Number of bytes used for size of entry key
	headersSizeInBytes   = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers
)

func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {
	keyLength := len(key)
	blobLength := len(entry) + headersSizeInBytes + keyLength

	if blobLength > len(*buffer) {
		*buffer = make([]byte, blobLength)
	}
	blob := *buffer

	binary.LittleEndian.PutUint64(blob, timestamp)
	binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash)
	binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength))
	copy(blob[headersSizeInBytes:], key)
	copy(blob[headersSizeInBytes+keyLength:], entry)

	return blob[:blobLength]
}

func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte {
	blobLength := len(wrappedEntry) + len(entry)
	if blobLength > len(*buffer) {
		*buffer = make([]byte, blobLength)
	}

	blob := *buffer

	binary.LittleEndian.PutUint64(blob, timestamp)
	copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:])
	copy(blob[len(wrappedEntry):], entry)

	return blob[:blobLength]
}

func readEntry(data []byte) []byte {
	length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])

	// copy on read
	dst := make([]byte, len(data)-int(headersSizeInBytes+length))
	copy(dst, data[headersSizeInBytes+length:])

	return dst
}

func readTimestampFromEntry(data []byte) uint64 {
	return binary.LittleEndian.Uint64(data)
}

func readKeyFromEntry(data []byte) string {
	length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])

	// copy on read
	dst := make([]byte, length)
	copy(dst, data[headersSizeInBytes:headersSizeInBytes+length])

	return bytesToString(dst)
}

func compareKeyFromEntry(data []byte, key string) bool {
	length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])

	return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key
}

func readHashFromEntry(data []byte) uint64 {
	return binary.LittleEndian.Uint64(data[timestampSizeInBytes:])
}

func resetHashFromEntry(data []byte) {
	binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0)
}


================================================
FILE: encoding_test.go
================================================
package bigcache

import (
	"testing"
	"time"
)

func TestEncodeDecode(t *testing.T) {
	// given
	now := uint64(time.Now().Unix())
	hash := uint64(42)
	key := "key"
	data := []byte("data")
	buffer := make([]byte, 100)

	// when
	wrapped := wrapEntry(now, hash, key, data, &buffer)

	// then
	assertEqual(t, key, readKeyFromEntry(wrapped))
	assertEqual(t, hash, readHashFromEntry(wrapped))
	assertEqual(t, now, readTimestampFromEntry(wrapped))
	assertEqual(t, data, readEntry(wrapped))
	assertEqual(t, 100, len(buffer))
}

func TestAllocateBiggerBuffer(t *testing.T) {
	//given
	now := uint64(time.Now().Unix())
	hash := uint64(42)
	key := "1"
	data := []byte("2")
	buffer := make([]byte, 1)

	// when
	wrapped := wrapEntry(now, hash, key, data, &buffer)

	// then
	assertEqual(t, key, readKeyFromEntry(wrapped))
	assertEqual(t, hash, readHashFromEntry(wrapped))
	assertEqual(t, now, readTimestampFromEntry(wrapped))
	assertEqual(t, data, readEntry(wrapped))
	assertEqual(t, 2+headersSizeInBytes, len(buffer))
}


================================================
FILE: entry_not_found_error.go
================================================
package bigcache

import "errors"

var (
	// ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key
	ErrEntryNotFound = errors.New("Entry not found") //nolint:staticcheck // keep for backward compatibility
)


================================================
FILE: examples_test.go
================================================
package bigcache_test

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/allegro/bigcache/v3"
)

func Example() {
	cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute))

	cache.Set("my-unique-key", []byte("value"))

	entry, _ := cache.Get("my-unique-key")
	fmt.Println(string(entry))
	// Output: value
}

func Example_custom() {
	// When cache load can be predicted in advance then it is better to use custom initialization
	// because additional memory allocation can be avoided in that way.
	config := bigcache.Config{
		// number of shards (must be a power of 2)
		Shards: 1024,

		// time after which entry can be evicted
		LifeWindow: 10 * time.Minute,

		// Interval between removing expired entries (clean up).
		// If set to <= 0 then no action is performed.
		// Setting to < 1 second is counterproductive — bigcache has a one second resolution.
		CleanWindow: 5 * time.Minute,

		// rps * lifeWindow, used only in initial memory allocation
		MaxEntriesInWindow: 1000 * 10 * 60,

		// max entry size in bytes, used only in initial memory allocation
		MaxEntrySize: 500,

		// prints information about additional memory allocation
		Verbose: true,

		// cache will not allocate more memory than this limit, value in MB
		// if value is reached then the oldest entries can be overridden for the new ones
		// 0 value means no size limit
		HardMaxCacheSize: 8192,

		// callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A bitmask representing the reason will be returned.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		OnRemove: nil,

		// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A constant representing the reason will be passed through.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		// Ignored if OnRemove is specified.
		OnRemoveWithReason: nil,
	}

	cache, initErr := bigcache.New(context.Background(), config)
	if initErr != nil {
		log.Fatal(initErr)
	}

	err := cache.Set("my-unique-key", []byte("value"))
	if err != nil {
		log.Fatal(err)
	}

	entry, err := cache.Get("my-unique-key")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(entry))
	// Output: value
}


================================================
FILE: fnv.go
================================================
package bigcache

// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations.
// Its Sum64 method will lay the value out in big-endian byte order.
// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
func newDefaultHasher() Hasher {
	return fnv64a{}
}

type fnv64a struct{}

const (
	// offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash
	offset64 = 14695981039346656037
	// prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash
	prime64 = 1099511628211
)

// Sum64 gets the string and returns its uint64 hash value.
func (f fnv64a) Sum64(key string) uint64 {
	var hash uint64 = offset64
	for i := 0; i < len(key); i++ {
		hash ^= uint64(key[i])
		hash *= prime64
	}

	return hash
}


================================================
FILE: fnv_bench_test.go
================================================
package bigcache

import "testing"

var text = "abcdefg"

func BenchmarkFnvHashSum64(b *testing.B) {
	h := newDefaultHasher()
	for i := 0; i < b.N; i++ {
		h.Sum64(text)
	}
}

func BenchmarkFnvHashStdLibSum64(b *testing.B) {
	for i := 0; i < b.N; i++ {
		stdLibFnvSum64(text)
	}
}


================================================
FILE: fnv_test.go
================================================
package bigcache

import (
	"hash/fnv"
	"testing"
)

type testCase struct {
	text         string
	expectedHash uint64
}

var testCases = []testCase{
	{"", stdLibFnvSum64("")},
	{"a", stdLibFnvSum64("a")},
	{"ab", stdLibFnvSum64("ab")},
	{"abc", stdLibFnvSum64("abc")},
	{"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")},
}

func TestFnvHashSum64(t *testing.T) {
	h := newDefaultHasher()
	for _, testCase := range testCases {
		hashed := h.Sum64(testCase.text)
		if hashed != testCase.expectedHash {
			t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash)
		}
	}
}

func stdLibFnvSum64(key string) uint64 {
	h := fnv.New64a()
	h.Write([]byte(key))
	return h.Sum64()
}


================================================
FILE: go.mod
================================================
module github.com/allegro/bigcache/v3

go 1.16


================================================
FILE: go.sum
================================================


================================================
FILE: hash.go
================================================
package bigcache

// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions
// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e.
// you can use FarmHash family).
type Hasher interface {
	Sum64(string) uint64
}


================================================
FILE: hash_test.go
================================================
package bigcache

type hashStub uint64

func (stub hashStub) Sum64(_ string) uint64 {
	return uint64(stub)
}


================================================
FILE: iterator.go
================================================
package bigcache

import (
	"sync"
)

type iteratorError string

func (e iteratorError) Error() string {
	return string(e)
}

// ErrInvalidIteratorState is reported when iterator is in invalid state
const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position")

// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying
const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache")

var emptyEntryInfo = EntryInfo{}

// EntryInfo holds informations about entry in the cache
type EntryInfo struct {
	timestamp uint64
	hash      uint64
	key       string
	value     []byte
	err       error
}

// Key returns entry's underlying key
func (e EntryInfo) Key() string {
	return e.key
}

// Hash returns entry's hash value
func (e EntryInfo) Hash() uint64 {
	return e.hash
}

// Timestamp returns entry's timestamp (time of insertion)
func (e EntryInfo) Timestamp() uint64 {
	return e.timestamp
}

// Value returns entry's underlying value
func (e EntryInfo) Value() []byte {
	return e.value
}

// EntryInfoIterator allows to iterate over entries in the cache
type EntryInfoIterator struct {
	mutex            sync.Mutex
	cache            *BigCache
	currentShard     int
	currentIndex     int
	currentEntryInfo EntryInfo
	elements         []uint64
	elementsCount    int
	valid            bool
}

// SetNext moves to next element and returns true if it exists.
func (it *EntryInfoIterator) SetNext() bool {
	it.mutex.Lock()

	it.valid = false
	it.currentIndex++

	if it.elementsCount > it.currentIndex {
		it.valid = true

		empty := it.setCurrentEntry()
		it.mutex.Unlock()

		if empty {
			return it.SetNext()
		}
		return true
	}

	for i := it.currentShard + 1; i < it.cache.config.Shards; i++ {
		it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys()

		// Non empty shard - stick with it
		if it.elementsCount > 0 {
			it.currentIndex = 0
			it.currentShard = i
			it.valid = true

			empty := it.setCurrentEntry()
			it.mutex.Unlock()

			if empty {
				return it.SetNext()
			}
			return true
		}
	}
	it.mutex.Unlock()
	return false
}

func (it *EntryInfoIterator) setCurrentEntry() bool {
	var entryNotFound = false
	entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex])

	if err == ErrEntryNotFound {
		it.currentEntryInfo = emptyEntryInfo
		entryNotFound = true
	} else if err != nil {
		it.currentEntryInfo = EntryInfo{
			err: err,
		}
	} else {
		it.currentEntryInfo = EntryInfo{
			timestamp: readTimestampFromEntry(entry),
			hash:      readHashFromEntry(entry),
			key:       readKeyFromEntry(entry),
			value:     readEntry(entry),
			err:       err,
		}
	}

	return entryNotFound
}

func newIterator(cache *BigCache) *EntryInfoIterator {
	elements, count := cache.shards[0].copyHashedKeys()

	return &EntryInfoIterator{
		cache:         cache,
		currentShard:  0,
		currentIndex:  -1,
		elements:      elements,
		elementsCount: count,
	}
}

// Value returns current value from the iterator
func (it *EntryInfoIterator) Value() (EntryInfo, error) {
	if !it.valid {
		return emptyEntryInfo, ErrInvalidIteratorState
	}

	return it.currentEntryInfo, it.currentEntryInfo.err
}


================================================
FILE: iterator_test.go
================================================
package bigcache

import (
	"context"
	"fmt"
	"math/rand"
	"runtime"
	"strconv"
	"sync"
	"testing"
	"time"
)

func TestEntriesIterator(t *testing.T) {
	t.Parallel()

	// given
	keysCount := 1000
	cache, _ := New(context.Background(), Config{
		Shards:             8,
		LifeWindow:         6 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})
	value := []byte("value")

	for i := 0; i < keysCount; i++ {
		cache.Set(fmt.Sprintf("key%d", i), value)
	}

	// when
	keys := make(map[string]struct{})
	iterator := cache.Iterator()

	for iterator.SetNext() {
		current, err := iterator.Value()

		if err == nil {
			keys[current.Key()] = struct{}{}
		}
	}

	// then
	assertEqual(t, keysCount, len(keys))
}

func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) {
	t.Parallel()

	// given
	clock := mockedClock{value: 0}
	cache, _ := newBigCache(context.Background(), Config{
		Shards:             8,
		LifeWindow:         6 * time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	}, &clock)

	cache.Set("key", []byte("value"))

	// when
	iterator := cache.Iterator()

	// then
	if !iterator.SetNext() {
		t.Errorf("Iterator should contain at least single element")
	}

	current, err := iterator.Value()

	// then
	noError(t, err)
	assertEqual(t, "key", current.Key())
	assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash())
	assertEqual(t, []byte("value"), current.Value())
	assertEqual(t, uint64(0), current.Timestamp())
}

func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	cache.Set("key", []byte("value"))

	// when
	iterator := cache.Iterator()

	// then
	if !iterator.SetNext() {
		t.Errorf("Iterator should contain at least single element")
	}

	getOldestEntry := func(s *cacheShard) ([]byte, error) {
		s.lock.RLock()
		defer s.lock.RUnlock()
		return s.entries.Peek()
	}

	// Quite ugly but works
	for i := 0; i < cache.config.Shards; i++ {
		if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil {
			cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry)
		}
	}

	current, err := iterator.Value()
	assertEqual(t, nil, err)
	assertEqual(t, []byte("value"), current.Value())

	next := iterator.SetNext()
	assertEqual(t, false, next)
}

func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	// when
	iterator := cache.Iterator()

	// then
	if iterator.SetNext() {
		t.Errorf("Iterator should not contain any elements")
	}
}

func TestEntriesIteratorInInvalidState(t *testing.T) {
	t.Parallel()

	// given
	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 1,
		MaxEntrySize:       256,
	})

	// when
	iterator := cache.Iterator()

	// then
	_, err := iterator.Value()
	assertEqual(t, ErrInvalidIteratorState, err)
	assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error())
}

func TestEntriesIteratorParallelAdd(t *testing.T) {
	bc, err := New(context.Background(), DefaultConfig(1*time.Minute))
	if err != nil {
		panic(err)
	}

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		for i := 0; i < 10000; i++ {
			err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa"))
			if err != nil {
				panic(err)
			}

			runtime.Gosched()
		}
		wg.Done()
	}()

	for i := 0; i < 100; i++ {
		iter := bc.Iterator()
		for iter.SetNext() {
			_, _ = iter.Value()
		}
	}
	wg.Wait()
}

func TestParallelSetAndIteration(t *testing.T) {
	t.Parallel()

	rand.Seed(0)

	cache, _ := New(context.Background(), Config{
		Shards:             1,
		LifeWindow:         time.Second,
		MaxEntriesInWindow: 100,
		MaxEntrySize:       256,
		HardMaxCacheSize:   1,
		Verbose:            true,
	})

	entrySize := 1024 * 100
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	wg := sync.WaitGroup{}
	wg.Add(2)

	go func() {
		defer func() {
			err := recover()
			// no panic
			assertEqual(t, err, nil)
		}()

		defer wg.Done()

		isTimeout := false

		for !isTimeout {

			select {
			case <-ctx.Done():
				isTimeout = true
			default:
				err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize))
				noError(t, err)
			}
		}
	}()

	go func() {
		defer func() {
			err := recover()
			// no panic
			assertEqual(t, nil, err)
		}()

		defer wg.Done()

		isTimeout := false

		for !isTimeout {

			select {
			case <-ctx.Done():
				isTimeout = true
			default:
				iter := cache.Iterator()
				for iter.SetNext() {
					entry, err := iter.Value()

					// then
					noError(t, err)
					assertEqual(t, entrySize, len(entry.Value()))
				}
			}
		}
	}()

	wg.Wait()
}


================================================
FILE: logger.go
================================================
package bigcache

import (
	"log"
	"os"
)

// Logger is invoked when `Config.Verbose=true`
type Logger interface {
	Printf(format string, v ...interface{})
}

// this is a safeguard, breaking on compile time in case
// `log.Logger` does not adhere to our `Logger` interface.
// see https://golang.org/doc/faq#guarantee_satisfies_interface
var _ Logger = &log.Logger{}

// DefaultLogger returns a `Logger` implementation
// backed by stdlib's log
func DefaultLogger() *log.Logger {
	return log.New(os.Stdout, "", log.LstdFlags)
}

func newLogger(custom Logger) Logger {
	if custom != nil {
		return custom
	}

	return DefaultLogger()
}


================================================
FILE: queue/bytes_queue.go
================================================
package queue

import (
	"encoding/binary"
	"log"
	"time"
)

const (
	// Number of bytes to encode 0 in uvarint format
	minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes
	// Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index
	leftMarginIndex = 1
)

var (
	errEmptyQueue       = &queueError{"Empty queue"}
	errInvalidIndex     = &queueError{"Index must be greater than zero. Invalid index."}
	errIndexOutOfBounds = &queueError{"Index out of range"}
	errFullQueue        = &queueError{"Full queue. Maximum size limit reached."}
)

// BytesQueue is a non-thread safe queue type of fifo based on bytes array.
// For every push operation index of entry is returned. It can be used to read the entry later
type BytesQueue struct {
	full         bool
	array        []byte
	capacity     int
	maxCapacity  int
	head         int
	tail         int
	count        int
	rightMargin  int
	headerBuffer []byte
	verbose      bool
}

type queueError struct {
	message string
}

// getNeededSize returns the number of bytes an entry of length need in the queue
func getNeededSize(length int) int {
	var header int
	switch {
	case length < 127: // 1<<7-1
		header = 1
	case length < 16382: // 1<<14-2
		header = 2
	case length < 2097149: // 1<<21 -3
		header = 3
	case length < 268435452: // 1<<28 -4
		header = 4
	default:
		header = 5
	}

	return length + header
}

// NewBytesQueue initialize new bytes queue.
// capacity is used in bytes array allocation
// When verbose flag is set then information about memory allocation are printed
func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue {
	return &BytesQueue{
		array:        make([]byte, capacity),
		capacity:     capacity,
		maxCapacity:  maxCapacity,
		headerBuffer: make([]byte, binary.MaxVarintLen32),
		tail:         leftMarginIndex,
		head:         leftMarginIndex,
		rightMargin:  leftMarginIndex,
		verbose:      verbose,
	}
}

// Reset removes all entries from queue
func (q *BytesQueue) Reset() {
	// Just reset indexes
	q.tail = leftMarginIndex
	q.head = leftMarginIndex
	q.rightMargin = leftMarginIndex
	q.count = 0
	q.full = false
}

// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed.
// Returns index for pushed data or error if maximum size queue limit is reached.
func (q *BytesQueue) Push(data []byte) (int, error) {
	neededSize := getNeededSize(len(data))

	if !q.canInsertAfterTail(neededSize) {
		if q.canInsertBeforeHead(neededSize) {
			q.tail = leftMarginIndex
		} else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 {
			return -1, errFullQueue
		} else {
			q.allocateAdditionalMemory(neededSize)
		}
	}

	index := q.tail

	q.push(data, neededSize)

	return index, nil
}

func (q *BytesQueue) allocateAdditionalMemory(minimum int) {
	start := time.Now()
	if q.capacity < minimum {
		q.capacity += minimum
	}
	q.capacity = q.capacity * 2
	if q.capacity > q.maxCapacity && q.maxCapacity > 0 {
		q.capacity = q.maxCapacity
	}

	oldArray := q.array
	q.array = make([]byte, q.capacity)

	if leftMarginIndex != q.rightMargin {
		copy(q.array, oldArray[:q.rightMargin])

		if q.tail <= q.head {
			if q.tail != q.head {
				// created slice is slightly larger than need but this is fine after only the needed bytes are copied
				q.push(make([]byte, q.head-q.tail), q.head-q.tail)
			}

			q.head = leftMarginIndex
			q.tail = q.rightMargin
		}
	}

	q.full = false

	if q.verbose {
		log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity)
	}
}

func (q *BytesQueue) push(data []byte, len int) {
	headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len))
	q.copy(q.headerBuffer, headerEntrySize)

	q.copy(data, len-headerEntrySize)

	if q.tail > q.head {
		q.rightMargin = q.tail
	}
	if q.tail == q.head {
		q.full = true
	}

	q.count++
}

func (q *BytesQueue) copy(data []byte, len int) {
	q.tail += copy(q.array[q.tail:], data[:len])
}

// Pop reads the oldest entry from queue and moves head pointer to the next one
func (q *BytesQueue) Pop() ([]byte, error) {
	data, blockSize, err := q.peek(q.head)
	if err != nil {
		return nil, err
	}

	q.head += blockSize
	q.count--

	if q.head == q.rightMargin {
		q.head = leftMarginIndex
		if q.tail == q.rightMargin {
			q.tail = leftMarginIndex
		}
		q.rightMargin = q.tail
	}

	q.full = false

	return data, nil
}

// Peek reads the oldest entry from list without moving head pointer
func (q *BytesQueue) Peek() ([]byte, error) {
	data, _, err := q.peek(q.head)
	return data, err
}

// Get reads entry from index
func (q *BytesQueue) Get(index int) ([]byte, error) {
	data, _, err := q.peek(index)
	return data, err
}

// CheckGet checks if an entry can be read from index
func (q *BytesQueue) CheckGet(index int) error {
	return q.peekCheckErr(index)
}

// Capacity returns number of allocated bytes for queue
func (q *BytesQueue) Capacity() int {
	return q.capacity
}

// Len returns number of entries kept in queue
func (q *BytesQueue) Len() int {
	return q.count
}

// Error returns error message
func (e *queueError) Error() string {
	return e.message
}

// peekCheckErr is identical to peek, but does not actually return any data
func (q *BytesQueue) peekCheckErr(index int) error {

	if q.count == 0 {
		return errEmptyQueue
	}

	if index <= 0 {
		return errInvalidIndex
	}

	if index >= len(q.array) {
		return errIndexOutOfBounds
	}
	return nil
}

// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format
func (q *BytesQueue) peek(index int) ([]byte, int, error) {
	err := q.peekCheckErr(index)
	if err != nil {
		return nil, 0, err
	}

	blockSize, n := binary.Uvarint(q.array[index:])
	return q.array[index+n : index+int(blockSize)], int(blockSize), nil
}

// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue
func (q *BytesQueue) canInsertAfterTail(need int) bool {
	if q.full {
		return false
	}
	if q.tail >= q.head {
		return q.capacity-q.tail >= need
	}
	// 1. there is exactly need bytes between head and tail, so we do not need
	// to reserve extra space for a potential empty entry when realloc this queue
	// 2. still have unused space between tail and head, then we must reserve
	// at least headerEntrySize bytes so we can put an empty entry
	return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize
}

// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue
func (q *BytesQueue) canInsertBeforeHead(need int) bool {
	if q.full {
		return false
	}
	if q.tail >= q.head {
		return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize
	}
	return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize
}


================================================
FILE: queue/bytes_queue_test.go
================================================
package queue

import (
	"bytes"
	"fmt"
	"path"
	"reflect"
	"runtime"
	"testing"
)

func TestPushAndPop(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(10, 0, true)
	entry := []byte("hello")

	// when
	_, err := queue.Pop()

	// then
	assertEqual(t, "Empty queue", err.Error())

	// when
	queue.Push(entry)

	// then
	assertEqual(t, entry, pop(queue))
}

func TestLen(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)
	entry := []byte("hello")
	assertEqual(t, 0, queue.Len())

	// when
	queue.Push(entry)

	// then
	assertEqual(t, queue.Len(), 1)
}

func TestPeek(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)
	entry := []byte("hello")

	// when
	read, err := queue.Peek()
	err2 := queue.peekCheckErr(queue.head)
	// then
	assertEqual(t, err, err2)
	assertEqual(t, "Empty queue", err.Error())
	assertEqual(t, 0, len(read))

	// when
	queue.Push(entry)
	read, err = queue.Peek()
	err2 = queue.peekCheckErr(queue.head)

	// then
	assertEqual(t, err, err2)
	noError(t, err)
	assertEqual(t, pop(queue), read)
	assertEqual(t, entry, read)
}

func TestResetFullQueue(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(10, 20, false)

	// when
	queue.Push(blob('a', 3))
	queue.Push(blob('b', 4))

	// when
	assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning
	_, err := queue.Push(blob('a', 3))       // will set q.full to true

	// then
	assertEqual(t, err, nil)

	// when
	queue.Reset()
	queue.Push(blob('c', 8)) // should not trigger a re-allocation

	// then
	assertEqual(t, blob('c', 8), pop(queue))
	assertEqual(t, queue.Capacity(), 10)
}

func TestReset(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)
	entry := []byte("hello")

	// when
	queue.Push(entry)
	queue.Push(entry)
	queue.Push(entry)

	queue.Reset()
	read, err := queue.Peek()

	// then
	assertEqual(t, "Empty queue", err.Error())
	assertEqual(t, 0, len(read))

	// when
	queue.Push(entry)
	read, err = queue.Peek()

	// then
	noError(t, err)
	assertEqual(t, pop(queue), read)
	assertEqual(t, entry, read)

	// when
	read, err = queue.Peek()

	// then
	assertEqual(t, "Empty queue", err.Error())
	assertEqual(t, 0, len(read))
}

func TestReuseAvailableSpace(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)

	// when
	queue.Push(blob('a', 70))
	queue.Push(blob('b', 20))
	queue.Pop()
	queue.Push(blob('c', 20))

	// then
	assertEqual(t, 100, queue.Capacity())
	assertEqual(t, blob('b', 20), pop(queue))
}

func TestAllocateAdditionalSpace(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(11, 0, false)

	// when
	queue.Push([]byte("hello1"))
	queue.Push([]byte("hello2"))

	// then
	assertEqual(t, 22, queue.Capacity())
}

func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(25, 0, false)

	// when
	queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes
	queue.Push(blob('b', 6)) // additional 7 bytes
	queue.Pop()              // space freed, 4 bytes available at the beginning
	queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail

	// then
	assertEqual(t, 25, queue.Capacity())
	assertEqual(t, blob('b', 6), pop(queue))
	assertEqual(t, blob('c', 6), pop(queue))
}

func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(25, 0, false)

	// when
	queue.Push(blob('a', 3))                   // header + entry + left margin = 5 bytes
	index, _ := queue.Push(blob('b', 6))       // additional 7 bytes
	queue.Pop()                                // space freed, 4 bytes available at the beginning
	newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail

	// then
	assertEqual(t, 25, queue.Capacity())
	assertEqual(t, blob('b', 6), get(queue, index))
	assertEqual(t, blob('c', 6), get(queue, newestIndex))
}

func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)

	// when
	queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes
	queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes
	queue.Pop()               // space freed at the beginning
	queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer
	queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory

	// then
	assertEqual(t, 200, queue.Capacity())
	assertEqual(t, blob('c', 30), pop(queue))
	// empty blob fills space between tail and head,
	// created when additional memory was allocated,
	// it keeps current entries indexes unchanged
	assertEqual(t, blob(0, 39), pop(queue))
	assertEqual(t, blob('b', 10), pop(queue))
	assertEqual(t, blob('d', 40), pop(queue))
}

func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(200, 0, false)

	// when
	queue.Push(blob('a', 30))  //  header + entry + left margin = 32 bytes
	queue.Push(blob('b', 1))   // 32 + 128 + 1 = 161 bytes
	queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes
	queue.Push(blob('c', 20))  //  160 + 20 + 1 = 182
	queue.Pop()                // space freed at the beginning
	queue.Pop()                // free 2 bytes
	queue.Pop()                // free 126
	queue.Push(blob('d', 30))  // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes
	queue.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)

	// then
	assertEqual(t, 400, queue.Capacity())
	assertEqual(t, blob('d', 30), pop(queue))
	assertEqual(t, blob(0, 126), pop(queue))  //126 bytes data with 2bytes header only possible as empty entry
	assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected
	assertEqual(t, blob('e', 160), pop(queue))
}

func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(100, 0, false)

	// when
	queue.Push(blob('a', 70))                   // header + entry + left margin = 72 bytes
	index, _ := queue.Push(blob('b', 10))       // 72 + 10 + 1 = 83 bytes
	queue.Pop()                                 // space freed at the beginning
	queue.Push(blob('c', 30))                   // 31 bytes used at the beginning, tail pointer is before head pointer
	newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory

	// then
	assertEqual(t, 200, queue.Capacity())
	assertEqual(t, blob('b', 10), get(queue, index))
	assertEqual(t, blob('d', 40), get(queue, newestIndex))
}

func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(11, 0, false)

	// when
	queue.Push(blob('a', 100))
	// then
	assertEqual(t, blob('a', 100), pop(queue))
	// 224 = (101 + 11) * 2
	assertEqual(t, 224, queue.Capacity())
}

func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(21, 0, false)

	// when
	queue.Push(make([]byte, 2))
	queue.Push(make([]byte, 2))
	queue.Push(make([]byte, 100))

	// then
	queue.Pop()
	queue.Pop()
	assertEqual(t, make([]byte, 100), pop(queue))
	// 244 = (101 + 21) * 2
	assertEqual(t, 244, queue.Capacity())
}

func TestPopWholeQueue(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(13, 0, false)

	// when
	queue.Push([]byte("a"))
	queue.Push([]byte("b"))
	queue.Pop()
	queue.Pop()
	queue.Push([]byte("c"))

	// then
	assertEqual(t, 13, queue.Capacity())
	assertEqual(t, []byte("c"), pop(queue))
}

func TestGetEntryFromIndex(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(20, 0, false)

	// when
	queue.Push([]byte("a"))
	index, _ := queue.Push([]byte("b"))
	queue.Push([]byte("c"))
	result, _ := queue.Get(index)

	// then
	assertEqual(t, []byte("b"), result)
}

func TestGetEntryFromInvalidIndex(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(1, 0, false)
	queue.Push([]byte("a"))

	// when
	result, err := queue.Get(0)
	err2 := queue.CheckGet(0)

	// then
	assertEqual(t, err, err2)
	assertEqual(t, []byte(nil), result)
	assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error())
}

func TestGetEntryFromIndexOutOfRange(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(1, 0, false)
	queue.Push([]byte("a"))

	// when
	result, err := queue.Get(42)
	err2 := queue.CheckGet(42)

	// then
	assertEqual(t, err, err2)
	assertEqual(t, []byte(nil), result)
	assertEqual(t, "Index out of range", err.Error())
}

func TestGetEntryFromEmptyQueue(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(13, 0, false)

	// when
	result, err := queue.Get(1)
	err2 := queue.CheckGet(1)

	// then
	assertEqual(t, err, err2)
	assertEqual(t, []byte(nil), result)
	assertEqual(t, "Empty queue", err.Error())
}

func TestMaxSizeLimit(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(30, 50, false)

	// when
	queue.Push(blob('a', 25))
	queue.Push(blob('b', 5))
	capacity := queue.Capacity()
	_, err := queue.Push(blob('c', 20))

	// then
	assertEqual(t, 50, capacity)
	assertEqual(t, "Full queue. Maximum size limit reached.", err.Error())
	assertEqual(t, blob('a', 25), pop(queue))
	assertEqual(t, blob('b', 5), pop(queue))
}

func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(9, 20, true)

	// when
	queue.Push([]byte("aaa"))
	queue.Push([]byte("bb"))
	queue.Pop()

	// allocate more memory
	assertEqual(t, 9, queue.Capacity())
	queue.Push([]byte("c"))
	assertEqual(t, 18, queue.Capacity())

	// push after allocate
	_, err := queue.Push([]byte("d"))
	noError(t, err)
}

func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) {
	t.Parallel()

	// given
	queue := NewBytesQueue(9, 40, true)

	// when
	queue.Push([]byte("aaa"))
	queue.Push([]byte("bb"))
	_, err := queue.Pop()
	noError(t, err)

	queue.Push([]byte("c"))
	queue.Push([]byte("d"))
	queue.Push([]byte("e"))
	_, err = queue.Pop()
	noError(t, err)
	_, err = queue.Pop()
	noError(t, err)
	queue.Push([]byte("fff"))
	_, err = queue.Pop()
	noError(t, err)
}

func pop(queue *BytesQueue) []byte {
	entry, err := queue.Pop()
	if err != nil {
		panic(err)
	}
	return entry
}

func get(queue *BytesQueue, index int) []byte {
	entry, err := queue.Get(index)
	if err != nil {
		panic(err)
	}
	return entry
}

func blob(char byte, len int) []byte {
	return bytes.Repeat([]byte{char}, len)
}

func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) {
	if !objectsAreEqual(expected, actual) {
		_, file, line, _ := runtime.Caller(1)
		file = path.Base(file)
		t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+
			"expected: %T(%#v)\n"+
			"actual  : %T(%#v)\n",
			file, line, expected, expected, actual, actual), msgAndArgs...)
	}
}

func noError(t *testing.T, e error) {
	if e != nil {
		_, file, line, _ := runtime.Caller(1)
		file = path.Base(file)
		t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+
			"actual  : %T(%#v)\n", file, line, e, e))
	}
}

func objectsAreEqual(expected, actual interface{}) bool {
	if expected == nil || actual == nil {
		return expected == actual
	}

	exp, ok := expected.([]byte)
	if !ok {
		return reflect.DeepEqual(expected, actual)
	}

	act, ok := actual.([]byte)
	if !ok {
		return false
	}
	if exp == nil || act == nil {
		return exp == nil && act == nil
	}
	return bytes.Equal(exp, act)
}


================================================
FILE: server/README.md
================================================
# BigCache HTTP Server

This 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.

```bash
# cache API.
GET         /api/v1/cache/{key}
PUT         /api/v1/cache/{key}
DELETE      /api/v1/cache/{key}

# stats API.
GET         /api/v1/stats
```

The 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.

### Notes for Operators

1. No SSL support, currently.
1. No authentication, currently.
1. Stats from the stats API are not persistent.
1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise.
1. There is no replication or clustering.

### Command-line Interface

```powershell
PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h
Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe:
  -lifetime duration
        Lifetime of each cache object. (default 10m0s)
  -logfile string
        Location of the logfile.
  -max int
        Maximum amount of data in the cache in MB. (default 8192)
  -maxInWindow int
        Used only in initial memory allocation. (default 600000)
  -maxShardEntrySize int
        The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500)
  -port int
        The port to listen on. (default 9090)
  -shards int
        Number of shards for the cache. (default 1024)
  -v    Verbose logging.
  -version
        Print server version.
```

Example:

```bash
$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9090 (#0)
> PUT /api/v1/cache/example HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 4
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 4 out of 4 bytes
< HTTP/1.1 201 Created
< Date: Fri, 17 Nov 2017 03:50:07 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
$ 
$ curl -v -XGET localhost:9090/api/v1/cache/example
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9090 (#0)
> GET /api/v1/cache/example HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 17 Nov 2017 03:50:23 GMT
< Content-Length: 4
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
yay!
```

The server does log basic metrics:

```bash
$ ./server
2017/11/16 22:49:22 cache initialised.
2017/11/16 22:49:22 starting server on :9090
2017/11/16 22:50:07 stored "example" in cache.
2017/11/16 22:50:07 request took 277000ns.
2017/11/16 22:50:23 request took 9000ns.
```

### Acquiring Natively

This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build:

```bash
go build server.go
```


================================================
FILE: server/cache_handlers.go
================================================
package main

import (
	"io"
	"log"
	"net/http"
	"strings"
)

func cacheIndexHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			getCacheHandler(w, r)
		case http.MethodPut:
			putCacheHandler(w, r)
		case http.MethodDelete:
			deleteCacheHandler(w, r)
		}
	})
}

func cacheClearHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		clearCache(w, r)
	})
}

func clearCache(w http.ResponseWriter, r *http.Request) {
	if err := cache.Reset(); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("internal cache error: %s", err)
	}
	log.Println("cache is successfully cleared")
	w.WriteHeader(http.StatusOK)
}

// handles get requests.
func getCacheHandler(w http.ResponseWriter, r *http.Request) {
	target := r.URL.Path[len(cachePath):]
	if target == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("can't get a key if there is no key."))
		log.Print("empty request.")
		return
	}
	entry, err := cache.Get(target)
	if err != nil {
		errMsg := (err).Error()
		if strings.Contains(errMsg, "not found") {
			log.Print(err)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(entry)
}

func putCacheHandler(w http.ResponseWriter, r *http.Request) {
	target := r.URL.Path[len(cachePath):]
	if target == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("can't put a key if there is no key."))
		log.Print("empty request.")
		return
	}

	entry, err := io.ReadAll(r.Body)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	if err := cache.Set(target, []byte(entry)); err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	log.Printf("stored \"%s\" in cache.", target)
	w.WriteHeader(http.StatusCreated)
}

// delete cache objects.
func deleteCacheHandler(w http.ResponseWriter, r *http.Request) {
	target := r.URL.Path[len(cachePath):]
	if err := cache.Delete(target); err != nil {
		if strings.Contains((err).Error(), "not found") {
			w.WriteHeader(http.StatusNotFound)
			log.Printf("%s not found.", target)
			return
		}
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("internal cache error: %s", err)
	}
	// this is what the RFC says to use when calling DELETE.
	w.WriteHeader(http.StatusOK)
}


================================================
FILE: server/middleware.go
================================================
package main

import (
	"log"
	"net/http"
	"time"
)

// our base middleware implementation.
type service func(http.Handler) http.Handler

// chain load middleware services.
func serviceLoader(h http.Handler, svcs ...service) http.Handler {
	for _, svc := range svcs {
		h = svc(h)
	}
	return h
}

// middleware for request length metrics.
func requestMetrics(l *log.Logger) service {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			h.ServeHTTP(w, r)
			l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds())
		})
	}
}


================================================
FILE: server/middleware_test.go
================================================
package main

import (
	"bytes"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"
)

func emptyTestHandler() service {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusAccepted)
		})
	}
}

func TestServiceLoader(t *testing.T) {
	req, err := http.NewRequest("GET", "/api/v1/stats", nil)
	if err != nil {
		t.Error(err)
	}
	rr := httptest.NewRecorder()
	testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler())
	testHandlers.ServeHTTP(rr, req)
	if status := rr.Code; status != http.StatusAccepted {
		t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code)
	}
}

func TestRequestMetrics(t *testing.T) {
	var b bytes.Buffer
	logger := log.New(&b, "", log.LstdFlags)
	req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil)
	if err != nil {
		t.Error(err)
	}
	rr := httptest.NewRecorder()
	testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger))
	testHandlers.ServeHTTP(rr, req)
	targetTestString := b.String()
	if len(targetTestString) == 0 {
		t.Errorf("we are not logging request length strings.")
	}
	t.Log(targetTestString)
}


================================================
FILE: server/server.go
================================================
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/allegro/bigcache/v3"
)

const (
	// base HTTP paths.
	apiVersion  = "v1"
	apiBasePath = "/api/" + apiVersion + "/"

	// path to cache.
	cachePath      = apiBasePath + "cache/"
	statsPath      = apiBasePath + "stats"
	cacheClearPath = apiBasePath + "cache/clear"
	// server version.
	version = "1.0.0"
)

var (
	port    int
	logfile string
	ver     bool

	// cache-specific settings.
	cache  *bigcache.BigCache
	config = bigcache.Config{}
)

func init() {
	flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.")
	flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.")
	flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.")
	flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.")
	flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.")
	flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.")
	flag.IntVar(&port, "port", 9090, "The port to listen on.")
	flag.StringVar(&logfile, "logfile", "", "Location of the logfile.")
	flag.BoolVar(&ver, "version", false, "Print server version.")
}

func main() {
	flag.Parse()

	if ver {
		fmt.Printf("BigCache HTTP Server v%s", version)
		os.Exit(0)
	}

	var logger *log.Logger

	if logfile == "" {
		logger = log.New(os.Stdout, "", log.LstdFlags)
	} else {
		f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600)
		if err != nil {
			panic(err)
		}
		logger = log.New(f, "", log.LstdFlags)
	}

	var err error
	cache, err = bigcache.New(context.Background(), config)
	if err != nil {
		logger.Fatal(err)
	}

	logger.Print("cache initialised.")

	// let the middleware log.
	http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger)))
	http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger)))
	http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger)))

	logger.Printf("starting server on :%d", port)

	strPort := ":" + strconv.Itoa(port)
	log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil))
}


================================================
FILE: server/server_test.go
================================================
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/allegro/bigcache/v3"
)

const (
	testBaseString = "http://bigcache.org"
)

func testCacheSetup() {
	cache, _ = bigcache.New(context.Background(), bigcache.Config{
		Shards:             1024,
		LifeWindow:         10 * time.Minute,
		MaxEntriesInWindow: 1000 * 10 * 60,
		MaxEntrySize:       500,
		Verbose:            true,
		HardMaxCacheSize:   8192,
		OnRemove:           nil,
	})
}

func TestMain(m *testing.M) {
	testCacheSetup()
	m.Run()
}

func TestGetWithNoKey(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil)
	rr := httptest.NewRecorder()

	getCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 400 {
		t.Errorf("want: 400; got: %d", resp.StatusCode)
	}
}

func TestGetWithMissingKey(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil)
	rr := httptest.NewRecorder()

	getCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 404 {
		t.Errorf("want: 404; got: %d", resp.StatusCode)
	}
}

func TestGetKey(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil)
	rr := httptest.NewRecorder()

	// set something.
	cache.Set("getKey", []byte("123"))

	getCacheHandler(rr, req)
	resp := rr.Result()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("cannot deserialise test response: %s", err)
	}

	if string(body) != "123" {
		t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body))
	}
}

func TestPutKey(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123")))
	rr := httptest.NewRecorder()

	putCacheHandler(rr, req)

	testPutKeyResult, err := cache.Get("putKey")
	if err != nil {
		t.Errorf("error returning cache entry: %s", err)
	}

	if string(testPutKeyResult) != "123" {
		t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult))
	}
}

func TestPutEmptyKey(t *testing.T) {
	t.Parallel()

	req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123")))
	rr := httptest.NewRecorder()

	putCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 400 {
		t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode)
	}
}

func TestDeleteEmptyKey(t *testing.T) {
	t.Parallel()

	req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123")))
	rr := httptest.NewRecorder()

	deleteCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 404 {
		t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode)
	}
}

func TestDeleteInvalidKey(t *testing.T) {
	t.Parallel()

	req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123")))
	rr := httptest.NewRecorder()

	deleteCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 404 {
		t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode)
	}
}

func TestDeleteKey(t *testing.T) {
	t.Parallel()

	req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123")))
	rr := httptest.NewRecorder()

	if err := cache.Set("testDeleteKey", []byte("123")); err != nil {
		t.Errorf("can't set key for testing. %s", err)
	}

	deleteCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 200 {
		t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode)
	}
}

func TestClearCache(t *testing.T) {
	t.Parallel()

	putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123")))
	putResponseRecorder := httptest.NewRecorder()

	putCacheHandler(putResponseRecorder, putRequest)

	requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil)
	rr := httptest.NewRecorder()

	if err := cache.Set("testDeleteKey", []byte("123")); err != nil {
		t.Errorf("can't set key for testing. %s", err)
	}

	clearCache(rr, requestClear)
	resp := rr.Result()

	if resp.StatusCode != 200 {
		t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode)
	}
}
func TestGetStats(t *testing.T) {
	t.Parallel()
	var testStats bigcache.Stats

	req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil)
	rr := httptest.NewRecorder()

	// manually enter a key so there are some stats. get it so there's at least 1 hit.
	if err := cache.Set("incrementStats", []byte("123")); err != nil {
		t.Errorf("error setting cache value. error %s", err)
	}
	// it's okay if this fails, since we'll catch it downstream.
	if _, err := cache.Get("incrementStats"); err != nil {
		t.Errorf("can't find incrementStats. error: %s", err)
	}

	getCacheStatsHandler(rr, req)
	resp := rr.Result()

	if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil {
		t.Errorf("error decoding cache stats. error: %s", err)
	}

	if testStats.Hits == 0 {
		t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.")
	}
}

func TestGetStatsIndex(t *testing.T) {
	t.Parallel()
	var testStats bigcache.Stats

	getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil)
	putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil)
	rr := httptest.NewRecorder()

	// manually enter a key so there are some stats. get it so there's at least 1 hit.
	if err := cache.Set("incrementStats", []byte("123")); err != nil {
		t.Errorf("error setting cache value. error %s", err)
	}
	// it's okay if this fails, since we'll catch it downstream.
	if _, err := cache.Get("incrementStats"); err != nil {
		t.Errorf("can't find incrementStats. error: %s", err)
	}

	testHandlers := statsIndexHandler()
	testHandlers.ServeHTTP(rr, getreq)
	resp := rr.Result()

	if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil {
		t.Errorf("error decoding cache stats. error: %s", err)
	}

	if testStats.Hits == 0 {
		t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.")
	}

	testHandlers = statsIndexHandler()
	testHandlers.ServeHTTP(rr, putreq)
	resp = rr.Result()
	_, err := io.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("cannot deserialise test response: %s", err)
	}
}

func TestCacheIndexHandler(t *testing.T) {
	getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil)
	putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123")))
	delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123")))

	getrr := httptest.NewRecorder()
	putrr := httptest.NewRecorder()
	delrr := httptest.NewRecorder()
	testHandlers := cacheIndexHandler()

	testHandlers.ServeHTTP(putrr, putreq)
	resp := putrr.Result()
	if resp.StatusCode != 201 {
		t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode)
	}
	testHandlers.ServeHTTP(getrr, getreq)
	resp = getrr.Result()
	if resp.StatusCode != 200 {
		t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode)
	}
	testHandlers.ServeHTTP(delrr, delreq)
	resp = delrr.Result()
	if resp.StatusCode != 200 {
		t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode)
	}
}

func TestInvalidPutWhenExceedShardCap(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024)))
	rr := httptest.NewRecorder()

	putCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 500 {
		t.Errorf("want: 500; got: %d", resp.StatusCode)
	}
}

func TestInvalidPutWhenReading(t *testing.T) {
	t.Parallel()
	req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0))
	rr := httptest.NewRecorder()

	putCacheHandler(rr, req)
	resp := rr.Result()

	if resp.StatusCode != 500 {
		t.Errorf("want: 500; got: %d", resp.StatusCode)
	}
}

type errReader int

func (errReader) Read([]byte) (int, error) {
	return 0, errors.New("test read error")
}


================================================
FILE: server/stats_handler.go
================================================
package main

import (
	"encoding/json"
	"log"
	"net/http"
)

// index for stats handle
func statsIndexHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			getCacheStatsHandler(w, r)
		default:
			w.WriteHeader(http.StatusMethodNotAllowed)
		}
	})
}

// returns the cache's statistics.
func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) {
	target, err := json.Marshal(cache.Stats())
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("cannot marshal cache stats. error: %s", err)
		return
	}
	// since we're sending a struct, make it easy for consumers to interface.
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(target)
}


================================================
FILE: shard.go
================================================
package bigcache

import (
	"errors"
	"sync"
	"sync/atomic"

	"github.com/allegro/bigcache/v3/queue"
)

type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason)

// Metadata contains information of a specific entry
type Metadata struct {
	RequestCount uint32
}

type cacheShard struct {
	hashmap     map[uint64]uint64
	entries     queue.BytesQueue
	lock        sync.RWMutex
	entryBuffer []byte
	onRemove    onRemoveCallback

	isVerbose    bool
	statsEnabled bool
	logger       Logger
	clock        clock
	lifeWindow   uint64

	hashmapStats map[uint64]uint32
	stats        Stats
	cleanEnabled bool
}

func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) {
	currentTime := uint64(s.clock.Epoch())
	s.lock.RLock()
	wrappedEntry, err := s.getWrappedEntry(hashedKey)
	if err != nil {
		s.lock.RUnlock()
		return nil, resp, err
	}
	if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey {
		s.lock.RUnlock()
		s.collision()
		if s.isVerbose {
			s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey)
		}
		return nil, resp, ErrEntryNotFound
	}

	entry = readEntry(wrappedEntry)
	if s.isExpired(wrappedEntry, currentTime) {
		resp.EntryStatus = Expired
	}
	s.lock.RUnlock()
	s.hit(hashedKey)
	return entry, resp, nil
}

func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) {
	s.lock.RLock()
	wrappedEntry, err := s.getWrappedEntry(hashedKey)
	if err != nil {
		s.lock.RUnlock()
		return nil, err
	}
	if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey {
		s.lock.RUnlock()
		s.collision()
		if s.isVerbose {
			s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey)
		}
		return nil, ErrEntryNotFound
	}
	entry := readEntry(wrappedEntry)
	s.lock.RUnlock()
	s.hit(hashedKey)

	return entry, nil
}

func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) {
	itemIndex := s.hashmap[hashedKey]

	if itemIndex == 0 {
		s.miss()
		return nil, ErrEntryNotFound
	}

	wrappedEntry, err := s.entries.Get(int(itemIndex))
	if err != nil {
		s.miss()
		return nil, err
	}

	return wrappedEntry, err
}

func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) {
	wrappedEntry, err := s.getWrappedEntry(hashedKey)
	if err != nil {
		return nil, err
	}

	if !compareKeyFromEntry(wrappedEntry, key) {
		s.collision()
		if s.isVerbose {
			s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey)
		}

		return nil, ErrEntryNotFound
	}
	s.hitWithoutLock(hashedKey)

	return wrappedEntry, nil
}

func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error {
	currentTimestamp := uint64(s.clock.Epoch())

	s.lock.Lock()

	if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 {
		if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil {
			resetHashFromEntry(previousEntry)
			//remove hashkey
			delete(s.hashmap, hashedKey)
		}
	}

	if !s.cleanEnabled {
		if oldestEntry, err := s.entries.Peek(); err == nil {
			s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)
		}
	}

	w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer)

	for {
		if index, err := s.entries.Push(w); err == nil {
			s.hashmap[hashedKey] = uint64(index)
			s.lock.Unlock()
			return nil
		}
		if s.removeOldestEntry(NoSpace) != nil {
			s.lock.Unlock()
			return errors.New("entry is bigger than max shard size")
		}
	}
}

func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error {
	currentTimestamp := uint64(s.clock.Epoch())

	if !s.cleanEnabled {
		if oldestEntry, err := s.entries.Peek(); err == nil {
			s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)
		}
	}

	w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer)

	for {
		if index, err := s.entries.Push(w); err == nil {
			s.hashmap[hashedKey] = uint64(index)
			return nil
		}
		if s.removeOldestEntry(NoSpace) != nil {
			return errors.New("entry is bigger than max shard size")
		}
	}
}

func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error {
	if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 {
		if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil {
			resetHashFromEntry(previousEntry)
		}
	}

	if !s.cleanEnabled {
		if oldestEntry, err := s.entries.Peek(); err == nil {
			s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)
		}
	}

	for {
		if index, err := s.entries.Push(w); err == nil {
			s.hashmap[hashedKey] = uint64(index)
			return nil
		}
		if s.removeOldestEntry(NoSpace) != nil {
			return errors.New("entry is bigger than max shard size")
		}
	}
}

func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error {
	s.lock.Lock()
	wrappedEntry, err := s.getValidWrapEntry(key, hashedKey)

	if err == ErrEntryNotFound {
		err = s.addNewWithoutLock(key, hashedKey, entry)
		s.lock.Unlock()
		return err
	}
	if err != nil {
		s.lock.Unlock()
		return err
	}

	currentTimestamp := uint64(s.clock.Epoch())

	w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer)

	err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey)
	s.lock.Unlock()

	return err
}

func (s *cacheShard) del(hashedKey uint64) error {
	// Optimistic pre-check using only readlock
	s.lock.RLock()
	{
		itemIndex := s.hashmap[hashedKey]

		if itemIndex == 0 {
			s.lock.RUnlock()
			s.delmiss()
			return ErrEntryNotFound
		}

		if err := s.entries.CheckGet(int(itemIndex)); err != nil {
			s.lock.RUnlock()
			s.delmiss()
			return err
		}
	}
	s.lock.RUnlock()

	s.lock.Lock()
	{
		// After obtaining the writelock, we need to read the same again,
		// since the data delivered earlier may be stale now
		itemIndex := s.hashmap[hashedKey]

		if itemIndex == 0 {
			s.lock.Unlock()
			s.delmiss()
			return ErrEntryNotFound
		}

		wrappedEntry, err := s.entries.Get(int(itemIndex))
		if err != nil {
			s.lock.Unlock()
			s.delmiss()
			return err
		}

		delete(s.hashmap, hashedKey)
		s.onRemove(wrappedEntry, Deleted)
		if s.statsEnabled {
			delete(s.hashmapStats, hashedKey)
		}
		resetHashFromEntry(wrappedEntry)
	}
	s.lock.Unlock()

	s.delhit()
	return nil
}

func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
	if s.isExpired(oldestEntry, currentTimestamp) {
		evict(Expired)
		return true
	}
	return false
}

func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool {
	oldestTimestamp := readTimestampFromEntry(oldestEntry)
	if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits;
		return false
	}
	return currentTimestamp-oldestTimestamp >= s.lifeWindow
}

func (s *cacheShard) cleanUp(currentTimestamp uint64) {
	s.lock.Lock()
	for {
		if oldestEntry, err := s.entries.Peek(); err != nil {
			break
		} else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted {
			break
		}
	}
	s.lock.Unlock()
}

func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) {
	s.lock.RLock()

	entry, err := s.getWrappedEntry(hashedKey)
	// copy entry
	newEntry := make([]byte, len(entry))
	copy(newEntry, entry)

	s.lock.RUnlock()

	return newEntry, err
}

func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) {
	s.lock.RLock()
	keys = make([]uint64, len(s.hashmap))

	for key := range s.hashmap {
		keys[next] = key
		next++
	}

	s.lock.RUnlock()
	return keys, next
}

func (s *cacheShard) removeOldestEntry(reason RemoveReason) error {
	oldest, err := s.entries.Pop()
	if err == nil {
		hash := readHashFromEntry(oldest)
		if hash == 0 {
			// entry has been explicitly deleted with resetHashFromEntry, ignore
			return nil
		}
		delete(s.hashmap, hash)
		s.onRemove(oldest, reason)
		if s.statsEnabled {
			delete(s.hashmapStats, hash)
		}
		return nil
	}
	return err
}

func (s *cacheShard) reset(config Config) {
	s.lock.Lock()
	s.hashmap = make(map[uint64]uint64, config.initialShardSize())
	s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes)
	s.entries.Reset()
	s.lock.Unlock()
}

func (s *cacheShard) resetStats() {
	s.lock.Lock()
	s.stats = Stats{}
	s.lock.Unlock()
}

func (s *cacheShard) len() int {
	s.lock.RLock()
	res := len(s.hashmap)
	s.lock.RUnlock()
	return res
}

func (s *cacheShard) capacity() int {
	s.lock.RLock()
	res := s.entries.Capacity()
	s.lock.RUnlock()
	return res
}

func (s *cacheShard) getStats() Stats {
	var stats = Stats{
		Hits:       atomic.LoadInt64(&s.stats.Hits),
		Misses:     atomic.LoadInt64(&s.stats.Misses),
		DelHits:    atomic.LoadInt64(&s.stats.DelHits),
		DelMisses:  atomic.LoadInt64(&s.stats.DelMisses),
		Collisions: atomic.LoadInt64(&s.stats.Collisions),
	}
	return stats
}

func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata {
	s.lock.RLock()
	c := s.hashmapStats[key]
	s.lock.RUnlock()
	return Metadata{
		RequestCount: c,
	}
}

func (s *cacheShard) getKeyMetadata(key uint64) Metadata {
	return Metadata{
		RequestCount: s.hashmapStats[key],
	}
}

func (s *cacheShard) hit(key uint64) {
	atomic.AddInt64(&s.stats.Hits, 1)
	if s.statsEnabled {
		s.lock.Lock()
		s.hashmapStats[key]++
		s.lock.Unlock()
	}
}

func (s *cacheShard) hitWithoutLock(key uint64) {
	atomic.AddInt64(&s.stats.Hits, 1)
	if s.statsEnabled {
		s.hashmapStats[key]++
	}
}

func (s *cacheShard) miss() {
	atomic.AddInt64(&s.stats.Misses, 1)
}

func (s *cacheShard) delhit() {
	atomic.AddInt64(&s.stats.DelHits, 1)
}

func (s *cacheShard) delmiss() {
	atomic.AddInt64(&s.stats.DelMisses, 1)
}

func (s *cacheShard) collision() {
	atomic.AddInt64(&s.stats.Collisions, 1)
}

func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard {
	bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize
	maximumShardSizeInBytes := config.maximumShardSizeInBytes()
	if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes {
		bytesQueueInitialCapacity = maximumShardSizeInBytes
	}
	var hashmapStatsCapacity int
	if config.StatsEnabled {
		hashmapStatsCapacity = config.initialShardSize()
	}
	return &cacheShard{
		hashmap:      make(map[uint64]uint64, config.initialShardSize()),
		hashmapStats: make(map[uint64]uint32, hashmapStatsCapacity),
		entries:      *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose),
		entryBuffer:  make([]byte, config.MaxEntrySize+headersSizeInBytes),
		onRemove:     callback,

		isVerbose:    config.Verbose,
		logger:       newLogger(config.Logger),
		clock:        clock,
		lifeWindow:   uint64(config.LifeWindow.Seconds()),
		statsEnabled: config.StatsEnabled,
		cleanEnabled: config.CleanWindow > 0,
	}
}


================================================
FILE: stats.go
================================================
package bigcache

// Stats stores cache statistics
type Stats struct {
	// Hits is a number of successfully found keys
	Hits int64 `json:"hits"`
	// Misses is a number of not found keys
	Misses int64 `json:"misses"`
	// DelHits is a number of successfully deleted keys
	DelHits int64 `json:"delete_hits"`
	// DelMisses is a number of not deleted keys
	DelMisses int64 `json:"delete_misses"`
	// Collisions is a number of happened key-collisions
	Collisions int64 `json:"collisions"`
}


================================================
FILE: utils.go
================================================
package bigcache

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func convertMBToBytes(value int) int {
	return value * 1024 * 1024
}

func isPowerOfTwo(number int) bool {
	return (number != 0) && (number&(number-1)) == 0
}
Download .txt
gitextract_z3iltele/

├── .codecov.yml
├── .github/
│   ├── CODEOWNERS
│   ├── ISSUE_TEMPLATE/
│   │   └── issue_template.md
│   ├── dependabot.yml
│   ├── release-drafter.yml
│   └── workflows/
│       ├── build.yml
│       └── release-management.yml
├── .gitignore
├── .golangci.yaml
├── LICENSE
├── README.md
├── assert_test.go
├── bigcache.go
├── bigcache_bench_test.go
├── bigcache_test.go
├── bytes.go
├── bytes_appengine.go
├── clock.go
├── config.go
├── encoding.go
├── encoding_test.go
├── entry_not_found_error.go
├── examples_test.go
├── fnv.go
├── fnv_bench_test.go
├── fnv_test.go
├── go.mod
├── go.sum
├── hash.go
├── hash_test.go
├── iterator.go
├── iterator_test.go
├── logger.go
├── queue/
│   ├── bytes_queue.go
│   └── bytes_queue_test.go
├── server/
│   ├── README.md
│   ├── cache_handlers.go
│   ├── middleware.go
│   ├── middleware_test.go
│   ├── server.go
│   ├── server_test.go
│   └── stats_handler.go
├── shard.go
├── stats.go
└── utils.go
Download .txt
SYMBOL INDEX (286 symbols across 30 files)

FILE: assert_test.go
  function assertEqual (line 12) | func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...
  function noError (line 23) | func noError(t *testing.T, e error) {
  function objectsAreEqual (line 32) | func objectsAreEqual(expected, actual interface{}) bool {

FILE: bigcache.go
  constant minimumEntriesInShard (line 10) | minimumEntriesInShard = 10
  type BigCache (line 16) | type BigCache struct
    method Close (line 130) | func (c *BigCache) Close() error {
    method Get (line 138) | func (c *BigCache) Get(key string) ([]byte, error) {
    method GetWithInfo (line 147) | func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) {
    method Set (line 154) | func (c *BigCache) Set(key string, entry []byte) error {
    method Append (line 163) | func (c *BigCache) Append(key string, entry []byte) error {
    method Delete (line 170) | func (c *BigCache) Delete(key string) error {
    method Reset (line 177) | func (c *BigCache) Reset() error {
    method ResetStats (line 185) | func (c *BigCache) ResetStats() error {
    method Len (line 193) | func (c *BigCache) Len() int {
    method Capacity (line 202) | func (c *BigCache) Capacity() int {
    method Stats (line 211) | func (c *BigCache) Stats() Stats {
    method KeyMetadata (line 225) | func (c *BigCache) KeyMetadata(key string) Metadata {
    method Iterator (line 232) | func (c *BigCache) Iterator() *EntryInfoIterator {
    method onEvict (line 236) | func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64...
    method cleanUp (line 248) | func (c *BigCache) cleanUp(currentTimestamp uint64) {
    method getShard (line 254) | func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) {
    method providedOnRemove (line 258) | func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason Remove...
    method providedOnRemoveWithReason (line 262) | func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, rea...
    method notProvidedOnRemove (line 268) | func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason Rem...
    method providedOnRemoveWithMetadata (line 271) | func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, r...
  type Response (line 27) | type Response struct
  type RemoveReason (line 32) | type RemoveReason
  constant _ (line 35) | _ RemoveReason = iota
  constant Expired (line 37) | Expired
  constant NoSpace (line 40) | NoSpace
  constant Deleted (line 42) | Deleted
  function New (line 46) | func New(ctx context.Context, config Config) (*BigCache, error) {
  function NewBigCache (line 55) | func NewBigCache(config Config) (*BigCache, error) {
  function newBigCache (line 59) | func newBigCache(ctx context.Context, config Config, clock clock) (*BigC...

FILE: bigcache_bench_test.go
  function BenchmarkWriteToCacheWith1Shard (line 14) | func BenchmarkWriteToCacheWith1Shard(b *testing.B) {
  function BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard (line 18) | func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) {
  function BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard (line 34) | func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing...
  function BenchmarkWriteToCache (line 49) | func BenchmarkWriteToCache(b *testing.B) {
  function BenchmarkAppendToCache (line 56) | func BenchmarkAppendToCache(b *testing.B) {
  function BenchmarkReadFromCache (line 64) | func BenchmarkReadFromCache(b *testing.B) {
  function BenchmarkReadFromCacheWithInfo (line 72) | func BenchmarkReadFromCacheWithInfo(b *testing.B) {
  function BenchmarkIterateOverCache (line 79) | func BenchmarkIterateOverCache(b *testing.B) {
  function BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize (line 112) | func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing...
  function BenchmarkReadFromCacheNonExistentKeys (line 116) | func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) {
  function writeToCache (line 124) | func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, re...
  function appendToCache (line 145) | func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, r...
  function readFromCache (line 169) | func readFromCache(b *testing.B, shards int, info bool) {
  function readFromCacheNonExistentKeys (line 194) | func readFromCacheNonExistentKeys(b *testing.B, shards int) {

FILE: bigcache_test.go
  function TestWriteAndGetOnCache (line 16) | func TestWriteAndGetOnCache(t *testing.T) {
  function TestAppendAndGetOnCache (line 32) | func TestAppendAndGetOnCache(t *testing.T) {
  function TestAppendRandomly (line 82) | func TestAppendRandomly(t *testing.T) {
  function TestAppendCollision (line 145) | func TestAppendCollision(t *testing.T) {
  function TestConstructCacheWithDefaultHasher (line 178) | func TestConstructCacheWithDefaultHasher(t *testing.T) {
  function TestNewBigcacheValidation (line 193) | func TestNewBigcacheValidation(t *testing.T) {
  function TestEntryNotFound (line 226) | func TestEntryNotFound(t *testing.T) {
  function TestTimingEviction (line 244) | func TestTimingEviction(t *testing.T) {
  function TestTimingEvictionShouldEvictOnlyFromUpdatedShard (line 274) | func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) {
  function TestCleanShouldEvictAll (line 297) | func TestCleanShouldEvictAll(t *testing.T) {
  function TestOnRemoveCallback (line 319) | func TestOnRemoveCallback(t *testing.T) {
  function TestOnRemoveWithReasonCallback (line 353) | func TestOnRemoveWithReasonCallback(t *testing.T) {
  function TestOnRemoveFilter (line 382) | func TestOnRemoveFilter(t *testing.T) {
  function TestOnRemoveFilterExpired (line 416) | func TestOnRemoveFilterExpired(t *testing.T) {
  function TestOnRemoveGetEntryStats (line 477) | func TestOnRemoveGetEntryStats(t *testing.T) {
  function TestCacheLen (line 510) | func TestCacheLen(t *testing.T) {
  function TestCacheCapacity (line 531) | func TestCacheCapacity(t *testing.T) {
  function TestCacheInitialCapacity (line 553) | func TestCacheInitialCapacity(t *testing.T) {
  function TestRemoveEntriesWhenShardIsFull (line 580) | func TestRemoveEntriesWhenShardIsFull(t *testing.T) {
  function TestCacheStats (line 607) | func TestCacheStats(t *testing.T) {
  function TestCacheEntryStats (line 648) | func TestCacheEntryStats(t *testing.T) {
  function TestCacheRestStats (line 672) | func TestCacheRestStats(t *testing.T) {
  function TestCacheDel (line 721) | func TestCacheDel(t *testing.T) {
  function TestCacheDelRandomly (line 744) | func TestCacheDelRandomly(t *testing.T) {
  function TestWriteAndReadParallelSameKeyWithStats (line 805) | func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) {
  function TestCacheReset (line 838) | func TestCacheReset(t *testing.T) {
  function TestIterateOnResetCache (line 873) | func TestIterateOnResetCache(t *testing.T) {
  function TestGetOnResetCache (line 897) | func TestGetOnResetCache(t *testing.T) {
  function TestEntryUpdate (line 923) | func TestEntryUpdate(t *testing.T) {
  function TestOldestEntryDeletionWhenMaxCacheSizeIsReached (line 947) | func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) {
  function TestRetrievingEntryShouldCopy (line 974) | func TestRetrievingEntryShouldCopy(t *testing.T) {
  function TestEntryBiggerThanMaxShardSizeError (line 1000) | func TestEntryBiggerThanMaxShardSizeError(t *testing.T) {
  function TestHashCollision (line 1019) | func TestHashCollision(t *testing.T) {
  function TestNilValueCaching (line 1061) | func TestNilValueCaching(t *testing.T) {
  function TestClosing (line 1098) | func TestClosing(t *testing.T) {
  function TestEntryNotPresent (line 1122) | func TestEntryNotPresent(t *testing.T) {
  function TestBigCache_GetWithInfo (line 1143) | func TestBigCache_GetWithInfo(t *testing.T) {
  function TestBigCache_GetWithInfoCollision (line 1203) | func TestBigCache_GetWithInfoCollision(t *testing.T) {
  type mockedLogger (line 1236) | type mockedLogger struct
    method Printf (line 1241) | func (ml *mockedLogger) Printf(format string, v ...interface{}) {
  type mockedClock (line 1246) | type mockedClock struct
    method Epoch (line 1250) | func (mc *mockedClock) Epoch() int64 {
    method set (line 1254) | func (mc *mockedClock) set(value int64) {
  function blob (line 1258) | func blob(char byte, len int) []byte {
  function TestCache_SetWithoutCleanWindow (line 1262) | func TestCache_SetWithoutCleanWindow(t *testing.T) {
  function TestCache_RepeatedSetWithBiggerEntry (line 1276) | func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) {
  function TestBigCache_allocateAdditionalMemoryLeadPanic (line 1318) | func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) {
  function TestRemoveNonExpiredData (line 1353) | func TestRemoveNonExpiredData(t *testing.T) {

FILE: bytes.go
  function bytesToString (line 10) | func bytesToString(b []byte) string {

FILE: bytes_appengine.go
  function bytesToString (line 5) | func bytesToString(b []byte) string {

FILE: clock.go
  type clock (line 5) | type clock interface
  type systemClock (line 9) | type systemClock struct
    method Epoch (line 12) | func (c systemClock) Epoch() int64 {

FILE: config.go
  type Config (line 6) | type Config struct
    method initialShardSize (line 73) | func (c Config) initialShardSize() int {
    method maximumShardSizeInBytes (line 78) | func (c Config) maximumShardSizeInBytes() int {
    method OnRemoveFilterSet (line 90) | func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config {
  function DefaultConfig (line 57) | func DefaultConfig(eviction time.Duration) Config {

FILE: encoding.go
  constant timestampSizeInBytes (line 8) | timestampSizeInBytes = 8
  constant hashSizeInBytes (line 9) | hashSizeInBytes      = 8
  constant keySizeInBytes (line 10) | keySizeInBytes       = 2
  constant headersSizeInBytes (line 11) | headersSizeInBytes   = timestampSizeInBytes + hashSizeInBytes + keySizeI...
  function wrapEntry (line 14) | func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, ...
  function appendToWrappedEntry (line 32) | func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry [...
  function readEntry (line 47) | func readEntry(data []byte) []byte {
  function readTimestampFromEntry (line 57) | func readTimestampFromEntry(data []byte) uint64 {
  function readKeyFromEntry (line 61) | func readKeyFromEntry(data []byte) string {
  function compareKeyFromEntry (line 71) | func compareKeyFromEntry(data []byte, key string) bool {
  function readHashFromEntry (line 77) | func readHashFromEntry(data []byte) uint64 {
  function resetHashFromEntry (line 81) | func resetHashFromEntry(data []byte) {

FILE: encoding_test.go
  function TestEncodeDecode (line 8) | func TestEncodeDecode(t *testing.T) {
  function TestAllocateBiggerBuffer (line 27) | func TestAllocateBiggerBuffer(t *testing.T) {

FILE: examples_test.go
  function Example (line 12) | func Example() {
  function Example_custom (line 22) | func Example_custom() {

FILE: fnv.go
  function newDefaultHasher (line 6) | func newDefaultHasher() Hasher {
  type fnv64a (line 10) | type fnv64a struct
    method Sum64 (line 20) | func (f fnv64a) Sum64(key string) uint64 {
  constant offset64 (line 14) | offset64 = 14695981039346656037
  constant prime64 (line 16) | prime64 = 1099511628211

FILE: fnv_bench_test.go
  function BenchmarkFnvHashSum64 (line 7) | func BenchmarkFnvHashSum64(b *testing.B) {
  function BenchmarkFnvHashStdLibSum64 (line 14) | func BenchmarkFnvHashStdLibSum64(b *testing.B) {

FILE: fnv_test.go
  type testCase (line 8) | type testCase struct
  function TestFnvHashSum64 (line 21) | func TestFnvHashSum64(t *testing.T) {
  function stdLibFnvSum64 (line 31) | func stdLibFnvSum64(key string) uint64 {

FILE: hash.go
  type Hasher (line 6) | type Hasher interface

FILE: hash_test.go
  type hashStub (line 3) | type hashStub
    method Sum64 (line 5) | func (stub hashStub) Sum64(_ string) uint64 {

FILE: iterator.go
  type iteratorError (line 7) | type iteratorError
    method Error (line 9) | func (e iteratorError) Error() string {
  constant ErrInvalidIteratorState (line 14) | ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. U...
  constant ErrCannotRetrieveEntry (line 17) | ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from ca...
  type EntryInfo (line 22) | type EntryInfo struct
    method Key (line 31) | func (e EntryInfo) Key() string {
    method Hash (line 36) | func (e EntryInfo) Hash() uint64 {
    method Timestamp (line 41) | func (e EntryInfo) Timestamp() uint64 {
    method Value (line 46) | func (e EntryInfo) Value() []byte {
  type EntryInfoIterator (line 51) | type EntryInfoIterator struct
    method SetNext (line 63) | func (it *EntryInfoIterator) SetNext() bool {
    method setCurrentEntry (line 103) | func (it *EntryInfoIterator) setCurrentEntry() bool {
    method Value (line 140) | func (it *EntryInfoIterator) Value() (EntryInfo, error) {
  function newIterator (line 127) | func newIterator(cache *BigCache) *EntryInfoIterator {

FILE: iterator_test.go
  function TestEntriesIterator (line 14) | func TestEntriesIterator(t *testing.T) {
  function TestEntriesIteratorWithMostShardsEmpty (line 47) | func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) {
  function TestEntriesIteratorWithConcurrentUpdate (line 79) | func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) {
  function TestEntriesIteratorWithAllShardsEmpty (line 121) | func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) {
  function TestEntriesIteratorInInvalidState (line 141) | func TestEntriesIteratorInInvalidState(t *testing.T) {
  function TestEntriesIteratorParallelAdd (line 161) | func TestEntriesIteratorParallelAdd(t *testing.T) {
  function TestParallelSetAndIteration (line 190) | func TestParallelSetAndIteration(t *testing.T) {

FILE: logger.go
  type Logger (line 9) | type Logger interface
  function DefaultLogger (line 20) | func DefaultLogger() *log.Logger {
  function newLogger (line 24) | func newLogger(custom Logger) Logger {

FILE: queue/bytes_queue.go
  constant minimumHeaderSize (line 11) | minimumHeaderSize = 17
  constant leftMarginIndex (line 13) | leftMarginIndex = 1
  type BytesQueue (line 25) | type BytesQueue struct
    method Reset (line 78) | func (q *BytesQueue) Reset() {
    method Push (line 89) | func (q *BytesQueue) Push(data []byte) (int, error) {
    method allocateAdditionalMemory (line 109) | func (q *BytesQueue) allocateAdditionalMemory(minimum int) {
    method push (line 143) | func (q *BytesQueue) push(data []byte, len int) {
    method copy (line 159) | func (q *BytesQueue) copy(data []byte, len int) {
    method Pop (line 164) | func (q *BytesQueue) Pop() ([]byte, error) {
    method Peek (line 187) | func (q *BytesQueue) Peek() ([]byte, error) {
    method Get (line 193) | func (q *BytesQueue) Get(index int) ([]byte, error) {
    method CheckGet (line 199) | func (q *BytesQueue) CheckGet(index int) error {
    method Capacity (line 204) | func (q *BytesQueue) Capacity() int {
    method Len (line 209) | func (q *BytesQueue) Len() int {
    method peekCheckErr (line 219) | func (q *BytesQueue) peekCheckErr(index int) error {
    method peek (line 236) | func (q *BytesQueue) peek(index int) ([]byte, int, error) {
    method canInsertAfterTail (line 247) | func (q *BytesQueue) canInsertAfterTail(need int) bool {
    method canInsertBeforeHead (line 262) | func (q *BytesQueue) canInsertBeforeHead(need int) bool {
  type queueError (line 38) | type queueError struct
    method Error (line 214) | func (e *queueError) Error() string {
  function getNeededSize (line 43) | func getNeededSize(length int) int {
  function NewBytesQueue (line 64) | func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQu...

FILE: queue/bytes_queue_test.go
  function TestPushAndPop (line 12) | func TestPushAndPop(t *testing.T) {
  function TestLen (line 32) | func TestLen(t *testing.T) {
  function TestPeek (line 47) | func TestPeek(t *testing.T) {
  function TestResetFullQueue (line 74) | func TestResetFullQueue(t *testing.T) {
  function TestReset (line 100) | func TestReset(t *testing.T) {
  function TestReuseAvailableSpace (line 136) | func TestReuseAvailableSpace(t *testing.T) {
  function TestAllocateAdditionalSpace (line 153) | func TestAllocateAdditionalSpace(t *testing.T) {
  function TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail (line 167) | func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereH...
  function TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail (line 185) | func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHead...
  function TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead (line 203) | func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereT...
  function TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128 (line 227) | func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereT...
  function TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead (line 252) | func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTail...
  function TestAllocateAdditionalSpaceForValueBiggerThanInitQueue (line 271) | func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) {
  function TestAllocateAdditionalSpaceForValueBiggerThanQueue (line 285) | func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) {
  function TestPopWholeQueue (line 304) | func TestPopWholeQueue(t *testing.T) {
  function TestGetEntryFromIndex (line 322) | func TestGetEntryFromIndex(t *testing.T) {
  function TestGetEntryFromInvalidIndex (line 338) | func TestGetEntryFromInvalidIndex(t *testing.T) {
  function TestGetEntryFromIndexOutOfRange (line 355) | func TestGetEntryFromIndexOutOfRange(t *testing.T) {
  function TestGetEntryFromEmptyQueue (line 372) | func TestGetEntryFromEmptyQueue(t *testing.T) {
  function TestMaxSizeLimit (line 388) | func TestMaxSizeLimit(t *testing.T) {
  function TestPushEntryAfterAllocateAdditionMemory (line 407) | func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) {
  function TestPushEntryAfterAllocateAdditionMemoryInFull (line 428) | func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) {
  function pop (line 452) | func pop(queue *BytesQueue) []byte {
  function get (line 460) | func get(queue *BytesQueue, index int) []byte {
  function blob (line 468) | func blob(char byte, len int) []byte {
  function assertEqual (line 472) | func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...
  function noError (line 483) | func noError(t *testing.T, e error) {
  function objectsAreEqual (line 492) | func objectsAreEqual(expected, actual interface{}) bool {

FILE: server/cache_handlers.go
  function cacheIndexHandler (line 10) | func cacheIndexHandler() http.Handler {
  function cacheClearHandler (line 23) | func cacheClearHandler() http.Handler {
  function clearCache (line 29) | func clearCache(w http.ResponseWriter, r *http.Request) {
  function getCacheHandler (line 39) | func getCacheHandler(w http.ResponseWriter, r *http.Request) {
  function putCacheHandler (line 62) | func putCacheHandler(w http.ResponseWriter, r *http.Request) {
  function deleteCacheHandler (line 88) | func deleteCacheHandler(w http.ResponseWriter, r *http.Request) {

FILE: server/middleware.go
  type service (line 10) | type service
  function serviceLoader (line 13) | func serviceLoader(h http.Handler, svcs ...service) http.Handler {
  function requestMetrics (line 21) | func requestMetrics(l *log.Logger) service {

FILE: server/middleware_test.go
  function emptyTestHandler (line 11) | func emptyTestHandler() service {
  function TestServiceLoader (line 19) | func TestServiceLoader(t *testing.T) {
  function TestRequestMetrics (line 32) | func TestRequestMetrics(t *testing.T) {

FILE: server/server.go
  constant apiVersion (line 17) | apiVersion  = "v1"
  constant apiBasePath (line 18) | apiBasePath = "/api/" + apiVersion + "/"
  constant cachePath (line 21) | cachePath      = apiBasePath + "cache/"
  constant statsPath (line 22) | statsPath      = apiBasePath + "stats"
  constant cacheClearPath (line 23) | cacheClearPath = apiBasePath + "cache/clear"
  constant version (line 25) | version = "1.0.0"
  function init (line 38) | func init() {
  function main (line 50) | func main() {

FILE: server/server_test.go
  constant testBaseString (line 17) | testBaseString = "http://bigcache.org"
  function testCacheSetup (line 20) | func testCacheSetup() {
  function TestMain (line 32) | func TestMain(m *testing.M) {
  function TestGetWithNoKey (line 37) | func TestGetWithNoKey(t *testing.T) {
  function TestGetWithMissingKey (line 50) | func TestGetWithMissingKey(t *testing.T) {
  function TestGetKey (line 63) | func TestGetKey(t *testing.T) {
  function TestPutKey (line 84) | func TestPutKey(t *testing.T) {
  function TestPutEmptyKey (line 101) | func TestPutEmptyKey(t *testing.T) {
  function TestDeleteEmptyKey (line 115) | func TestDeleteEmptyKey(t *testing.T) {
  function TestDeleteInvalidKey (line 129) | func TestDeleteInvalidKey(t *testing.T) {
  function TestDeleteKey (line 143) | func TestDeleteKey(t *testing.T) {
  function TestClearCache (line 161) | func TestClearCache(t *testing.T) {
  function TestGetStats (line 183) | func TestGetStats(t *testing.T) {
  function TestGetStatsIndex (line 211) | func TestGetStatsIndex(t *testing.T) {
  function TestCacheIndexHandler (line 249) | func TestCacheIndexHandler(t *testing.T) {
  function TestInvalidPutWhenExceedShardCap (line 276) | func TestInvalidPutWhenExceedShardCap(t *testing.T) {
  function TestInvalidPutWhenReading (line 289) | func TestInvalidPutWhenReading(t *testing.T) {
  type errReader (line 302) | type errReader
    method Read (line 304) | func (errReader) Read([]byte) (int, error) {

FILE: server/stats_handler.go
  function statsIndexHandler (line 10) | func statsIndexHandler() http.Handler {
  function getCacheStatsHandler (line 22) | func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) {

FILE: shard.go
  type onRemoveCallback (line 11) | type onRemoveCallback
  type Metadata (line 14) | type Metadata struct
  type cacheShard (line 18) | type cacheShard struct
    method getWithInfo (line 36) | func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry ...
    method get (line 62) | func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) {
    method getWrappedEntry (line 84) | func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) {
    method getValidWrapEntry (line 101) | func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) (...
    method set (line 120) | func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) e...
    method addNewWithoutLock (line 154) | func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, e...
    method setWrappedEntryWithoutLock (line 176) | func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint6...
    method append (line 200) | func (s *cacheShard) append(key string, hashedKey uint64, entry []byte...
    method del (line 224) | func (s *cacheShard) del(hashedKey uint64) error {
    method onEvict (line 276) | func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint...
    method isExpired (line 284) | func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp ui...
    method cleanUp (line 292) | func (s *cacheShard) cleanUp(currentTimestamp uint64) {
    method getEntry (line 304) | func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) {
    method copyHashedKeys (line 317) | func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) {
    method removeOldestEntry (line 330) | func (s *cacheShard) removeOldestEntry(reason RemoveReason) error {
    method reset (line 348) | func (s *cacheShard) reset(config Config) {
    method resetStats (line 356) | func (s *cacheShard) resetStats() {
    method len (line 362) | func (s *cacheShard) len() int {
    method capacity (line 369) | func (s *cacheShard) capacity() int {
    method getStats (line 376) | func (s *cacheShard) getStats() Stats {
    method getKeyMetadataWithLock (line 387) | func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata {
    method getKeyMetadata (line 396) | func (s *cacheShard) getKeyMetadata(key uint64) Metadata {
    method hit (line 402) | func (s *cacheShard) hit(key uint64) {
    method hitWithoutLock (line 411) | func (s *cacheShard) hitWithoutLock(key uint64) {
    method miss (line 418) | func (s *cacheShard) miss() {
    method delhit (line 422) | func (s *cacheShard) delhit() {
    method delmiss (line 426) | func (s *cacheShard) delmiss() {
    method collision (line 430) | func (s *cacheShard) collision() {
  function initNewShard (line 434) | func initNewShard(config Config, callback onRemoveCallback, clock clock)...

FILE: stats.go
  type Stats (line 4) | type Stats struct

FILE: utils.go
  function max (line 3) | func max(a, b int) int {
  function convertMBToBytes (line 10) | func convertMBToBytes(value int) int {
  function isPowerOfTwo (line 14) | func isPowerOfTwo(number int) bool {
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (152K chars).
[
  {
    "path": ".codecov.yml",
    "chars": 471,
    "preview": "---\ncodecov:\n  require_ci_to_pass: true\ncomment:\n  behavior: default\n  layout: reach, diff, flags, files, footer\n  requi"
  },
  {
    "path": ".github/CODEOWNERS",
    "chars": 23,
    "preview": "* @janisz @cristaloleg\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/issue_template.md",
    "chars": 876,
    "preview": "---\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"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 276,
    "preview": "version: 2\n\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n "
  },
  {
    "path": ".github/release-drafter.yml",
    "chars": 378,
    "preview": "name-template: \"v$NEXT_PATCH_VERSION 🌈\"\ntag-template: \"v$NEXT_PATCH_VERSION\"\ncategories:\n  - title: \"🚀 Features\"\n    lab"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 1244,
    "preview": "name: build\non: [push, pull_request]\nenv:\n  GO111MODULE: on\n  CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}\njobs:\n  build:"
  },
  {
    "path": ".github/workflows/release-management.yml",
    "chars": 393,
    "preview": "name: Release Management\n\non:\n  push:\n    # branches to consider in the event; optional, defaults to all\n    branches:\n "
  },
  {
    "path": ".gitignore",
    "chars": 183,
    "preview": ".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/se"
  },
  {
    "path": ".golangci.yaml",
    "chars": 438,
    "preview": "version: \"2\"\nlinters:\n  disable:\n    - errcheck\n  settings:\n    staticcheck:\n      checks:\n        - -SA1019\n        - a"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 8628,
    "preview": "# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/b"
  },
  {
    "path": "assert_test.go",
    "chars": 1043,
    "preview": "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, ex"
  },
  {
    "path": "bigcache.go",
    "chars": 7909,
    "preview": "package bigcache\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n)\n\nconst (\n\tminimumEntriesInShard = 10 // Minimum number of entr"
  },
  {
    "path": "bigcache_bench_test.go",
    "chars": 4889,
    "preview": "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"
  },
  {
    "path": "bigcache_test.go",
    "chars": 29449,
    "preview": "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\"ti"
  },
  {
    "path": "bytes.go",
    "chars": 163,
    "preview": "//go:build !appengine\n// +build !appengine\n\npackage bigcache\n\nimport (\n\t\"unsafe\"\n)\n\nfunc bytesToString(b []byte) string "
  },
  {
    "path": "bytes_appengine.go",
    "chars": 98,
    "preview": "//go:build appengine\n\npackage bigcache\n\nfunc bytesToString(b []byte) string {\n\treturn string(b)\n}\n"
  },
  {
    "path": "clock.go",
    "chars": 168,
    "preview": "package bigcache\n\nimport \"time\"\n\ntype clock interface {\n\tEpoch() int64\n}\n\ntype systemClock struct {\n}\n\nfunc (c systemClo"
  },
  {
    "path": "config.go",
    "chars": 4371,
    "preview": "package bigcache\n\nimport \"time\"\n\n// Config for BigCache\ntype Config struct {\n\t// Number of cache shards, value must be a"
  },
  {
    "path": "encoding.go",
    "chars": 2629,
    "preview": "package bigcache\n\nimport (\n\t\"encoding/binary\"\n)\n\nconst (\n\ttimestampSizeInBytes = 8                                      "
  },
  {
    "path": "encoding_test.go",
    "chars": 1011,
    "preview": "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"
  },
  {
    "path": "entry_not_found_error.go",
    "chars": 254,
    "preview": "package bigcache\n\nimport \"errors\"\n\nvar (\n\t// ErrEntryNotFound is an error type struct which is returned when entry was n"
  },
  {
    "path": "examples_test.go",
    "chars": 2468,
    "preview": "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"
  },
  {
    "path": "fnv.go",
    "chars": 825,
    "preview": "package bigcache\n\n// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations.\n// Its Sum64"
  },
  {
    "path": "fnv_bench_test.go",
    "chars": 281,
    "preview": "package bigcache\n\nimport \"testing\"\n\nvar text = \"abcdefg\"\n\nfunc BenchmarkFnvHashSum64(b *testing.B) {\n\th := newDefaultHas"
  },
  {
    "path": "fnv_test.go",
    "chars": 743,
    "preview": "package bigcache\n\nimport (\n\t\"hash/fnv\"\n\t\"testing\"\n)\n\ntype testCase struct {\n\ttext         string\n\texpectedHash uint64\n}\n"
  },
  {
    "path": "go.mod",
    "chars": 47,
    "preview": "module github.com/allegro/bigcache/v3\n\ngo 1.16\n"
  },
  {
    "path": "go.sum",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "hash.go",
    "chars": 339,
    "preview": "package bigcache\n\n// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimi"
  },
  {
    "path": "hash_test.go",
    "chars": 109,
    "preview": "package bigcache\n\ntype hashStub uint64\n\nfunc (stub hashStub) Sum64(_ string) uint64 {\n\treturn uint64(stub)\n}\n"
  },
  {
    "path": "iterator.go",
    "chars": 3232,
    "preview": "package bigcache\n\nimport (\n\t\"sync\"\n)\n\ntype iteratorError string\n\nfunc (e iteratorError) Error() string {\n\treturn string("
  },
  {
    "path": "iterator_test.go",
    "chars": 4964,
    "preview": "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 TestE"
  },
  {
    "path": "logger.go",
    "chars": 635,
    "preview": "package bigcache\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n// Logger is invoked when `Config.Verbose=true`\ntype Logger interface {\n\tPrin"
  },
  {
    "path": "queue/bytes_queue.go",
    "chars": 6892,
    "preview": "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\t"
  },
  {
    "path": "queue/bytes_queue_test.go",
    "chars": 11775,
    "preview": "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"
  },
  {
    "path": "server/README.md",
    "chars": 3383,
    "preview": "# BigCache HTTP Server\n\nThis is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is desig"
  },
  {
    "path": "server/cache_handlers.go",
    "chars": 2452,
    "preview": "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.Handl"
  },
  {
    "path": "server/middleware.go",
    "chars": 653,
    "preview": "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.Handl"
  },
  {
    "path": "server/middleware_test.go",
    "chars": 1179,
    "preview": "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"
  },
  {
    "path": "server/server.go",
    "chars": 2302,
    "preview": "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"
  },
  {
    "path": "server/server_test.go",
    "chars": 8224,
    "preview": "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\"g"
  },
  {
    "path": "server/stats_handler.go",
    "chars": 785,
    "preview": "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.Ha"
  },
  {
    "path": "shard.go",
    "chars": 10874,
    "preview": "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 onRemoveCal"
  },
  {
    "path": "stats.go",
    "chars": 485,
    "preview": "package bigcache\n\n// Stats stores cache statistics\ntype Stats struct {\n\t// Hits is a number of successfully found keys\n\t"
  },
  {
    "path": "utils.go",
    "chars": 241,
    "preview": "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 {"
  }
]

About this extraction

This page contains the full source code of the allegro/bigcache GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (135.9 KB), approximately 39.4k tokens, and a symbol index with 286 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!