Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String Interpolation, Equatability, Hashability #48

Merged
merged 3 commits into from
Mar 25, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions Sources/Html/Node.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,64 @@ extension Node {
}
}

extension Node: Equatable {
public static func == (lhs: Node, rhs: Node) -> Bool {
switch (lhs, rhs) {
case
let (.comment(lhs), .comment(rhs)),
let (.doctype(lhs), .doctype(rhs)),
let (.raw(lhs), .raw(rhs)),
let (.text(lhs), .text(rhs)):
return lhs == rhs
case let (
.element(lhsTag, lhsAttributes, lhsChildren),
.element(rhsTag, rhsAttributes, rhsChildren)):

return lhsTag == rhsTag
&& zip(lhsAttributes, rhsAttributes).allSatisfy { $0 == $1 }
&& lhsChildren == rhsChildren
case let (.fragment(lhs), .fragment(rhs)):
return lhs == rhs
default:
return false
}
}
}

extension Node: Hashable {
public func hash(into hasher: inout Hasher) {
enum HashingTag: String {
case comment, doctype, element, fragment, raw, text
}

switch self {
case let .comment(comment):
hasher.combine(HashingTag.comment)
hasher.combine(comment)
case let .doctype(doctype):
hasher.combine(HashingTag.doctype)
hasher.combine(doctype)
case let .element(tag, attributes, children):
hasher.combine(HashingTag.element)
hasher.combine(tag)
attributes.forEach {
hasher.combine($0)
hasher.combine($1)
}
hasher.combine(children)
case let .fragment(nodes):
hasher.combine(HashingTag.fragment)
hasher.combine(nodes)
case let .raw(raw):
hasher.combine(HashingTag.raw)
hasher.combine(raw)
case let .text(text):
hasher.combine(HashingTag.text)
hasher.combine(text)
}
}
}

extension Node: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Node...) {
self = .fragment(elements)
Expand All @@ -44,6 +102,19 @@ extension Node: ExpressibleByStringLiteral {
}
}

extension Node: ExpressibleByStringInterpolation {
#if swift(>=5.0)
#else
public init(stringInterpolation strings: Node...) {
self = .fragment(strings)
}

public init<T>(stringInterpolationSegment expr: T) {
self = .text("\(expr)")
}
#endif
}

extension Node {
/// Default HTML DOCTYPE.
public static let doctype: Node = .doctype("html")
Expand Down