+ if inplace then
+ self[2] = data
+ return self
+ else
+ return __bless({ self[1], data, self[3] })
+ end
+end
+
+--- Substract specified amount of hosts from this instance.
+-- @param amount Number of hosts to substract from this instance
+-- @param inplace Boolen indicating whether to alter values inplace (optional)
+-- @return CIDR representing the new address or nil on underflow error
+-- @see cidr.add
+function cidr.sub( self, amount, inplace )
+ local data = { unpack(self[2]) }
+ local shorts = __array16( amount, self[1] )
+
+ for pos = #data, 1, -1 do
+ local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
+ if ( data[pos] - sub ) < 0 then
+ data[pos] = ( sub - data[pos] ) % 0xFFFF
+ if pos > 1 then
+ data[pos-1] = data[pos-1] - ( sub + data[pos] )
+ else
+ return nil
+ end
+ else
+ data[pos] = data[pos] - sub
+ end
+ end
+
+ if inplace then
+ self[2] = data
+ return self
+ else
+ return __bless({ self[1], data, self[3] })
+ end
+end
+
+--- Return CIDR containing the lowest available host address within this subnet.
+-- @return CIDR containing the host address, nil if subnet is too small
+-- @see cidr.maxhost
+function cidr.minhost( self )
+ if self[3] <= __sublen(self[1]) then
+ -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
+ return self:network():add(1, true)
+ end
+end
+
+--- Return CIDR containing the highest available host address within the subnet.
+-- @return CIDR containing the host address, nil if subnet is too small
+-- @see cidr.minhost
+function cidr.maxhost( self )
+ if self[3] <= __sublen(self[1]) then
+ local data = { unpack(self[2]) }
+ local offset = math.floor( self[3] / 16 ) + 1
+
+ data[offset] = bit.bor( data[offset], __not16(self[3]) )
+ for i = offset + 1, #data do data[i] = 0xFFFF end
+ data = __bless({ self[1], data, __maxlen(self[1]) })
+
+ -- Last address in reserved for Broadcast Address in IPv4
+ if data[1] == FAMILY_INET4 then data:sub(1, true) end
+
+ return data
+ end