Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / libaddressinput / src / cpp / src / ondemand_supplier.cc
1 // Copyright (C) 2014 Google Inc.
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
15 #include <libaddressinput/ondemand_supplier.h>
16
17 #include <algorithm>
18 #include <cstddef>
19 #include <map>
20 #include <string>
21
22 #include "lookup_key.h"
23 #include "ondemand_supply_task.h"
24 #include "region_data_constants.h"
25 #include "retriever.h"
26 #include "rule.h"
27
28 namespace i18n {
29 namespace addressinput {
30
31 OndemandSupplier::OndemandSupplier(const Source* source, Storage* storage)
32     : retriever_(new Retriever(source, storage)) {
33 }
34
35 OndemandSupplier::~OndemandSupplier() {
36   for (std::map<std::string, const Rule*>::const_iterator
37        it = rule_cache_.begin(); it != rule_cache_.end(); ++it) {
38     delete it->second;
39   }
40 }
41
42 void OndemandSupplier::Supply(const LookupKey& lookup_key,
43                               const Callback& supplied) {
44   OndemandSupplyTask* task =
45       new OndemandSupplyTask(lookup_key, &rule_cache_, supplied);
46
47   if (RegionDataConstants::IsSupported(lookup_key.GetRegionCode())) {
48     size_t max_depth = std::min(
49         lookup_key.GetDepth(),
50         RegionDataConstants::GetMaxLookupKeyDepth(lookup_key.GetRegionCode()));
51
52     for (size_t depth = 0; depth <= max_depth; ++depth) {
53       const std::string& key = lookup_key.ToKeyString(depth);
54       std::map<std::string, const Rule*>::const_iterator it =
55           rule_cache_.find(key);
56       if (it != rule_cache_.end()) {
57         task->hierarchy_.rule[depth] = it->second;
58       } else {
59         task->Queue(key);  // If not in the cache, it needs to be loaded.
60       }
61     }
62   }
63
64   task->Retrieve(*retriever_);
65 }
66
67 }  // namespace addressinput
68 }  // namespace i18n