1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef LIB_TONIC_DART_CLASS_LIBRARY_H_
6#define LIB_TONIC_DART_CLASS_LIBRARY_H_
7
8#include <memory>
9#include <string>
10#include <unordered_map>
11
12#include "third_party/dart/runtime/include/dart_api.h"
13#include "tonic/dart_class_provider.h"
14
15namespace tonic {
16struct DartWrapperInfo;
17
18class DartClassLibrary {
19 public:
20 explicit DartClassLibrary();
21 ~DartClassLibrary();
22
23 void add_provider(const std::string& library_name,
24 std::unique_ptr<DartClassProvider> provider) {
25 providers_.insert(std::make_pair(library_name, std::move(provider)));
26 }
27
28 Dart_PersistentHandle GetClass(const DartWrapperInfo& info);
29 Dart_PersistentHandle GetClass(const std::string& library_name,
30 const std::string& interface_name);
31
32 private:
33 Dart_PersistentHandle GetAndCacheClass(const char* library_name,
34 const char* interface_name,
35 Dart_PersistentHandle* cache_slot);
36
37 // TODO(abarth): Move this class somewhere more general.
38 // We should also use a more reasonable hash function, such as described in
39 // http://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html
40 struct PairHasher {
41 template <typename T, typename U>
42 std::size_t operator()(const std::pair<T, U>& pair) const {
43 return std::hash<T>()(pair.first) + 37 * std::hash<U>()(pair.second);
44 }
45 };
46
47 std::unordered_map<std::string, std::unique_ptr<DartClassProvider>>
48 providers_;
49 std::unordered_map<const DartWrapperInfo*, Dart_PersistentHandle> info_cache_;
50 std::unordered_map<std::pair<std::string, std::string>,
51 Dart_PersistentHandle,
52 PairHasher>
53 name_cache_;
54
55 TONIC_DISALLOW_COPY_AND_ASSIGN(DartClassLibrary);
56};
57
58} // namespace tonic
59
60#endif // LIB_TONIC_DART_CLASS_LIBRARY_H_
61