blob: 917c232cd4a1cbcefbfe8ce2ff48527e89e8c964 [file] [log] [blame]
Prathmesh Prabhuba99b592013-04-17 15:13:14 -07001// Copyright (c) 2013 The Chromium OS 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 "shill/ip_address_store.h"
6
7#include <iterator>
8
9#include <stdlib.h>
10#include <time.h>
11
12using std::advance;
13
14namespace shill {
15
16// This is a less than comparison so that IPAddress can be stored in a set.
17// We do not care about a semantically meaningful comparison. This is
18// deterministic, and that's all that matters.
19bool IPAddressLTIgnorePrefix::operator () (const IPAddress &lhs,
20 const IPAddress &rhs) const {
21 return lhs.ToString() < rhs.ToString();
22}
23
Alex Vakulenko37c5d942014-06-17 18:17:43 -070024IPAddressStore::IPAddressStore() : random_engine_(time(nullptr)) {
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070025}
26
27IPAddressStore::~IPAddressStore() {}
28
29void IPAddressStore::AddUnique(const IPAddress &ip) {
30 ip_addresses_.insert(ip);
31}
32
Samuel Tanfe734672014-08-07 15:50:48 -070033void IPAddressStore::Remove(const IPAddress &ip) {
34 ip_addresses_.erase(ip);
35}
36
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070037void IPAddressStore::Clear() {
38 ip_addresses_.clear();
39}
40
41size_t IPAddressStore::Count() const {
42 return ip_addresses_.size();
43}
44
45bool IPAddressStore::Empty() const {
46 return ip_addresses_.empty();
47}
48
49IPAddress IPAddressStore::GetRandomIP() {
50 if (ip_addresses_.empty())
51 return IPAddress(IPAddress::kFamilyUnknown);
Alex Vakulenko37c5d942014-06-17 18:17:43 -070052 std::uniform_int_distribution<int> uniform_rand(0, ip_addresses_.size() - 1);
53 int index = uniform_rand(random_engine_);
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070054 IPAddresses::const_iterator cit = ip_addresses_.begin();
55 advance(cit, index);
56 return *cit;
57}
58
59} // namespace shill