Skip to content
Snippets Groups Projects
DurableHNSWCorpus + Dictionary.swift 2.39 KiB
// Copyright (c) 2024 Jim Wallace
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// Created by Mingchung Xia on 2024-02-26.
//

#if os(macOS)

import Foundation

extension DurableHNSWCorpus {
    /// This extension is used for the dictionary operations
    public struct DocumentVectorPair {
        var untokenizedDocument: String
        var vector: [Encoder.Scalar]
        
        init(untokenizedDocument: String, vector: [Encoder.Scalar]) {
            self.untokenizedDocument = untokenizedDocument
            self.vector = vector
        }
    }
    
    @inlinable
    func getUntokenizedDocument(at key: Int) -> String {
        if let pair = dictionary[key] {
            return pair.untokenizedDocument
        } else {
            fatalError("Key \(key) not found in HNSW dictionary")
        }
    }
    
    @inlinable
    func getVector(at key: Int) -> [Encoder.Scalar] {
        if let pair = dictionary[key] {
            return pair.vector
        } else {
            fatalError("Key \(key) not found in HNSW dictionary")
        }
    }
    
    @inlinable
    func getDictionary() -> [Int: DocumentVectorPair] {
        return dictionary
    }
    
    func addDocumentVectorPair(at key: Int, document: String, vector: [Encoder.Scalar]) {
        dictionary[key] = DocumentVectorPair(
            untokenizedDocument: document,
            vector: vector
        )
    }
}

#endif