blob: 7f67fd6a4744989e2bf1d0a51cffedf5fc892e9e [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.
Paul Stewart8ae18742015-06-16 13:13:10 -070019bool IPAddressLTIgnorePrefix::operator () (const IPAddress& lhs,
20 const IPAddress& rhs) const {
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070021 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
Paul Stewart8ae18742015-06-16 13:13:10 -070029void IPAddressStore::AddUnique(const IPAddress& ip) {
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070030 ip_addresses_.insert(ip);
31}
32
Paul Stewart8ae18742015-06-16 13:13:10 -070033void IPAddressStore::Remove(const IPAddress& ip) {
Samuel Tanfe734672014-08-07 15:50:48 -070034 ip_addresses_.erase(ip);
35}
36
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070037void IPAddressStore::Clear() {
38 ip_addresses_.clear();
39}
40
Paul Stewart8ae18742015-06-16 13:13:10 -070041bool IPAddressStore::Contains(const IPAddress& ip) const {
Samuel Tanaba10002014-08-18 17:13:56 -070042 return ip_addresses_.find(ip) != ip_addresses_.end();
43}
44
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070045size_t IPAddressStore::Count() const {
46 return ip_addresses_.size();
47}
48
49bool IPAddressStore::Empty() const {
50 return ip_addresses_.empty();
51}
52
53IPAddress IPAddressStore::GetRandomIP() {
54 if (ip_addresses_.empty())
55 return IPAddress(IPAddress::kFamilyUnknown);
Alex Vakulenko37c5d942014-06-17 18:17:43 -070056 std::uniform_int_distribution<int> uniform_rand(0, ip_addresses_.size() - 1);
57 int index = uniform_rand(random_engine_);
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070058 IPAddresses::const_iterator cit = ip_addresses_.begin();
59 advance(cit, index);
60 return *cit;
61}
62
63} // namespace shill