Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
julianschiavo committed Feb 13, 2021
0 parents commit 1814072
Show file tree
Hide file tree
Showing 23 changed files with 1,143 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>Loadability.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>Loadability</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
27 changes: 27 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Loadability Contribution Guide

*Adapted from the [Plot Contribution Guide](https://github.com/JohnSundell/Plot/blob/master/CONTRIBUTING.md)*

Welcome to the **Loadability Contribution Guide**, which aims to give you all the information you need to contribute to Loadability. Thank you for your interest in contributing to this project!

## Bugs, feature requests and support

### I found a bug, how do I report it?

If you find a bug, such as loading or caching not working correctly, please file a detailed Github Issue containing all of the information necessary to reproduce the bug. This helps us to quickly understand the bug and triage it.

### I have an idea for a feature request

Awesome! You can either create a Github Issue describing your idea and how it would improve the project, or create a Pull Request with your feature. Creating a Pull Request contributes to the project and makes it more likely your idea will be added!

### I have a question

Please make sure you read the documentation (inline in the source files) and [README](README.md) carefully. If your question is still not answered, file a Github Issue detailing your question and what steps you took already.

## Project structure

Loadability is structured in the default way for Swift Packages. Source code is in the `Source/Loadability` directory, with each type in a separate file.

## Conclusion

Hopefully this document helped you better understand how Loadability is structured and the best way to get help or contribute to the project. Thanks again for the interest!
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Julian Schiavo

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.
19 changes: 19 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "Loadability",
platforms: [.iOS(.v14), .macOS(.v11), .watchOS(.v7)],
products: [
.library(name: "Loadability", targets: ["Loadability"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
.target(name: "Loadability", dependencies: []),
]
)
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Loadability

A description of this package.
8 changes: 8 additions & 0 deletions Sources/Loadability/Caching/AnySharedCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/// A shared cache.
public protocol AnySharedCache {
associatedtype Key: Hashable & Identifiable
associatedtype Value

static subscript(key: Key) -> Value? { get set }
static func isValueStale(_ key: Key) -> Bool
}
154 changes: 154 additions & 0 deletions Sources/Loadability/Caching/Cache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import Foundation

/// A mutable collection used to store key-value pairs that are subject to eviction when resources are low.
public class Cache<Key: Hashable & Identifiable, Value> {

/// Whether the cache automatically removes stale items.
final let autoRemoveStaleItems: Bool

/// The wrapped `NSCache`.
final let _cache = NSCache<_Key, _Entry>()

// MARK: - Public

/// Creates a new `Cache`
/// - Parameter autoRemoveStaleItems: Whether to automatically remove stale items, `false` by default.
public init(shouldAutomaticallyRemoveStaleItems autoRemoveStaleItems: Bool = false) {
self.autoRemoveStaleItems = autoRemoveStaleItems
}

/// Accesses the value associated with the given key for reading and writing. When you assign a value for a key and that key already exists, the cache overwrites the existing value. If the cache doesn’t contain the key, the key and value are added as a new key-value pair. If you assign `nil` as the value for the given key, the cache removes that key and its associated value.
public final subscript(key: Key) -> Value? {
get {
value(for: key)
}
set {
guard let value = newValue else {
removeValue(forKey: key)
return
}

updateValue(value, forKey: key)
}
}

/// Whether the value associated with the `key` is stale. Returns `true` if the key is not in the cache.
/// - Parameter key: The key to find in the cache.
/// - Returns: Whether the value associated with the `key` is stale.
final func isValueStale(forKey key: Key) -> Bool {
guard let value = entry(for: key) else {
return true
}

return Date() > value.expirationDate
}

// MARK: - Internal

/// Accesses the value associated with the given key.
/// - Parameter key: The key to find in the cache.
/// - Returns: The value associated with `key` if `key` is in the cache; otherwise, `nil`.
final func value(for key: Key) -> Value? {
entry(for: key)?.value
}

/// Accesses the entry associated with the given key.
/// - Parameter key: The key to find in the cache.
/// - Returns: The entry associated with `key` if `key` is in the cache; otherwise, `nil`.
final func entry(for key: Key) -> _Entry? {
let key = _Key(key)
return entry(for: key)
}

/// Accesses the entry associated with the given key.
/// - Parameter key: The key to find in the cache.
/// - Returns: The entry associated with `key` if `key` is in the cache; otherwise, `nil`.
private final func entry(for key: _Key) -> _Entry? {
_cache.object(forKey: key)
}

/// Updates the cached value for the given key, or adds the key-value pair to the cache if the key does not exist.
/// - Parameters:
/// - value: The new value to add to the cache.
/// - key: The key to associate with `value`. If `key` already exists in the cache, `value` replaces the existing associated value. If `key` isn’t already a key of the cache, the (`key`, `value`) pair is added.
/// - expirationDate: The date at which the entry will become stale, and be reloaded.
final func updateValue(_ value: Value, forKey key: Key, expirationDate: Date = Date().addingTimeInterval(3600)) {
let _key = _Key(key)
let entry = _Entry(key: key, value: value, expirationDate: expirationDate)
updateEntry(entry, forKey: _key)
}

/// Updates the cached entry for the given key, or adds the entry to the cache if the key does not exist.
/// - Parameters:
/// - entry: The entry to add to the cache.
/// - key: The key to associate with `entry`. If `key` already exists in the cache, `entry` replaces the existing entry. If `key` isn’t already a key of the cache, the entry is added.
func updateEntry(_ entry: _Entry, forKey key: _Key) {
_cache.setObject(entry, forKey: key)
}

/// Removes the given key and its associated value from the cache.
/// - Parameter key: The key to remove along with its associated value.
private final func removeValue(forKey key: Key) {
let key = _Key(key)
removeValue(forKey: key)
}

/// Removes the given key and its associated value from the cache.
/// - Parameter key: The key to remove along with its associated value.
private final func removeValue(forKey key: _Key) {
_cache.removeObject(forKey: key)
}

/// Empties the cache.
private final func removeAll() {
_cache.removeAllObjects()
}

// MARK: - Wrapped Classes

/// A wrapper for a `Key`
final class _Key: NSObject {
/// The wrapped `Key`
let key: Key.ID

/// Creates a new wrapper for a key.
/// - Parameter key: The key to wrap
init(_ key: Key) {
self.key = key.id
}

override var hash: Int {
key.hashValue
}

override func isEqual(_ object: Any?) -> Bool {
guard let value = object as? Self else { return false }
return value.key == key
}
}

/// A wrapper for a key-value pair.
final class _Entry {
/// The key
let key: Key

/// The value
let value: Value

/// The expiration date of the object
let expirationDate: Date

/// Creates a new wrapper for a key-value pair.
/// - Parameters:
/// - key: The key
/// - value: The value
/// - expirationDate: The expiration date, at which point the data will be reloaded
init(key: Key, value: Value, expirationDate: Date) {
self.key = key
self.value = value
self.expirationDate = expirationDate
}
}
}

extension Cache._Entry: Codable where Key: Codable, Value: Codable {}
Loading

0 comments on commit 1814072

Please sign in to comment.