don't use local-file-change context for mapreduce
[hiphop-php.git] / hphp / util / compression-ctx-pool.h
blobc46aa2f6979f9fbebe35418b555fe585771259cc
1 /*
2 +----------------------------------------------------------------------+
3 | HipHop for PHP |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
17 #pragma once
19 #include <memory>
20 #include <string>
22 #include <folly/Memory.h>
23 #include <folly/Synchronized.h>
25 namespace HPHP {
27 template <typename T, T* (*Creator)(), void (*Deleter)(T*)>
28 class CompressionContextPool {
29 private:
30 using InternalRef =
31 std::unique_ptr<T, folly::static_function_deleter<T, Deleter>>;
33 class ReturnToPoolDeleter {
34 public:
35 using Pool = CompressionContextPool<T, Creator, Deleter>;
37 // lets us default-construct non-attached deleters, so we can
38 // default-construct empty Refs.
39 ReturnToPoolDeleter() : pool_(nullptr) {}
41 explicit ReturnToPoolDeleter(Pool* pool) : pool_(pool) {}
43 void operator()(T* t) {
44 InternalRef ptr(t);
45 if (pool_ != nullptr) {
46 pool_->add(std::move(ptr));
50 private:
51 Pool* pool_;
54 public:
55 using Object = T;
56 using Ref = std::unique_ptr<T, ReturnToPoolDeleter>;
58 explicit CompressionContextPool() {}
60 Ref get() {
61 auto stack = stack_.wlock();
62 if (stack->empty()) {
63 T* t = Creator();
64 if (t == nullptr) {
65 throw std::runtime_error("Failed to allocate new pool object!");
67 return Ref(t, ReturnToPoolDeleter(this));
69 auto ptr = std::move(stack->back());
70 stack->pop_back();
71 return Ref(ptr.release(), ReturnToPoolDeleter(this));
74 private:
75 void add(InternalRef ptr) {
76 DCHECK(ptr);
77 stack_->push_back(std::move(ptr));
80 folly::Synchronized<std::vector<InternalRef>> stack_;
82 } // namespace HPHP