1// Copyright 2014 The Chromium 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#include "extensions/common/extension_icon_set.h"
6
7#include "base/logging.h"
8#include "base/strings/string_util.h"
9
10ExtensionIconSet::ExtensionIconSet() {}
11
12ExtensionIconSet::~ExtensionIconSet() {}
13
14void ExtensionIconSet::Clear() {
15  map_.clear();
16}
17
18void ExtensionIconSet::Add(int size, const std::string& path) {
19  DCHECK(!path.empty() && path[0] != '/');
20  map_[size] = path;
21}
22
23const std::string& ExtensionIconSet::Get(int size, MatchType match_type) const {
24  // The searches for MATCH_BIGGER and MATCH_SMALLER below rely on the fact that
25  // std::map is sorted. This is per the spec, so it should be safe to rely on.
26  if (match_type == MATCH_EXACTLY) {
27    IconMap::const_iterator result = map_.find(size);
28    return result == map_.end() ? base::EmptyString() : result->second;
29  } else if (match_type == MATCH_SMALLER) {
30    IconMap::const_reverse_iterator result = map_.rend();
31    for (IconMap::const_reverse_iterator iter = map_.rbegin();
32         iter != map_.rend(); ++iter) {
33      if (iter->first <= size) {
34        result = iter;
35        break;
36      }
37    }
38    return result == map_.rend() ? base::EmptyString() : result->second;
39  } else {
40    DCHECK(match_type == MATCH_BIGGER);
41    IconMap::const_iterator result = map_.end();
42    for (IconMap::const_iterator iter = map_.begin(); iter != map_.end();
43         ++iter) {
44      if (iter->first >= size) {
45        result = iter;
46        break;
47      }
48    }
49    return result == map_.end() ? base::EmptyString() : result->second;
50  }
51}
52
53bool ExtensionIconSet::ContainsPath(const std::string& path) const {
54  return GetIconSizeFromPath(path) != 0;
55}
56
57int ExtensionIconSet::GetIconSizeFromPath(const std::string& path) const {
58  if (path.empty())
59    return 0;
60
61  DCHECK_NE(path[0], '/') <<
62      "ExtensionIconSet stores icon paths without leading slash.";
63
64  for (IconMap::const_iterator iter = map_.begin(); iter != map_.end();
65       ++iter) {
66    if (iter->second == path)
67      return iter->first;
68  }
69
70  return 0;
71}
72