Skip to content

Instantly share code, notes, and snippets.

@akkyie
Created November 18, 2015 07:54
Show Gist options
  • Save akkyie/6592245a8810f0035df5 to your computer and use it in GitHub Desktop.
Save akkyie/6592245a8810f0035df5 to your computer and use it in GitHub Desktop.
Graph.swift
//
// Graph.swift
// CoreMesh
//
// Created by Akio Yasui on 10/24/15.
// Copyright © 2015 Akio Yasui. All rights reserved.
//
import Foundation
func ==(lhs: Node, rhs: Node) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func ==(lhs: Edge, rhs: Edge) -> Bool {
return lhs.hashValue == rhs.hashValue
}
struct Graph {
var nodes: Set<Node>
var edges: Set<Edge>
init(nodes: Set<Node> = Set(), edges: Set<Edge> = Set()) {
self.nodes = nodes
self.edges = edges
}
}
struct Node: Equatable, Hashable, CustomStringConvertible {
let UUID: NSUUID
let label: String
var hashValue: Int {
let vs = UUID.integerValues
return Int(Int32((vs.0 ^ vs.1) >> 33))
}
var description: String {
return label
}
var debugDescription: String {
return label
}
init(UUID: NSUUID, label: String) {
self.UUID = UUID
self.label = label
}
}
struct Edge: Equatable, Hashable, CustomStringConvertible {
let source: Node
let target: Node
var UUID: NSUUID {
return NSUUID()
}
var hashValue: Int {
return Int(UUID.integerValues.0 >> 33)
}
var description: String {
return "\(source) <-(\(UUID.UUIDString))-> \(target)"
}
init(source: Node, target: Node) {
self.source = source
self.target = target
}
}
extension NSUUID {
var integerValues: (UInt64, UInt64) {
var bytes = [UInt8](count: 16, repeatedValue: 0)
self.getUUIDBytes(&bytes)
let headData = NSData(bytes: Array(bytes[0 ..< 8]), length: sizeof(UInt8) * 8)
var headValue = UInt64()
headData.getBytes(&headValue, length: sizeof(UInt64))
let tailData = NSData(bytes: Array(bytes[8 ..< 16]), length: sizeof(UInt8) * 8)
var tailValue = UInt64()
tailData.getBytes(&tailValue, length: sizeof(UInt64))
return (headValue, tailValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment