Skip to content
This repository has been archived by the owner on Aug 7, 2020. It is now read-only.

Commit

Permalink
Add a license and some documentation
Browse files Browse the repository at this point in the history
Signed-off-by: Ariel Abreu <[email protected]>
  • Loading branch information
facekapow committed Oct 11, 2019
1 parent 702c077 commit 6e638ae
Show file tree
Hide file tree
Showing 4 changed files with 278 additions and 6 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Alta Project Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
102 changes: 102 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# ip
![Package Name](https://img.shields.io/badge/dynamic/yaml?color=%2332a852&label=Package%20Name&query=%24.name&url=https%3A%2F%2Fraw.githubusercontent.com%2Falta-lang%2Fip%2Fmaster%2Fpackage.alta.yaml)
![Version](https://img.shields.io/badge/dynamic/yaml?color=a61900&label=Version&query=%24.version&url=https%3A%2F%2Fraw.githubusercontent.com%2Falta-lang%2Fip%2Fmaster%2Fpackage.alta.yaml)
[![License](https://img.shields.io/github/license/alta-lang/ip?color=%23428bff)](LICENSE)

An IP address parsing/serialization library for Alta.
Fully supports IPv6 shorthand syntax.

## Documentation
Check out the [docs](docs).

## Example Usage
Assuming you've done the following at the top of your module:
```alta
import Address from "ip" # this module's Address class
import String from "string" # the stdlib's String class
import printLine from "io" # the stdlib's printLine function
```

Parse an IP string:
```alta
let ipv4 = new Address("14.323.643.66")
let ipv6 = new Address("0053:0000:0000:0000:000f:0fcf:3400:005f")
# shorthand: leading zeros omitted
let noLeadingZeros = new Address("53:0:0:0:f:fcf:3400:5f")
# shorthand: consecutive zeros omitted
let noConsecutiveZeros = new Address("0053::000f:0fcf:3400:005f")
# shorthand: full shorthand (both omitted)
let fullShorthand = new Address("53::f:fcf:3400:5f")
```

Serialize an IP object:
```alta
# assuming the same objects as the example above...
let ipv4String = ipv4 as String # "14.323.643.66"
# serialization is implemented as a cast method, which means
# that automatic conversion is available. this allows it to be
# used, for example, with printLine:
printLine("my shortened ipv6 string: ", ipv6)
# all the ipv6 objects are represented the same way:
# they will all be printed in full shorthand syntax
# ("53::f:fcf:3400:5f" in this example)
printLine("original: ", ipv6)
printLine("no-leading-zeros shorthand: ", noLeadingZeros)
printLine("no-consecutive-zeros shorthand: ", noConsecutiveZeros)
printLine("full shorthand: ", fullShorthand)
```

Access a specific component:
```alta
# again, assuming the same objects as the examples above...
# prints "14" for ipv4[0]
printLine("the first component of the IPv4 address is ", ipv4[0])
# prints "0" for ipv6[2]
printLine("the third component of the IPv6 address is ", ipv6[2])
# remember ipv6 components are hexadecimals when parsing and serializing
# but components are accessed as unsigned integers
# ipv6[4] is actually "f", but as an unsigned integer, that's 15, so...
# prints "15" for ipv6[4]
printLine("the fifth component of the IPv6 address is ", ipv6[4])
# all IPv4 addresses have 4 components
# all IPv6 addresses have 8 components
# trying to access an invalid index will yield an InvalidComponentIndex error
# printLine("6th component of the IPv4 address = ", ipv4[5])
```

Create a new Address from scratch:
```alta
# by default, `Address`es are ipv4
let newIPv4 = new Address
let anotherIPv4: Address
let newIPv6 = new Address(true)
# in true Alta fashion, you can also specify the parameter name
# (which helps with self-documenting code)
let anotherIPv6 = new Address(isIPv6: true)
```

Detect if an Address is IPv4 or IPv6:
```alta
# assuming the same objects as the examples above...
if ipv4.isIPv6 {
# huh, something's wrong...
}
# assuming we created an address called `userInputAddr`
if userInputAddr.isIPv4 {
# it's IPv4
} else {
# it's IPv6
}
```
98 changes: 98 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# `ip` Package

## Depends On
* `vector`
* `types`
* `exceptions`
* `util`
* `string`

Classes
---
## `Address`
**Defines copy constructor**: No\
**Defines destructor**: No\
**Has copy constructor**: Yes\
**Has destructor**: Yes

### Constructors
#### `constructor()`
Constructs an IPv4 `Address` with all components initialized to 0

#### `constructor(isIPv6: bool)`
Constructs an `Address` with all components intialized to 0

**Parameters**:
* `isIPv6` - If `true`, the new address will be IPv6. Otherwise, it will be IPv4

#### <a name="constructor(address: [string].String)">`constructor(address: [string].String)`</a>
Constructs an `Address` by parsing the given string as an IPv4 or IPv6 address

**Parameters**:
* `address` - The string to parse as an address

**Is cast-constructor**: Yes

### Cast Operators
#### from `[string].String`
**Is from cast-constructor**: Yes

See [`constructor(address: [string].String)`](#constructor%28address%3A%20%5Bstring%5D.String%29)
.

#### to `[string].String`
**Returns**: A string representation of this Address\
**Notes**:
* IPv6 addresses will be represented with full shorthand (i.e. leading zeros and consecutive zero components omitted) and components will be in hexadecimal format
* IPv4 addresses will be represented normally&mdash;i.e. decimal formatted components joined with dots (`.`)

### Accessors
#### `isIPv4: bool`
**Read**: Yes\
**Write**: No

If true, this address is an [IPv4](https://en.wikipedia.org/wiki/IPv4) address.

#### `isIPv6: bool`
**Read**: Yes\
**Write**: No

If true, this address is an [IPv6](https://en.wikipedia.org/wiki/IPv6) address.

### Operators
#### `this[[types].uint8]: ref [types].uint16`
Accesses a component at the specified index

**Parameters**:
* The index of the desired component

**Returns**: A reference to the component at the index\
**Note**: Throws an InvalidComponentIndex error when trying to access past the:
* 3rd index (base-0) for IPv4
* 7th index (base-0) for IPv6

Exceptions
---
## `InvalidComponentIndex`
An invalid address component index was provided

An exception thrown by Address's subscript operator
when the provided subscript index exceeds the maximum
for the Address:
* 3 (base-0) for IPv4
* 7 (base-0) for IPv6

## `InvalidAddress`
An invalid address string was provided

An exception thrown by Address's String cast constructor
when the provided string is invalid for either IPv4 or IPv6.

For IPv4:
* If less than 3 dots are found
* If more than 3 dots are found

For IPv6:
* If less than 8 components are found (and no consecutive shorthand is found)
* If multiple consecutive shorthands are found
* If more than 8 components are found
63 changes: 57 additions & 6 deletions main.alta
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,51 @@ import Exception from "exceptions"
import parseNumber, numberToString from "util"
import String from "string"

# @brief An invalid address component index was provided
# @desc An exception thrown by Address's subscript operator
# when the provided subscript index exceeds the maximum
# for the Address:
# * 3 (base-0) for IPv4
# * 7 (base-0) for IPv6
export class InvalidComponentIndex extends Exception {}

# @brief An invalid address string was provided
# @desc An exception thrown by Address's String cast constructor
# when the provided string is invalid for either IPv4 or IPv6.
#
# For IPv4:
# * If less than 3 dots are found
# * If more than 3 dots are found
#
# For IPv6:
# * If less than 8 components are found (and no consecutive shorthand is found)
# * If multiple consecutive shorthands are found
# * If more than 8 components are found
export class InvalidAddress extends Exception {}

export class Address {
private var _isV6 = false
private var _components = new Vector<uint16>(6)

# @brief Constructs an IPv4 `Address` with all components initialized to 0
public constructor() {
for i: uint8 in 0..4 {
this._components.push(0)
}
}
public constructor(isIPV6: bool) {
for i: uint8 in 0..(isIPV6 ? 8 : 4) {

# @brief Constructs an `Address` with all components intialized to 0
#
# @param isIPv6 If `true`, the new address will be IPv6. Otherwise, it will be IPv4
public constructor(isIPv6: bool) {
for i: uint8 in 0..(isIPv6 ? 8 : 4) {
this._components.push(0)
}
}

# @brief Constructs an `Address` by parsing the given string as an IPv4 or IPv6 address
#
# @param address The string to parse as an address
public @from constructor(address: String) {
let found = false
for i: Size in 0..address.length {
Expand Down Expand Up @@ -90,23 +118,41 @@ export class Address {
let second = address.indexOf('.', after: first)
let third = address.indexOf('.', after: second)

if first == SizeMaximum || second == SizeMaximum || third == SizeMaximum {
throw new InvalidAddress
}

if address.indexOf('.', after: third) != SizeMaximum {
throw new InvalidAddress
}

this._components[0] = parseNumber<uint16>(address.substring(from: 0, to: first))
this._components[1] = parseNumber<uint16>(address.substring(from: first + 1, to: second))
this._components[2] = parseNumber<uint16>(address.substring(from: second + 1, to: third))
this._components[3] = parseNumber<uint16>(address.substring(from: third + 1, to: address.length))
}
}

public @read function isIPV4(): bool {
# @brief If true, this address is an [IPv4](https://en.wikipedia.org/wiki/IPv4) address.
public @read function isIPv4(): bool {
return !this._isV6
}
public @read function isIPV6(): bool {

# @brief If true, this address is an [IPv6](https://en.wikipedia.org/wiki/IPv6) address.
public @read function isIPv6(): bool {
return this._isV6
}

# limit index to uint8 since we can only have up to 8 components
# limit return value to uint16 since we components can have a maximum of 16 bits
# @brief Accesses a component at the specified index
# @returns A reference to the component at the index
# @param $ The index of the desired component
# @note Throws an InvalidComponentIndex error when trying to access past the:
# * 3rd index (base-0) for IPv4
# * 7th index (base-0) for IPv6
public this[uint8]: ref uint16 {
# limit index to uint8 since we can only have up to 8 components
# limit return value to uint16 since we components can have a maximum of 16 bits

if this._isV6 && $ > 7 {
throw new InvalidComponentIndex
} else if !this._isV6 && $ > 3 {
Expand All @@ -115,6 +161,11 @@ export class Address {
return this._components[$]
}

# @returns A string representation of this Address
# @note IPv6 addresses will be represented with full shorthand (i.e. leading zeros and
# consecutive zero components omitted) and components will be in hexadecimal format
# @note IPv4 addresses will be represented normally&mdash;i.e. decimal formatted
# components joined with dots (`.`)
public to String {
if this._isV6 {
let longestIdx: uint8 = 0
Expand Down

0 comments on commit 6e638ae

Please sign in to comment.