/
Cursor.swift
123 lines (104 loc) · 2.89 KB
/
Cursor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
/**
* Status results for a Cursor
*/
public enum CursorStatus {
case Success
case Failure
case Closed
}
public protocol TypedCursor: SequenceType {
typealias T
var count: Int { get }
var status: CursorStatus { get }
var statusMessage: String { get }
subscript(index: Int) -> T? { get }
func asArray() -> [T]
}
/**
* Provides a generic method of returning some data and status information about a request.
*/
public class Cursor<T>: TypedCursor {
public var count: Int {
get { return 0 }
}
// Extra status information
public var status: CursorStatus
public var statusMessage: String
init(err: NSError) {
self.status = .Failure
self.statusMessage = err.description
}
public init(status: CursorStatus = CursorStatus.Success, msg: String = "") {
self.status = status
self.statusMessage = msg
}
// Collection iteration and access functions
public subscript(index: Int) -> T? {
get { return nil }
}
public func asArray() -> [T] {
var acc = [T]()
acc.reserveCapacity(self.count)
for row in self {
// Shouldn't ever be nil -- that's to allow the generator or subscript to be
// out of range.
if let row = row {
acc.append(row)
}
}
return acc
}
public func generate() -> AnyGenerator<T?> {
var nextIndex = 0
return anyGenerator() {
if (nextIndex >= self.count || self.status != CursorStatus.Success) {
return nil
}
return self[nextIndex++]
}
}
public func close() {
status = .Closed
statusMessage = "Closed"
}
deinit {
if status != CursorStatus.Closed {
close()
}
}
}
/*
* A cursor implementation that wraps an array.
*/
public class ArrayCursor<T> : Cursor<T> {
private var data : [T]
public override var count : Int {
if (status != .Success) {
return 0
}
return data.count
}
public init(data: [T], status: CursorStatus, statusMessage: String) {
self.data = data;
super.init(status: status, msg: statusMessage)
}
public convenience init(data: [T]) {
self.init(data: data, status: CursorStatus.Success, statusMessage: "Success")
}
public override subscript(index: Int) -> T? {
get {
if (index >= data.count || index < 0 || status != .Success) {
return nil
}
return data[index]
}
}
override public func close() {
data = [T]()
super.close()
}
}