• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {Disposable} from '../base/disposable';
16
17export interface HasKind {
18  kind: string;
19}
20
21export class RegistryError extends Error {
22  constructor(message?: string) {
23    super(message);
24    this.name = this.constructor.name;
25  }
26}
27
28export class Registry<T> {
29  private key: (t: T) => string;
30  protected registry: Map<string, T>;
31
32  static kindRegistry<T extends HasKind>(): Registry<T> {
33    return new Registry<T>((t) => t.kind);
34  }
35
36  constructor(key: (t: T) => string) {
37    this.registry = new Map<string, T>();
38    this.key = key;
39  }
40
41  register(registrant: T): Disposable {
42    const kind = this.key(registrant);
43    if (this.registry.has(kind)) {
44      throw new RegistryError(
45        `Registrant ${kind} already exists in the registry`,
46      );
47    }
48    this.registry.set(kind, registrant);
49
50    return {
51      dispose: () => this.registry.delete(kind),
52    };
53  }
54
55  has(kind: string): boolean {
56    return this.registry.has(kind);
57  }
58
59  get(kind: string): T {
60    const registrant = this.registry.get(kind);
61    if (registrant === undefined) {
62      throw new RegistryError(`${kind} has not been registered.`);
63    }
64    return registrant;
65  }
66
67  tryGet(kind: string): T | undefined {
68    return this.registry.get(kind);
69  }
70
71  // Support iteration: for (const foo of fooRegistry.values()) { ... }
72  *values() {
73    yield* this.registry.values();
74  }
75
76  unregisterAllForTesting(): void {
77    this.registry.clear();
78  }
79}
80