copy wangle back into folly
[folly.git] / folly / wangle / acceptor / NetworkAddress.h
1 /*
2  *  Copyright (c) 2015, Facebook, Inc.
3  *  All rights reserved.
4  *
5  *  This source code is licensed under the BSD-style license found in the
6  *  LICENSE file in the root directory of this source tree. An additional grant
7  *  of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10 #pragma once
11
12 #include <folly/SocketAddress.h>
13
14 namespace folly {
15
16 /**
17  * A simple wrapper around SocketAddress that represents
18  * a network in CIDR notation
19  */
20 class NetworkAddress {
21 public:
22   /**
23    * Create a NetworkAddress for an addr/prefixLen
24    * @param addr         IPv4 or IPv6 address of the network
25    * @param prefixLen    Prefix length, in bits
26    */
27   NetworkAddress(const folly::SocketAddress& addr,
28       unsigned prefixLen):
29     addr_(addr), prefixLen_(prefixLen) {}
30
31   /** Get the network address */
32   const folly::SocketAddress& getAddress() const {
33     return addr_;
34   }
35
36   /** Get the prefix length in bits */
37   unsigned getPrefixLength() const { return prefixLen_; }
38
39   /** Check whether a given address lies within the network */
40   bool contains(const folly::SocketAddress& addr) const {
41     return addr_.prefixMatch(addr, prefixLen_);
42   }
43
44   /** Comparison operator to enable use in ordered collections */
45   bool operator<(const NetworkAddress& other) const {
46     if (addr_ <  other.addr_) {
47       return true;
48     } else if (other.addr_ < addr_) {
49       return false;
50     } else {
51       return (prefixLen_ < other.prefixLen_);
52     }
53   }
54
55 private:
56   folly::SocketAddress addr_;
57   unsigned prefixLen_;
58 };
59
60 } // namespace