Skip to content

Commit

Permalink
Ensure MoveTree.Node is sendable
Browse files Browse the repository at this point in the history
  • Loading branch information
pdil committed Sep 28, 2024
1 parent 566e5f1 commit fd2a125
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
18 changes: 14 additions & 4 deletions Sources/ChessKit/MoveTree/MoveTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// ChessKit
//

import Foundation

/// A tree-like data structure that represents the moves of a chess game.
///
/// The tree maintains the move order including variations and
Expand All @@ -27,6 +29,10 @@ public struct MoveTree: Hashable, Sendable {
Array(dictionary.keys)
}

/// Lock to restrict modification of tree nodes
/// to ensure `Sendable` conformance for ``Node``.
private static let nodeLock = NSLock()

/// Adds a move to the move tree.
///
/// - parameter move: The move to add to the tree.
Expand Down Expand Up @@ -67,7 +73,9 @@ public struct MoveTree: Hashable, Sendable {
}
}

dictionary[newIndex] = newNode
Self.nodeLock.withLock {
dictionary[newIndex] = newNode
}
newNode.index = newIndex

if newIndex.variation == Index.mainVariation {
Expand Down Expand Up @@ -257,8 +265,10 @@ public struct MoveTree: Hashable, Sendable {
assessment: Move.Assessment = .null,
comment: String = ""
) -> Move? {
dictionary[index]?.move.assessment = assessment
dictionary[index]?.move.comment = comment
Self.nodeLock.withLock {
dictionary[index]?.move.assessment = assessment
dictionary[index]?.move.comment = comment
}
return dictionary[index]?.move
}

Expand Down Expand Up @@ -343,7 +353,7 @@ extension MoveTree: Equatable {
extension MoveTree {

/// Object that represents a node in the move tree.
final class Node: Hashable, @unchecked Sendable {
class Node: Hashable, @unchecked Sendable {

/// The move for this node.
var move: Move
Expand Down
8 changes: 8 additions & 0 deletions Tests/ChessKitTests/MoveTreeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ final class MoveTreeTests: XCTestCase {
XCTAssertEqual(moveTree[.minimum.next], e4)
}

func testNodeHashValue() {
var moveTree = MoveTree()
let e4 = Move(san: "e4", position: .standard)
moveTree[.minimum.next] = e4
print(moveTree.dictionary[.minimum.next]?.hashValue)
XCTAssertNotNil(moveTree.dictionary[.minimum.next]?.hashValue)
}

func testSameVariationComparability() {
let wIndex = MoveTree.Index(number: 4, color: .white, variation: 2)
XCTAssertLessThan(wIndex, wIndex.next)
Expand Down

0 comments on commit fd2a125

Please sign in to comment.