Skip to content

Commit

Permalink
Add AccountId
Browse files Browse the repository at this point in the history
  • Loading branch information
qtbeee committed Sep 23, 2019
1 parent 4836492 commit b3ff7ca
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Sources/hedera/account/AccountId.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
public struct AccountId {
let shard: UInt64
let realm: UInt64
let num: UInt64

public init(accountNum: UInt64) {
self = AccountId(shard: 0, realm: 0, num: accountNum)
}

public init(shard: UInt64, realm: UInt64, num: UInt64) {
self.shard = shard
self.realm = realm
self.num = num
}
}

extension AccountId: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(shard).\(realm).\(num)"
}

public var debugDescription: String {
return description
}
}

extension AccountId: LosslessStringConvertible {
public init?(_ description: String) {
let parts = description.split(separator: ".")
if parts.count != 3 {
return nil
}

guard let shard = UInt64(parts[parts.startIndex], radix: 10) else { return nil }
guard let realm = UInt64(parts[parts.startIndex.advanced(by: 1)], radix: 10) else { return nil }
guard let num = UInt64(parts[parts.startIndex.advanced(by: 2)], radix: 10) else { return nil }

self.shard = shard
self.realm = realm
self.num = num
}
}
1 change: 1 addition & 0 deletions Tests/hederaTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public func allTests() -> [XCTestCaseEntry] {
testCase(Ed25519PrivateKeyTests.allTests),
testCase(Ed25519PublicKeyTests.allTests),
testCase(HexTests.allTests),
testCase(AccountIdTests.allTests),
]
}
#endif
37 changes: 37 additions & 0 deletions Tests/hederaTests/account/AccountIdTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import XCTest
import hedera

final class AccountIdTests: XCTestCase {
static let allTests = [
("testToString", testToString),
("testFromString", testFromString),
("testFromBadStrings", testFromBadStrings),
]

func testToString() {
let id = AccountId(shard: 1, realm: 2, num: 3)
XCTAssertEqual(String(id), "1.2.3")
}

func testFromString() {
let id = AccountId("0.0.2")
XCTAssertNotNil(id)
}

func testFromBadStrings() {
var id = AccountId("0.0")
XCTAssertNil(id)

id = AccountId("a.2.3")
XCTAssertNil(id)

id = AccountId("1.b.3")
XCTAssertNil(id)

id = AccountId("1.2.c")
XCTAssertNil(id)

id = AccountId("1.2.3.4")
XCTAssertNil(id)
}
}

0 comments on commit b3ff7ca

Please sign in to comment.