Home | History | Annotate | Download | only in shill
      1 //
      2 // Copyright (C) 2013 The Android Open Source Project
      3 //
      4 // Licensed under the Apache License, Version 2.0 (the "License");
      5 // you may not use this file except in compliance with the License.
      6 // You may obtain a copy of the License at
      7 //
      8 //      http://www.apache.org/licenses/LICENSE-2.0
      9 //
     10 // Unless required by applicable law or agreed to in writing, software
     11 // distributed under the License is distributed on an "AS IS" BASIS,
     12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 // See the License for the specific language governing permissions and
     14 // limitations under the License.
     15 //
     16 
     17 #include "shill/ip_address_store.h"
     18 
     19 #include <iterator>
     20 
     21 #include <stdlib.h>
     22 #include <time.h>
     23 
     24 using std::advance;
     25 
     26 namespace shill {
     27 
     28 // This is a less than comparison so that IPAddress can be stored in a set.
     29 // We do not care about a semantically meaningful comparison. This is
     30 // deterministic, and that's all that matters.
     31 bool IPAddressLTIgnorePrefix::operator () (const IPAddress& lhs,
     32                                            const IPAddress& rhs) const {
     33   return lhs.ToString() < rhs.ToString();
     34 }
     35 
     36 IPAddressStore::IPAddressStore() : random_engine_(time(nullptr)) {
     37 }
     38 
     39 IPAddressStore::~IPAddressStore() {}
     40 
     41 void IPAddressStore::AddUnique(const IPAddress& ip) {
     42   ip_addresses_.insert(ip);
     43 }
     44 
     45 void IPAddressStore::Remove(const IPAddress& ip) {
     46   ip_addresses_.erase(ip);
     47 }
     48 
     49 void IPAddressStore::Clear() {
     50   ip_addresses_.clear();
     51 }
     52 
     53 bool IPAddressStore::Contains(const IPAddress& ip) const {
     54   return ip_addresses_.find(ip) != ip_addresses_.end();
     55 }
     56 
     57 size_t IPAddressStore::Count() const {
     58   return ip_addresses_.size();
     59 }
     60 
     61 bool IPAddressStore::Empty() const {
     62   return ip_addresses_.empty();
     63 }
     64 
     65 IPAddress IPAddressStore::GetRandomIP() {
     66   if (ip_addresses_.empty())
     67     return IPAddress(IPAddress::kFamilyUnknown);
     68   std::uniform_int_distribution<int> uniform_rand(0, ip_addresses_.size() - 1);
     69   int index = uniform_rand(random_engine_);
     70   IPAddresses::const_iterator cit = ip_addresses_.begin();
     71   advance(cit, index);
     72   return *cit;
     73 }
     74 
     75 }  // namespace shill
     76