1/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/common_runtime/request_cost_accessor_registry.h"
17
18#include <string>
19
20#include "absl/container/flat_hash_map.h"
21#include "absl/strings/string_view.h"
22#include "tensorflow/core/platform/logging.h"
23
24namespace tensorflow {
25namespace {
26
27using RegistrationMap =
28 absl::flat_hash_map<std::string, RequestCostAccessorRegistry::Creator>;
29
30RegistrationMap* GetRegistrationMap() {
31 static RegistrationMap* registered_request_cost_accessors =
32 new RegistrationMap;
33 return registered_request_cost_accessors;
34}
35
36} // namespace
37
38std::unique_ptr<RequestCostAccessor>
39RequestCostAccessorRegistry::CreateByNameOrNull(absl::string_view name) {
40 const auto it = GetRegistrationMap()->find(name);
41 if (it == GetRegistrationMap()->end()) return nullptr;
42 return std::unique_ptr<RequestCostAccessor>(it->second());
43}
44
45void RequestCostAccessorRegistry::RegisterRequestCostAccessor(
46 absl::string_view name, Creator creator) {
47 const auto it = GetRegistrationMap()->find(name);
48 CHECK(it == GetRegistrationMap()->end()) // Crash OK
49 << "RequestCostAccessor " << name << " is registered twice.";
50 GetRegistrationMap()->emplace(name, std::move(creator));
51}
52
53} // namespace tensorflow
54