1336809Sdim//===- xray-registry.cpp: Implement a command registry. -------------------===//
2336809Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6336809Sdim//
7336809Sdim//===----------------------------------------------------------------------===//
8336809Sdim//
9336809Sdim// Implement a simple subcommand registry.
10336809Sdim//
11336809Sdim//===----------------------------------------------------------------------===//
12336809Sdim#include "xray-registry.h"
13336809Sdim
14336809Sdim#include "llvm/Support/ManagedStatic.h"
15336809Sdim#include <unordered_map>
16336809Sdim
17336809Sdimnamespace llvm {
18336809Sdimnamespace xray {
19336809Sdim
20336809Sdimusing HandlerType = std::function<Error()>;
21336809Sdim
22336809SdimManagedStatic<std::unordered_map<cl::SubCommand *, HandlerType>> Commands;
23336809Sdim
24336809SdimCommandRegistration::CommandRegistration(cl::SubCommand *SC,
25336809Sdim                                         HandlerType Command) {
26336809Sdim  assert(Commands->count(SC) == 0 &&
27336809Sdim         "Attempting to overwrite a command handler");
28336809Sdim  assert(Command && "Attempting to register an empty std::function<Error()>");
29336809Sdim  (*Commands)[SC] = Command;
30336809Sdim}
31336809Sdim
32336809SdimHandlerType dispatch(cl::SubCommand *SC) {
33336809Sdim  auto It = Commands->find(SC);
34336809Sdim  assert(It != Commands->end() &&
35336809Sdim         "Attempting to dispatch on un-registered SubCommand.");
36336809Sdim  return It->second;
37336809Sdim}
38336809Sdim
39336809Sdim} // namespace xray
40336809Sdim} // namespace llvm
41