<commit_before>//
//  Observation.swift
//
//  This file is part of LyricsX
//  Copyright (C) 2017 <NAME> - https://github.com/ddddxxx/LyricsX
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import Foundation
import GenericID

private class NotificationObservationToken {
    
    var center: NotificationCenter?
    var token: NSObjectProtocol?
    
    init(center: NotificationCenter, token: NSObjectProtocol) {
        self.center = center
        self.token = token
    }
    
    func invalidate() {
        token.map { center?.removeObserver($0) }
        center = nil
        token = nil
    }
    
    deinit {
        invalidate()
    }
}

extension NSObject {
    
    private static var autoDestructionTokens: Void = ()
    
    // using [Any] causes unexpected destruction, use NSMutableArray instead.
    private var autoDestruction: NSMutableArray {
        get {
            if let arr = objc_getAssociatedObject(self, &NSObject.autoDestructionTokens) as? NSMutableArray {
                return arr
            }
            let arr = NSMutableArray()
            objc_setAssociatedObject(self, &NSObject.autoDestructionTokens, arr, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return arr
        }
    }
    
    func observeNotification(center: NotificationCenter = .default, name: NSNotification.Name, object: Any? = nil, queue: OperationQueue? = nil, using: @escaping (Notification) -> Void) {
        let token = center.addObserver(forName: name, object: object, queue: queue, using: using)
        autoDestruction.add(NotificationObservationToken(center: center, token: token))
    }
    
    func observeObject<Target: NSObject, Value>(_ object: Target, keyPath: KeyPath<Target, Value>, options: NSKeyValueObservingOptions, changeHandler: @escaping (NSObject, NSKeyValueObservedChange<Value>) -> Void) {
        let token = object.observe(keyPath, options: options, changeHandler: changeHandler)
        autoDestruction.add(token)
    }
    
    func observeDefaults<T>(_ defaults: UserDefaults = .standard, key: UserDefaults.DefaultsKeys.Key<T>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (UserDefaults, UserDefaults.DefaultsObservedChange<T>) -> Void) {
        let token = defaults.observe(key, options: options, changeHandler: changeHandler)
        autoDestruction.add(token)<commit_msg>fix: auto destruction array doesn't work properly<commit_after>//
//  Observation.swift
//
//  This file is part of LyricsX
//  Copyright (C) 2017 <NAME> - https://github.com/ddddxxx/LyricsX
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import Foundation
import GenericID

private class NotificationObservationToken {
    
    var center: NotificationCenter?
    var token: NSObjectProtocol?
    
    init(center: NotificationCenter, token: NSObjectProtocol) {
        self.center = center
        self.token = token
    }
    
    func invalidate() {
        token.map { center?.removeObserver($0) }
        center = nil
        token = nil
    }
    
    deinit {
        invalidate()
    }
}

extension NSObject {
    
    private static var autoDestructionTokens: Void?
    
    // using [Any] causes unexpected destruction, use NSMutableArray instead.
    private var autoDestruction: NSMutableArray {
        get {
            if let arr = objc_getAssociatedObject(self, &NSObject.autoDestructionTokens) as? NSMutableArray {
                return arr
            }
            let arr = NSMutableArray()
            objc_setAssociatedObject(self, &NSObject.autoDestructionTokens, arr, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return arr
        }
    }
    
    func observeNotification(center: NotificationCenter = .default, name: NSNotification.Name, object: Any? = nil, queue: OperationQueue? = nil, using: @escaping (Notification) -> Void) {
        let token = center.addObserver(forName: name, object: object, queue: queue, using: using)
        autoDestruction.add(NotificationObservationToken(center: center, token: token))
    }
    
    func observeObject<Target: NSObject, Value>(_ object: Target, keyPath: KeyPath<Target, Value>, options: NSKeyValueObservingOptions, changeHandler: @escaping (NSObject, NSKeyValueObservedChange<Value>) -> Void) {
        let token = object.observe(keyPath, options: options, changeHandler: changeHandler)
        autoDestruction.add(token)
    }
    
    func observeDefaults<T>(_ defaults: UserDefaults = .standard, key: UserDefaults.DefaultsKeys.Key<T>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (UserDefaults, UserDefaults.DefaultsObservedChange<T>) -> Void) {
        let token = defaults.observe(key, options: options, changeHandler: changeHandler)
        autoDestruction.add(token)
{'fraction_non_alphanumeric': 0.09045057162071285, 'fraction_numerical': 0.0020174848688634837, 'mean_word_length': 3.1226611226611225, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '798181', 'n_tokens_mistral': 1657, 'n_tokens_neox': 1594, 'n_words': 519}