SPB Git

Repository Public BSD-3-Clause

NodeStore.swift 7.1 KB 180 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/geocoder-builder/Sources/GeocoderBuilder/NodeStore.swift10// Module           : GeocoderBuilder11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXGeoCore9091/// Coordinates of the nodes the builder needs (those referenced by kept ways), not of every node of the extract:92/// a sorted array of identifiers with parallel E7 arrays, 16 bytes per node, looked up by binary search.93public struct NodeStore: Sendable {94    public private(set) var ids: [Int64]95    private var lat: [Int32]96    private var lon: [Int32]97    private var cursor = 098    private var lastID = Int64.min99    public private(set) var filled = 0100101    private static let missing = Int32.min102103    /// - Parameter wanted: node identifiers, in any order, duplicates allowed.104    public init(wanted: [Int64]) {105        var sorted = wanted106        sorted.sort()107        var unique: [Int64] = []108        unique.reserveCapacity(sorted.count)109        var previous: Int64?110        for id in sorted where id != previous { unique.append(id); previous = id }111        ids = unique112        lat = [Int32](repeating: Self.missing, count: unique.count)113        lon = [Int32](repeating: Self.missing, count: unique.count)114    }115116    public var count: Int { ids.count }117118    private func index(of id: Int64) -> Int? {119        var lo = 0, hi = ids.count - 1120        while lo <= hi {121            let mid = (lo + hi) >> 1122            let v = ids[mid]123            if v == id { return mid }124            if v < id { lo = mid + 1 } else { hi = mid - 1 }125        }126        return nil127    }128129    /// Records a node met while reading the extract. Nodes arriving in increasing identifier order (the normal case in a PBF)130    /// are matched by a merge walk; anything else falls back to a binary search.131    public mutating func offer(id: Int64, latitude: Double, longitude: Double) {132        var slot: Int?133        if id > lastID {134            while cursor < ids.count, ids[cursor] < id { cursor += 1 }135            if cursor < ids.count, ids[cursor] == id { slot = cursor }136        } else {137            slot = index(of: id)138        }139        lastID = max(lastID, id)140        guard let slot else { return }141        if lat[slot] == Self.missing { filled += 1 }142        lat[slot] = Int32((latitude * 1e7).rounded())143        lon[slot] = Int32((longitude * 1e7).rounded())144    }145146    public func contains(_ id: Int64) -> Bool { index(of: id) != nil }147148    public func coordinate(_ id: Int64) -> Coordinate? {149        guard let i = index(of: id), lat[i] != Self.missing else { return nil }150        return Coordinate(latE7: lat[i], lonE7: lon[i])151    }152153    /// The coordinates of a way; nodes missing from the extract are skipped.154    public func coordinates(_ refs: [Int64]) -> [Coordinate] {155        var out: [Coordinate] = []156        out.reserveCapacity(refs.count)157        for r in refs { if let c = coordinate(r) { out.append(c) } }158        return out159    }160}161162/// Runs `body` for every index on all cores and collects the results in order.163func parallelMap<T: Sendable>(_ count: Int, _ body: @Sendable (Int) -> T) -> [T] {164    guard count > 0 else { return [] }165    return [T](unsafeUninitializedCapacity: count) { buffer, initialized in166        let base = SendablePointer(pointer: buffer.baseAddress!)167        let chunk = max(1, count / (ProcessInfo.processInfo.activeProcessorCount * 8))168        let chunks = (count + chunk - 1) / chunk169        DispatchQueue.concurrentPerform(iterations: chunks) { c in170            let start = c * chunk, end = min(count, start + chunk)171            for i in start..<end { (base.pointer + i).initialize(to: body(i)) }172        }173        initialized = count174    }175}176177private struct SendablePointer<T>: @unchecked Sendable {178    let pointer: UnsafeMutablePointer<T>179}180
Files main
Menu

Theme