no message

This commit is contained in:
Peter 2016-06-19 15:17:53 +03:00
parent d354e968ec
commit 82e22670c0
43 changed files with 624 additions and 781 deletions

View File

@ -42,7 +42,6 @@
D0977F9E1B8234DF009994B2 /* ValueBoxKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0977F9D1B8234DF009994B2 /* ValueBoxKey.swift */; };
D0977FA01B8244D7009994B2 /* SqliteValueBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0977F9F1B8244D7009994B2 /* SqliteValueBox.swift */; };
D0A7D9451C556CFE0016A115 /* MessageHistoryIndexTableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A7D9441C556CFE0016A115 /* MessageHistoryIndexTableTests.swift */; };
D0B76BE71B66639F0095CF45 /* DeferredString.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B76BE61B66639F0095CF45 /* DeferredString.swift */; };
D0C07F6A1B67DB4800966E43 /* SwiftSignalKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0C07F691B67DB4800966E43 /* SwiftSignalKit.framework */; };
D0C674C81CBB11C600183765 /* MessageHistoryReadStateTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C674C71CBB11C600183765 /* MessageHistoryReadStateTable.swift */; };
D0C674CC1CBB14A700183765 /* PeerReadState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C674CB1CBB14A700183765 /* PeerReadState.swift */; };
@ -120,7 +119,6 @@
D0977F9D1B8234DF009994B2 /* ValueBoxKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueBoxKey.swift; sourceTree = "<group>"; };
D0977F9F1B8244D7009994B2 /* SqliteValueBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SqliteValueBox.swift; sourceTree = "<group>"; };
D0A7D9441C556CFE0016A115 /* MessageHistoryIndexTableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageHistoryIndexTableTests.swift; sourceTree = "<group>"; };
D0B76BE61B66639F0095CF45 /* DeferredString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeferredString.swift; sourceTree = "<group>"; };
D0C07F691B67DB4800966E43 /* SwiftSignalKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = SwiftSignalKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
D0C674C71CBB11C600183765 /* MessageHistoryReadStateTable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageHistoryReadStateTable.swift; sourceTree = "<group>"; };
D0C674CB1CBB14A700183765 /* PeerReadState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PeerReadState.swift; sourceTree = "<group>"; };
@ -275,7 +273,6 @@
isa = PBXGroup;
children = (
D0E3A7871B28AE9C00A402D9 /* Coding.swift */,
D0B76BE61B66639F0095CF45 /* DeferredString.swift */,
D0F9E8741C5A334100037222 /* SimpleDictionary.swift */,
D0C9DA381C65782500855278 /* SimpleSet.swift */,
);
@ -441,7 +438,7 @@
attributes = {
LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0710;
LastUpgradeCheck = 0800;
ORGANIZATIONNAME = Telegram;
TargetAttributes = {
D0E3A7491B28A7E300A402D9 = {
@ -537,7 +534,6 @@
D055BD331B7D3D2D00F06C0A /* MediaBox.swift in Sources */,
D0C674CC1CBB14A700183765 /* PeerReadState.swift in Sources */,
D0977F9C1B822DB4009994B2 /* ValueBox.swift in Sources */,
D0B76BE71B66639F0095CF45 /* DeferredString.swift in Sources */,
D075166A1B2EC7FE00AE42E0 /* Database.swift in Sources */,
D07516441B2D9CEF00AE42E0 /* sqlite3.c in Sources */,
);
@ -830,6 +826,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.telegram.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
};
name = Release;
};

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"

View File

@ -12,7 +12,7 @@
<key>PostboxTests.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>12</integer>
<integer>3</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>

View File

@ -5,13 +5,13 @@ final class ChatListIndexTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(peerId: PeerId) -> ValueBoxKey {
private func key(_ peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8)
key.setInt64(0, value: peerId.toInt64())
return key
}
func set(index: MessageIndex) {
func set(_ index: MessageIndex) {
let writeBuffer = WriteBuffer()
var idNamespace: Int32 = index.id.namespace
var idId: Int32 = index.id.id
@ -22,11 +22,11 @@ final class ChatListIndexTable: Table {
self.valueBox.set(self.tableId, key: self.key(index.id.peerId), value: writeBuffer.readBufferNoCopy())
}
func remove(peerId: PeerId) {
func remove(_ peerId: PeerId) {
self.valueBox.remove(self.tableId, key: self.key(peerId))
}
func get(peerId: PeerId) -> MessageIndex? {
func get(_ peerId: PeerId) -> MessageIndex? {
if let value = self.valueBox.get(self.tableId, key: self.key(peerId)) {
var idNamespace: Int32 = 0
var idId: Int32 = 0

View File

@ -32,7 +32,7 @@ private enum ChatListEntryType: Int8 {
final class ChatListTable: Table {
let indexTable: ChatListIndexTable
let emptyMemoryBuffer = MemoryBuffer(memory: nil, capacity: 0, length: 0, freeWhenDone: false)
let emptyMemoryBuffer = MemoryBuffer()
let metadataTable: MessageHistoryMetadataTable
let seedConfiguration: SeedConfiguration
@ -44,7 +44,7 @@ final class ChatListTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(index: MessageIndex, type: ChatListEntryType) -> ValueBoxKey {
private func key(_ index: MessageIndex, type: ChatListEntryType) -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 4 + 4 + 8 + 1)
key.setInt32(0, value: index.timestamp)
key.setInt32(4, value: index.id.namespace)
@ -75,7 +75,7 @@ final class ChatListTable: Table {
}
}
func replay(historyOperationsByPeerId: [PeerId : [MessageHistoryOperation]], messageHistoryTable: MessageHistoryTable, inout operations: [ChatListOperation]) {
func replay(_ historyOperationsByPeerId: [PeerId : [MessageHistoryOperation]], messageHistoryTable: MessageHistoryTable, operations: inout [ChatListOperation]) {
self.ensureInitialized()
for (peerId, _) in historyOperationsByPeerId {
@ -101,7 +101,7 @@ final class ChatListTable: Table {
}
}
func addHole(hole: ChatListHole, inout operations: [ChatListOperation]) {
func addHole(_ hole: ChatListHole, operations: inout [ChatListOperation]) {
self.ensureInitialized()
if self.valueBox.get(self.tableId, key: self.key(hole.index, type: .Hole)) == nil {
@ -110,7 +110,7 @@ final class ChatListTable: Table {
}
}
func replaceHole(index: MessageIndex, hole: ChatListHole?, inout operations: [ChatListOperation]) {
func replaceHole(_ index: MessageIndex, hole: ChatListHole?, operations: inout [ChatListOperation]) {
self.ensureInitialized()
if self.valueBox.get(self.tableId, key: self.key(index, type: .Hole)) != nil {
@ -128,23 +128,23 @@ final class ChatListTable: Table {
}
}
private func justInsertMessage(index: MessageIndex) {
private func justInsertMessage(_ index: MessageIndex) {
self.valueBox.set(self.tableId, key: self.key(index, type: .Message), value: self.emptyMemoryBuffer)
}
private func justRemoveMessage(index: MessageIndex) {
private func justRemoveMessage(_ index: MessageIndex) {
self.valueBox.remove(self.tableId, key: self.key(index, type: .Message))
}
private func justInsertHole(hole: ChatListHole) {
private func justInsertHole(_ hole: ChatListHole) {
self.valueBox.set(self.tableId, key: self.key(hole.index, type: .Hole), value: self.emptyMemoryBuffer)
}
private func justRemoveHole(index: MessageIndex) {
private func justRemoveHole(_ index: MessageIndex) {
self.valueBox.remove(self.tableId, key: self.key(index, type: .Hole))
}
func entriesAround(index: MessageIndex, messageHistoryTable: MessageHistoryTable, count: Int) -> (entries: [ChatListIntermediateEntry], lower: ChatListIntermediateEntry?, upper: ChatListIntermediateEntry?) {
func entriesAround(_ index: MessageIndex, messageHistoryTable: MessageHistoryTable, count: Int) -> (entries: [ChatListIntermediateEntry], lower: ChatListIntermediateEntry?, upper: ChatListIntermediateEntry?) {
self.ensureInitialized()
var lowerEntries: [ChatListIntermediateEntry] = []
@ -217,16 +217,16 @@ final class ChatListTable: Table {
lower = additionalLowerEntries.last
additionalLowerEntries.removeLast()
}
lowerEntries.appendContentsOf(additionalLowerEntries)
lowerEntries.append(contentsOf: additionalLowerEntries)
}
var entries: [ChatListIntermediateEntry] = []
entries.appendContentsOf(lowerEntries.reverse())
entries.appendContentsOf(upperEntries)
entries.append(contentsOf: lowerEntries.reversed())
entries.append(contentsOf: upperEntries)
return (entries: entries, lower: lower, upper: upper)
}
func earlierEntries(index: MessageIndex?, messageHistoryTable: MessageHistoryTable, count: Int) -> [ChatListIntermediateEntry] {
func earlierEntries(_ index: MessageIndex?, messageHistoryTable: MessageHistoryTable, count: Int) -> [ChatListIntermediateEntry] {
self.ensureInitialized()
var entries: [ChatListIntermediateEntry] = []
@ -254,7 +254,7 @@ final class ChatListTable: Table {
return entries
}
func laterEntries(index: MessageIndex?, messageHistoryTable: MessageHistoryTable, count: Int) -> [ChatListIntermediateEntry] {
func laterEntries(_ index: MessageIndex?, messageHistoryTable: MessageHistoryTable, count: Int) -> [ChatListIntermediateEntry] {
self.ensureInitialized()
var entries: [ChatListIntermediateEntry] = []
@ -282,7 +282,7 @@ final class ChatListTable: Table {
return entries
}
func debugList(messageHistoryTable: MessageHistoryTable) -> [ChatListIntermediateEntry] {
func debugList(_ messageHistoryTable: MessageHistoryTable) -> [ChatListIntermediateEntry] {
return self.laterEntries(MessageIndex.absoluteLowerBound(), messageHistoryTable: messageHistoryTable, count: 1000)
}
}

View File

@ -113,7 +113,7 @@ final class MutableChatListView {
self.count = count
}
func replay(operations: [ChatListOperation], context: MutableChatListViewReplayContext) -> Bool {
func replay(_ operations: [ChatListOperation], context: MutableChatListViewReplayContext) -> Bool {
var hasChanges = false
for operation in operations {
switch operation {
@ -142,7 +142,7 @@ final class MutableChatListView {
return hasChanges
}
func add(entry: MutableChatListEntry) -> Bool {
func add(_ entry: MutableChatListEntry) -> Bool {
if self.entries.count == 0 {
self.entries.append(entry)
return true
@ -155,7 +155,7 @@ final class MutableChatListView {
if entry.index < last.index {
if self.earlier == nil || self.earlier!.index < entry.index {
if self.entries.count < self.count {
self.entries.insert(entry, atIndex: 0)
self.entries.insert(entry, at: 0)
} else {
self.earlier = entry
}
@ -179,7 +179,7 @@ final class MutableChatListView {
self.entries.append(entry)
if self.entries.count > self.count {
self.earlier = self.entries[0]
self.entries.removeAtIndex(0)
self.entries.remove(at: 0)
}
return true
}
@ -191,10 +191,10 @@ final class MutableChatListView {
}
i -= 1
}
self.entries.insert(entry, atIndex: i)
self.entries.insert(entry, at: i)
if self.entries.count > self.count {
self.earlier = self.entries[0]
self.entries.removeAtIndex(0)
self.entries.remove(at: 0)
}
return true
} else {
@ -203,7 +203,7 @@ final class MutableChatListView {
}
}
func remove(indices: Set<MessageIndex>, holes: Bool, context: MutableChatListViewReplayContext) -> Bool {
func remove(_ indices: Set<MessageIndex>, holes: Bool, context: MutableChatListViewReplayContext) -> Bool {
var hasChanges = false
if let earlier = self.earlier where indices.contains(earlier.index) {
var match = false
@ -245,7 +245,7 @@ final class MutableChatListView {
match = !holes
}
if match {
self.entries.removeAtIndex(i)
self.entries.remove(at: i)
context.removedEntries = true
hasChanges = true
}
@ -280,11 +280,11 @@ final class MutableChatListView {
}
addedEntries += self.entries
addedEntries.sortInPlace({ $0.index < $1.index })
addedEntries.sort(isOrderedBefore: { $0.index < $1.index })
var i = addedEntries.count - 1
while i >= 1 {
if addedEntries[i].index.id == addedEntries[i - 1].index.id {
addedEntries.removeAtIndex(i)
addedEntries.remove(at: i)
}
i -= 1
}
@ -309,7 +309,7 @@ final class MutableChatListView {
i = anchorIndex
while i >= 0 && i > anchorIndex - self.count {
self.entries.insert(addedEntries[i], atIndex: 0)
self.entries.insert(addedEntries[i], at: 0)
i -= 1
}
@ -352,8 +352,8 @@ final class MutableChatListView {
return nil
}
func updatePeers(peers: [PeerId: Peer]) -> Bool {
var hasChanges = false
func updatePeers(_ peers: [PeerId: Peer]) -> Bool {
let hasChanges = false
/*for i in 0 ..< self.entries.count {
switch self.entries[i] {
case let .MessageEntry(message):
@ -374,7 +374,7 @@ final class MutableChatListView {
return hasChanges
}
func render(renderMessage: IntermediateMessage -> Message) {
func render(_ renderMessage: (IntermediateMessage) -> Message) {
for i in 0 ..< self.entries.count {
if case let .IntermediateMessageEntry(message, combinedReadState) = self.entries[i] {
self.entries[i] = .MessageEntry(renderMessage(message), combinedReadState)

View File

@ -2,13 +2,13 @@ import Foundation
public protocol Coding {
init(decoder: Decoder)
func encode(encoder: Encoder)
func encode(_ encoder: Encoder)
}
private final class EncodableTypeStore {
var dict: [Int32 : Decoder -> Coding] = [:]
var dict: [Int32 : (Decoder) -> Coding] = [:]
func decode(typeHash: Int32, decoder: Decoder) -> Coding? {
func decode(_ typeHash: Int32, decoder: Decoder) -> Coding? {
if let typeDecoder = self.dict[typeHash] {
return typeDecoder(decoder)
} else {
@ -22,7 +22,7 @@ private let typeStore = { () -> EncodableTypeStore in
return _typeStore
}()
public func declareEncodable(type: Any.Type, f: Decoder -> Coding) {
public func declareEncodable(_ type: Any.Type, f: (Decoder) -> Coding) {
let string = "\(type)"
let hash = murMurHashString32(string)
if typeStore.dict[hash] != nil {
@ -31,6 +31,8 @@ public func declareEncodable(type: Any.Type, f: Decoder -> Coding) {
typeStore.dict[murMurHashString32("\(type)")] = f
}
private let emptyMemory = malloc(1)!
public class MemoryBuffer: Equatable, CustomStringConvertible {
var memory: UnsafeMutablePointer<Void>
var capacity: Int
@ -52,15 +54,23 @@ public class MemoryBuffer: Equatable, CustomStringConvertible {
self.freeWhenDone = freeWhenDone
}
public init(data: NSData) {
self.memory = UnsafeMutablePointer(data.bytes)
self.capacity = data.length
self.length = data.length
self.freeWhenDone = false
public init(data: Data) {
if data.count == 0 {
self.memory = emptyMemory
self.capacity = 0
self.length = 0
self.freeWhenDone = false
} else {
self.memory = malloc(data.count)!
data.copyBytes(to: UnsafeMutablePointer<UInt8>(self.memory), count: data.count)
self.capacity = data.count
self.length = data.count
self.freeWhenDone = false
}
}
public init() {
self.memory = nil
self.memory = emptyMemory
self.capacity = 0
self.length = 0
self.freeWhenDone = false
@ -106,23 +116,42 @@ public final class WriteBuffer: MemoryBuffer {
return ReadBuffer(memory: self.memory, length: self.offset, freeWhenDone: false)
}
public func makeData() -> NSData {
return NSData(bytes: self.memory, length: self.offset)
public func makeData() -> Data {
return Data(bytes: UnsafePointer<UInt8>(self.memory), count: self.offset)
}
public func reset() {
self.offset = 0
}
public func write(data: UnsafePointer<Void>, offset: Int, length: Int) {
public func write(_ data: UnsafePointer<Void>, offset: Int, length: Int) {
if self.offset + length > self.capacity {
self.capacity = self.offset + length + 256
self.memory = realloc(self.memory, self.capacity)
if self.length == 0 {
self.memory = malloc(self.capacity)!
} else {
self.memory = realloc(self.memory, self.capacity)
}
}
memcpy(self.memory + self.offset, data + offset, length)
self.offset += length
self.length = self.offset
}
public func write(_ data: Data) {
let length = data.count
if self.offset + length > self.capacity {
self.capacity = self.offset + length + 256
if self.length == 0 {
self.memory = malloc(self.capacity)!
} else {
self.memory = realloc(self.memory, self.capacity)
}
}
data.copyBytes(to: UnsafeMutablePointer<UInt8>(self.memory + offset), count: length)
self.offset += length
self.length = self.offset
}
}
public final class ReadBuffer: MemoryBuffer {
@ -136,16 +165,16 @@ public final class ReadBuffer: MemoryBuffer {
super.init(memory: memoryBufferNoCopy.memory, capacity: memoryBufferNoCopy.length, length: memoryBufferNoCopy.length, freeWhenDone: false)
}
func dataNoCopy() -> NSData {
return NSData(bytesNoCopy: self.memory, length: self.length, freeWhenDone: false)
func dataNoCopy() -> Data {
return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(self.memory), count: self.length, deallocator: .none)
}
func read(data: UnsafeMutablePointer<Void>, offset: Int, length: Int) {
func read(_ data: UnsafeMutablePointer<Void>, offset: Int, length: Int) {
memcpy(data + offset, self.memory + self.offset, length)
self.offset += length
}
func skip(length: Int) {
func skip(_ length: Int) {
self.offset += length
}
@ -190,7 +219,7 @@ public final class Encoder {
return self.buffer.readBufferNoCopy()
}
public func makeData() -> NSData {
public func makeData() -> Data {
return self.buffer.makeData()
}
@ -198,13 +227,13 @@ public final class Encoder {
self.buffer.reset()
}
public func encodeKey(key: StaticString) {
var length: Int8 = Int8(key.byteSize)
public func encodeKey(_ key: StaticString) {
var length: Int8 = Int8(key.utf8CodeUnitCount)
self.buffer.write(&length, offset: 0, length: 1)
self.buffer.write(key.utf8Start, offset: 0, length: Int(length))
}
public func encodeInt32(value: Int32, forKey key: StaticString) {
public func encodeInt32(_ value: Int32, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Int32.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -212,7 +241,7 @@ public final class Encoder {
self.buffer.write(&v, offset: 0, length: 4)
}
public func encodeInt64(value: Int64, forKey key: StaticString) {
public func encodeInt64(_ value: Int64, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Int64.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -220,7 +249,7 @@ public final class Encoder {
self.buffer.write(&v, offset: 0, length: 8)
}
public func encodeBool(value: Bool, forKey key: StaticString) {
public func encodeBool(_ value: Bool, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Bool.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -228,7 +257,7 @@ public final class Encoder {
self.buffer.write(&v, offset: 0, length: 1)
}
public func encodeDouble(value: Double, forKey key: StaticString) {
public func encodeDouble(_ value: Double, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Double.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -236,31 +265,21 @@ public final class Encoder {
self.buffer.write(&v, offset: 0, length: 8)
}
public func encodeString(value: String, forKey key: StaticString) {
public func encodeString(_ value: String, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.String.rawValue
self.buffer.write(&type, offset: 0, length: 1)
let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var length: Int32 = Int32(data.length)
let data = value.data(using: .utf8, allowLossyConversion: true)!
var length: Int32 = Int32(data.count)
self.buffer.write(&length, offset: 0, length: 4)
self.buffer.write(data.bytes, offset: 0, length: Int(length))
self.buffer.write(data)
}
public func encodeString(value: DeferredString, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.String.rawValue
self.buffer.write(&type, offset: 0, length: 1)
let data = value.data
var length: Int32 = Int32(data.length)
self.buffer.write(&length, offset: 0, length: 4)
self.buffer.write(data.bytes, offset: 0, length: Int(length))
}
public func encodeRootObject(value: Coding) {
public func encodeRootObject(_ value: Coding) {
self.encodeObject(value, forKey: "_")
}
public func encodeObject(value: Coding, forKey key: StaticString) {
public func encodeObject(_ value: Coding, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Object.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -277,31 +296,31 @@ public final class Encoder {
self.buffer.write(innerEncoder.buffer.memory, offset: 0, length: Int(length))
}
public func encodeInt32Array(value: [Int32], forKey key: StaticString) {
public func encodeInt32Array(_ value: [Int32], forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Int32Array.rawValue
self.buffer.write(&type, offset: 0, length: 1)
var length: Int32 = Int32(value.count)
self.buffer.write(&length, offset: 0, length: 4)
value.withUnsafeBufferPointer { (data: UnsafeBufferPointer) -> Void in
self.buffer.write(UnsafePointer<Void>(data.baseAddress), offset: 0, length: Int(length) * 4)
self.buffer.write(UnsafePointer<Void>(data.baseAddress!), offset: 0, length: Int(length) * 4)
return
}
}
public func encodeInt64Array(value: [Int64], forKey key: StaticString) {
public func encodeInt64Array(_ value: [Int64], forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Int64Array.rawValue
self.buffer.write(&type, offset: 0, length: 1)
var length: Int32 = Int32(value.count)
self.buffer.write(&length, offset: 0, length: 4)
value.withUnsafeBufferPointer { (data: UnsafeBufferPointer) -> Void in
self.buffer.write(UnsafePointer<Void>(data.baseAddress), offset: 0, length: Int(length) * 8)
self.buffer.write(UnsafePointer<Void>(data.baseAddress!), offset: 0, length: Int(length) * 8)
return
}
}
public func encodeObjectArray<T: Coding>(value: [T], forKey key: StaticString) {
public func encodeObjectArray<T: Coding>(_ value: [T], forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.ObjectArray.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -321,7 +340,7 @@ public final class Encoder {
}
}
public func encodeObjectArray(value: [Coding], forKey key: StaticString) {
public func encodeGenericObjectArray(_ value: [Coding], forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.ObjectArray.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -341,7 +360,7 @@ public final class Encoder {
}
}
public func encodeObjectDictionary<K, V: Coding where K: Coding, K: Hashable>(value: [K : V], forKey key: StaticString) {
public func encodeObjectDictionary<K, V: Coding where K: Coding, K: Hashable>(_ value: [K : V], forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.ObjectDictionary.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -368,7 +387,7 @@ public final class Encoder {
}
}
public func encodeBytes(bytes: WriteBuffer, forKey key: StaticString) {
public func encodeBytes(_ bytes: WriteBuffer, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Bytes.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -377,7 +396,7 @@ public final class Encoder {
self.buffer.write(bytes.memory, offset: 0, length: bytes.offset)
}
public func encodeBytes(bytes: ReadBuffer, forKey key: StaticString) {
public func encodeBytes(_ bytes: ReadBuffer, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Bytes.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -386,7 +405,7 @@ public final class Encoder {
self.buffer.write(bytes.memory, offset: 0, length: bytes.offset)
}
public func encodeBytes(bytes: MemoryBuffer, forKey key: StaticString) {
public func encodeBytes(_ bytes: MemoryBuffer, forKey key: StaticString) {
self.encodeKey(key)
var type: Int8 = ValueType.Bytes.rawValue
self.buffer.write(&type, offset: 0, length: 1)
@ -406,7 +425,7 @@ public final class Decoder {
self.buffer = buffer
}
private class func skipValue(bytes: UnsafePointer<Int8>, inout offset: Int, length: Int, valueType: ValueType) {
private class func skipValue(_ bytes: UnsafePointer<Int8>, offset: inout Int, length: Int, valueType: ValueType) {
switch valueType {
case .Int32:
offset += 4
@ -465,11 +484,11 @@ public final class Decoder {
}
}
private class func positionOnKey(bytes: UnsafePointer<Int8>, inout offset: Int, maxOffset: Int, length: Int, key: StaticString, valueType: ValueType) -> Bool
private class func positionOnKey(_ bytes: UnsafePointer<Int8>, offset: inout Int, maxOffset: Int, length: Int, key: StaticString, valueType: ValueType) -> Bool
{
let startOffset = offset
let keyLength: Int = key.byteSize
let keyLength: Int = key.utf8CodeUnitCount
while (offset < maxOffset)
{
let readKeyLength = bytes[offset]
@ -495,7 +514,7 @@ public final class Decoder {
return false
}
private class func positionOnKey(bytes: UnsafePointer<Int8>, inout offset: Int, maxOffset: Int, length: Int, key: Int16, valueType: ValueType) -> Bool
private class func positionOnKey(_ bytes: UnsafePointer<Int8>, offset: inout Int, maxOffset: Int, length: Int, key: Int16, valueType: ValueType) -> Bool
{
var keyValue = key
let startOffset = offset
@ -526,7 +545,7 @@ public final class Decoder {
return false
}
public func decodeInt32ForKey(key: StaticString) -> Int32 {
public func decodeInt32ForKey(_ key: StaticString) -> Int32 {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int32) {
var value: Int32 = 0
memcpy(&value, self.buffer.memory + self.offset, 4)
@ -537,7 +556,7 @@ public final class Decoder {
}
}
public func decodeInt32ForKey(key: StaticString) -> Int32? {
public func decodeInt32ForKey(_ key: StaticString) -> Int32? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int32) {
var value: Int32 = 0
memcpy(&value, self.buffer.memory + self.offset, 4)
@ -548,7 +567,7 @@ public final class Decoder {
}
}
public func decodeInt64ForKey(key: StaticString) -> Int64 {
public func decodeInt64ForKey(_ key: StaticString) -> Int64 {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int64) {
var value: Int64 = 0
memcpy(&value, self.buffer.memory + self.offset, 8)
@ -559,7 +578,7 @@ public final class Decoder {
}
}
public func decodeInt64ForKey(key: StaticString) -> Int64? {
public func decodeInt64ForKey(_ key: StaticString) -> Int64? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int64) {
var value: Int64 = 0
memcpy(&value, self.buffer.memory + self.offset, 8)
@ -570,7 +589,7 @@ public final class Decoder {
}
}
public func decodeBoolForKey(key: StaticString) -> Bool {
public func decodeBoolForKey(_ key: StaticString) -> Bool {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Bool) {
var value: Int8 = 0
memcpy(&value, self.buffer.memory + self.offset, 1)
@ -581,7 +600,7 @@ public final class Decoder {
}
}
public func decodeDoubleForKey(key: StaticString) -> Double {
public func decodeDoubleForKey(_ key: StaticString) -> Double {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Double) {
var value: Double = 0
memcpy(&value, self.buffer.memory + self.offset, 8)
@ -592,51 +611,25 @@ public final class Decoder {
}
}
public func decodeStringForKey(key: StaticString) -> String {
public func decodeStringForKey(_ key: StaticString) -> String {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .String) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
let data = NSData(bytes: self.buffer.memory + (self.offset + 4), length: Int(length))
let data = Data(bytes: UnsafeMutablePointer<UInt8>(self.buffer.memory).advanced(by: self.offset + 4), count: Int(length))
self.offset += 4 + Int(length)
let value = NSString(data: data, encoding: NSUTF8StringEncoding)
return (value as? String) ?? ""
return String(data: data, encoding: .utf8) ?? ""
} else {
return ""
}
}
public func decodeStringForKey(key: StaticString) -> String? {
public func decodeStringForKey(_ key: StaticString) -> String? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .String) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
let data = NSData(bytes: self.buffer.memory + (self.offset + 4), length: Int(length))
let data = Data(bytes: UnsafeMutablePointer<UInt8>(self.buffer.memory).advanced(by: self.offset + 4), count: Int(length))
self.offset += 4 + Int(length)
let value = NSString(data: data, encoding: NSUTF8StringEncoding)
return value as? String
} else {
return nil
}
}
public func decodeStringForKey(key: StaticString) -> DeferredString {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .String) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
let data = NSData(bytes: self.buffer.memory + (self.offset + 4), length: Int(length))
self.offset += 4 + Int(length)
return DeferredStringValue(data)
} else {
return DeferredStringValue("")
}
}
public func decodeStringForKey(key: StaticString) -> DeferredString? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .String) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
let data = NSData(bytes: self.buffer.memory + (self.offset + 4), length: Int(length))
self.offset += 4 + Int(length)
return DeferredStringValue(data)
return String(data: data, encoding: .utf8)
} else {
return nil
}
@ -646,7 +639,7 @@ public final class Decoder {
return self.decodeObjectForKey("_")
}
public func decodeObjectForKey(key: StaticString) -> Coding? {
public func decodeObjectForKey(_ key: StaticString) -> Coding? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Object) {
var typeHash: Int32 = 0
memcpy(&typeHash, self.buffer.memory + self.offset, 4)
@ -664,7 +657,7 @@ public final class Decoder {
}
}
public func decodeObjectForKey(key: StaticString, decoder: Decoder -> Coding) -> Coding? {
public func decodeObjectForKey(_ key: StaticString, decoder: (Decoder) -> Coding) -> Coding? {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Object) {
var typeHash: Int32 = 0
memcpy(&typeHash, self.buffer.memory + self.offset, 4)
@ -682,7 +675,7 @@ public final class Decoder {
}
}
public func decodeInt32ArrayForKey(key: StaticString) -> [Int32] {
public func decodeInt32ArrayForKey(_ key: StaticString) -> [Int32] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int32Array) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -702,7 +695,7 @@ public final class Decoder {
}
}
public func decodeInt64ArrayForKey(key: StaticString) -> [Int64] {
public func decodeInt64ArrayForKey(_ key: StaticString) -> [Int64] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Int64Array) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -722,7 +715,7 @@ public final class Decoder {
}
}
public func decodeObjectArrayWithDecoderForKey<T where T: Coding>(key: StaticString) -> [T] {
public func decodeObjectArrayWithDecoderForKey<T where T: Coding>(_ key: StaticString) -> [T] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .ObjectArray) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -731,7 +724,7 @@ public final class Decoder {
var array: [T] = []
array.reserveCapacity(Int(length))
var failed = false
let failed = false
var i: Int32 = 0
while i < length {
var typeHash: Int32 = 0
@ -745,11 +738,7 @@ public final class Decoder {
self.offset += 4 + Int(objectLength)
if !failed {
if let object = T(decoder: innerDecoder) as? T {
array.append(object)
} else {
failed = true
}
array.append(T(decoder: innerDecoder))
}
i += 1
@ -765,7 +754,7 @@ public final class Decoder {
}
}
public func decodeObjectArrayForKey<T where T: Coding>(key: StaticString) -> [T] {
public func decodeObjectArrayForKey<T where T: Coding>(_ key: StaticString) -> [T] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .ObjectArray) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -808,7 +797,7 @@ public final class Decoder {
}
}
public func decodeObjectArrayForKey(key: StaticString) -> [Coding] {
public func decodeObjectArrayForKey(_ key: StaticString) -> [Coding] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .ObjectArray) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -851,7 +840,7 @@ public final class Decoder {
}
}
public func decodeObjectDictionaryForKey<K, V: Coding where K: Coding, K: Hashable>(key: StaticString) -> [K : V] {
public func decodeObjectDictionaryForKey<K, V: Coding where K: Coding, K: Hashable>(_ key: StaticString) -> [K : V] {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .ObjectDictionary) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)
@ -905,7 +894,7 @@ public final class Decoder {
}
}
public func decodeBytesForKeyNoCopy(key: StaticString) -> ReadBuffer! {
public func decodeBytesForKeyNoCopy(_ key: StaticString) -> ReadBuffer! {
if Decoder.positionOnKey(UnsafePointer<Int8>(self.buffer.memory), offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Bytes) {
var length: Int32 = 0
memcpy(&length, self.buffer.memory + self.offset, 4)

View File

@ -1,124 +0,0 @@
import Foundation
public protocol DeferredString {
var data: NSData { get }
var string: String { get }
}
private final class DeferredStringImpl {
var string: String!
var data: NSData!
var lock: OSSpinLock = 0
init(string: String!, data: NSData!) {
self.string = string
self.data = data
}
}
public final class DeferredStringValue: DeferredString, CustomStringConvertible, StringLiteralConvertible {
private var impl: DeferredStringImpl
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.impl = DeferredStringImpl(string: "\(value)", data: nil)
}
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.impl = DeferredStringImpl(string: value, data: nil)
}
public init(stringLiteral value: StringLiteralType) {
self.impl = DeferredStringImpl(string: value, data: nil)
}
public init(_ string: String) {
self.impl = DeferredStringImpl(string: string, data: nil)
}
public init(_ data: NSData) {
self.impl = DeferredStringImpl(string: nil, data: data)
}
public var description: String {
return self.string
}
public var data: NSData {
if isUniquelyReferencedNonObjC(&self.impl) {
let value: NSData
if impl.data != nil {
value = impl.data
} else if impl.string != nil {
value = impl.string.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData()
impl.data = value
} else {
value = NSData()
}
return value
} else {
let value: NSData
OSSpinLockLock(&impl.lock)
if impl.data != nil {
value = impl.data
} else if impl.string != nil {
value = impl.string.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData()
impl.data = value
} else {
value = NSData()
}
OSSpinLockUnlock(&impl.lock)
return value
}
}
public var string: String {
if isUniquelyReferencedNonObjC(&self.impl) {
let value: String
if impl.string != nil {
value = impl.string
} else if impl.data != nil {
let fromData = NSString(data: impl.data, encoding: NSUTF8StringEncoding)
if fromData == nil {
value = ""
impl.string = value
} else {
value = fromData as! String
impl.string = value
}
} else {
value = ""
}
return value
} else {
let value: String
OSSpinLockLock(&impl.lock)
if impl.string != nil {
value = impl.string
} else if impl.data != nil {
let fromData = NSString(data: impl.data, encoding: NSUTF8StringEncoding)
if fromData == nil {
value = ""
impl.string = value
} else {
value = fromData as! String
impl.string = value
}
} else {
value = ""
}
OSSpinLockUnlock(&impl.lock)
return value
}
}
}

View File

@ -12,12 +12,12 @@ final class GlobalMessageIdsTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(id: Int32) -> ValueBoxKey {
private func key(_ id: Int32) -> ValueBoxKey {
self.sharedKey.setInt32(0, value: id)
return self.sharedKey
}
func set(globalId: Int32, id: MessageId) {
func set(_ globalId: Int32, id: MessageId) {
self.sharedBuffer.reset()
var idPeerId: Int64 = id.peerId.toInt64()
var idNamespace: Int32 = id.namespace
@ -26,7 +26,7 @@ final class GlobalMessageIdsTable: Table {
self.valueBox.set(self.tableId, key: self.key(globalId), value: self.sharedBuffer)
}
func get(globalId: Int32) -> MessageId? {
func get(_ globalId: Int32) -> MessageId? {
if let value = self.valueBox.get(self.tableId, key: self.key(globalId)) {
var idPeerId: Int64 = 0
var idNamespace: Int32 = 0
@ -37,7 +37,7 @@ final class GlobalMessageIdsTable: Table {
return nil
}
func remove(globalId: Int32) {
func remove(_ globalId: Int32) {
self.valueBox.remove(self.tableId, key: self.key(globalId))
}
}
}

View File

@ -5,22 +5,22 @@ final class KeychainTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(string: String) -> ValueBoxKey {
private func key(_ string: String) -> ValueBoxKey {
return ValueBoxKey(string)
}
func get(key: String) -> NSData? {
func get(_ key: String) -> Data? {
if let value = self.valueBox.get(self.tableId, key: self.key(key)) {
return NSData(bytes: value.memory, length: value.length)
return Data(bytes: UnsafePointer<UInt8>(value.memory), count: value.length)
}
return nil
}
func set(key: String, value: NSData) {
func set(_ key: String, value: Data) {
self.valueBox.set(self.tableId, key: self.key(key), value: MemoryBuffer(data: value))
}
func remove(key: String) {
func remove(_ key: String) {
self.valueBox.remove(self.tableId, key: self.key(key))
}
}

View File

@ -6,9 +6,9 @@ private struct LmdbTable {
}
private struct LmdbCursor {
var cursor: COpaquePointer
var cursor: OpaquePointer!
func seekTo(key: ValueBoxKey, forward: Bool) -> (ValueBoxKey, ReadBuffer)? {
func seekTo(_ key: ValueBoxKey, forward: Bool) -> (ValueBoxKey, ReadBuffer)? {
var mdbKey = MDB_val()
var mdbData = MDB_val()
@ -23,7 +23,7 @@ private struct LmdbCursor {
let actualKey = ValueBoxKey(length: mdbKey.mv_size)
memcpy(actualKey.memory, mdbKey.mv_data, mdbKey.mv_size)
let value = malloc(mdbData.mv_size)
let value = malloc(mdbData.mv_size)!
memcpy(value, mdbData.mv_data, mdbData.mv_size)
return (actualKey, ReadBuffer(memory: value, length: mdbData.mv_size, freeWhenDone: true))
@ -53,7 +53,7 @@ private struct LmdbCursor {
let actualKey = ValueBoxKey(length: mdbKey.mv_size)
memcpy(actualKey.memory, mdbKey.mv_data, mdbKey.mv_size)
let value = malloc(mdbData.mv_size)
let value = malloc(mdbData.mv_size)!
memcpy(value, mdbData.mv_data, mdbData.mv_size)
return (actualKey, ReadBuffer(memory: value, length: mdbData.mv_size, freeWhenDone: true))
@ -79,7 +79,7 @@ private struct LmdbCursor {
let actualKey = ValueBoxKey(length: mdbKey.mv_size)
memcpy(actualKey.memory, mdbKey.mv_data, mdbKey.mv_size)
let value = malloc(mdbData.mv_size)
let value = malloc(mdbData.mv_size)!
memcpy(value, mdbData.mv_data, mdbData.mv_size)
return (actualKey, ReadBuffer(memory: value, length: mdbData.mv_size, freeWhenDone: true))
@ -93,10 +93,10 @@ private struct LmdbCursor {
}
public final class LmdbValueBox: ValueBox {
private var env: COpaquePointer = nil
private var env: OpaquePointer? = nil
private var tables: [Int32 : LmdbTable] = [:]
private var sharedTxn: COpaquePointer = nil
private var sharedTxn: OpaquePointer? = nil
private var readQueryTime: CFAbsoluteTime = 0.0
private var writeQueryTime: CFAbsoluteTime = 0.0
@ -113,10 +113,10 @@ public final class LmdbValueBox: ValueBox {
var createDirectory = false
var isDirectory: ObjCBool = false as ObjCBool
if NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) {
if FileManager.default().fileExists(atPath: path, isDirectory: &isDirectory) {
if !isDirectory {
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
try FileManager.default().removeItem(atPath: path)
} catch _ { }
createDirectory = true
}
@ -127,7 +127,7 @@ public final class LmdbValueBox: ValueBox {
if createDirectory {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch _ { }
}
@ -154,7 +154,7 @@ public final class LmdbValueBox: ValueBox {
mdb_env_close(self.env)
}
private func createTableWithName(name: Int32) -> LmdbTable? {
private func createTableWithName(_ name: Int32) -> LmdbTable? {
var dbi = MDB_dbi()
let result = mdb_dbi_open(self.sharedTxn, "\(name)", UInt32(MDB_CREATE), &dbi)
@ -204,7 +204,7 @@ public final class LmdbValueBox: ValueBox {
}
}
public func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape values: (ValueBoxKey, ReadBuffer) -> Bool, limit: Int) {
public func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, values: @noescape(ValueBoxKey, ReadBuffer) -> Bool, limit: Int) {
if start == end || limit == 0 {
return
}
@ -225,7 +225,7 @@ public final class LmdbValueBox: ValueBox {
if let nativeTable = nativeTable {
var startTime = CFAbsoluteTimeGetCurrent()
var cursorPtr: COpaquePointer = nil
var cursorPtr: OpaquePointer? = nil
let result = mdb_cursor_open(self.sharedTxn, nativeTable.dbi, &cursorPtr)
if result != MDB_SUCCESS {
print("(LmdbValueBox mdb_cursor_open failed with \(result))")
@ -247,7 +247,7 @@ public final class LmdbValueBox: ValueBox {
var count = 0
if value != nil && value!.0 < end {
count += 1
values(value!.0, value!.1)
let _ = values(value!.0, value!.1)
}
while value != nil && value!.0 < end && count < limit {
@ -261,7 +261,7 @@ public final class LmdbValueBox: ValueBox {
if value != nil && value!.0 < end {
count += 1
values(value!.0, value!.1)
let _ = values(value!.0, value!.1)
}
}
} else {
@ -280,7 +280,7 @@ public final class LmdbValueBox: ValueBox {
var count = 0
if value != nil && value!.0 > end {
count += 1
values(value!.0, value!.1)
let _ = values(value!.0, value!.1)
}
while value != nil && value!.0 > end && count < limit {
@ -294,7 +294,7 @@ public final class LmdbValueBox: ValueBox {
if value != nil && value!.0 > end {
count += 1
values(value!.0, value!.1)
let _ = values(value!.0, value!.1)
}
}
}
@ -312,13 +312,13 @@ public final class LmdbValueBox: ValueBox {
}
}
public func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape keys: ValueBoxKey -> Bool, limit: Int) {
public func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, keys: @noescape(ValueBoxKey) -> Bool, limit: Int) {
self.range(table, start: start, end: end, values: { key, _ in
return keys(key)
}, limit: limit)
}
public func get(table: Int32, key: ValueBoxKey) -> ReadBuffer? {
public func get(_ table: Int32, key: ValueBoxKey) -> ReadBuffer? {
let startTime = CFAbsoluteTimeGetCurrent()
var commit = false
@ -347,7 +347,7 @@ public final class LmdbValueBox: ValueBox {
let result = mdb_get(self.sharedTxn, nativeTable.dbi, &mdbKey, &mdbData)
if result == MDB_SUCCESS {
let value = malloc(mdbData.mv_size)
let value = malloc(mdbData.mv_size)!
memcpy(value, mdbData.mv_data, mdbData.mv_size)
resultValue = ReadBuffer(memory: value, length: mdbData.mv_size, freeWhenDone: true)
} else {
@ -366,11 +366,11 @@ public final class LmdbValueBox: ValueBox {
return resultValue
}
public func exists(table: Int32, key: ValueBoxKey) -> Bool {
public func exists(_ table: Int32, key: ValueBoxKey) -> Bool {
return self.get(table, key: key) != nil
}
public func set(table: Int32, key: ValueBoxKey, value: MemoryBuffer) {
public func set(_ table: Int32, key: ValueBoxKey, value: MemoryBuffer) {
let startTime = CFAbsoluteTimeGetCurrent()
var commit = false
@ -409,7 +409,7 @@ public final class LmdbValueBox: ValueBox {
writeQueryTime += CFAbsoluteTimeGetCurrent() - startTime
}
public func remove(table: Int32, key: ValueBoxKey) {
public func remove(_ table: Int32, key: ValueBoxKey) {
let startTime = CFAbsoluteTimeGetCurrent()
var commit = false

View File

@ -35,14 +35,14 @@ public struct MediaId: Hashable, CustomStringConvertible {
buffer.offset += 12
}
public func encodeToBuffer(buffer: WriteBuffer) {
public func encodeToBuffer(_ buffer: WriteBuffer) {
var namespace = self.namespace
var id = self.id
buffer.write(&namespace, offset: 0, length: 4);
buffer.write(&id, offset: 0, length: 8);
}
public static func encodeArrayToBuffer(array: [MediaId], buffer: WriteBuffer) {
public static func encodeArrayToBuffer(_ array: [MediaId], buffer: WriteBuffer) {
var length: Int32 = Int32(array.count)
buffer.write(&length, offset: 0, length: 4)
for id in array {
@ -50,7 +50,7 @@ public struct MediaId: Hashable, CustomStringConvertible {
}
}
public static func decodeArrayFromBuffer(buffer: ReadBuffer) -> [MediaId] {
public static func decodeArrayFromBuffer(_ buffer: ReadBuffer) -> [MediaId] {
var length: Int32 = 0
memcpy(&length, buffer.memory, 4)
buffer.offset += 4
@ -72,5 +72,5 @@ public protocol Media: Coding {
var id: MediaId? { get }
var peerIds: [PeerId] { get }
func isEqual(other: Media) -> Bool
func isEqual(_ other: Media) -> Bool
}

View File

@ -3,13 +3,13 @@ import SwiftSignalKit
private final class ResourceStatusContext {
var status: MediaResourceStatus?
let subscribers = Bag<MediaResourceStatus -> Void>()
let subscribers = Bag<(MediaResourceStatus) -> Void>()
}
private final class ResourceDataContext {
var data: MediaResourceData
let progresiveDataSubscribers = Bag<MediaResourceData -> Void>()
let completeDataSubscribers = Bag<MediaResourceData -> Void>()
let progresiveDataSubscribers = Bag<(MediaResourceData) -> Void>()
let completeDataSubscribers = Bag<(MediaResourceData) -> Void>()
var fetchDisposable: Disposable?
let fetchSubscribers = Bag<Void>()
@ -19,7 +19,7 @@ private final class ResourceDataContext {
}
}
private func fileSize(path: String) -> Int {
private func fileSize(_ path: String) -> Int {
var value = stat()
stat(path, &value)
return Int(value.st_size)
@ -35,8 +35,8 @@ public final class MediaBox {
private var statusContexts: [String: ResourceStatusContext] = [:]
private var dataContexts: [String: ResourceDataContext] = [:]
private var wrappedFetchResource = Promise<(MediaResource, Int) -> Signal<NSData, NoError>>()
public var fetchResource: ((MediaResource, Int) -> Signal<NSData, NoError>)? {
private var wrappedFetchResource = Promise<(MediaResource, Int) -> Signal<Data, NoError>>()
public var fetchResource: ((MediaResource, Int) -> Signal<Data, NoError>)? {
didSet {
if let fetchResource = self.fetchResource {
wrappedFetchResource.set(.single(fetchResource))
@ -47,22 +47,22 @@ public final class MediaBox {
}
lazy var ensureDirectoryCreated: Void = {
try! NSFileManager.defaultManager().createDirectoryAtPath(self.basePath, withIntermediateDirectories: true, attributes: nil)
try! FileManager.default().createDirectory(atPath: self.basePath, withIntermediateDirectories: true, attributes: nil)
}()
public init(basePath: String) {
self.basePath = basePath
}
private func pathForId(id: String) -> String {
private func pathForId(_ id: String) -> String {
return "\(self.basePath)/\(id)"
}
public func resourceStatus(resource: MediaResource) -> Signal<MediaResourceStatus, NoError> {
public func resourceStatus(_ resource: MediaResource) -> Signal<MediaResourceStatus, NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.statusQueue.dispatch {
self.statusQueue.async {
let statusContext: ResourceStatusContext
if let current = self.statusContexts[resource.id] {
statusContext = current
@ -78,7 +78,7 @@ public final class MediaBox {
if let status = statusContext.status {
subscriber.putNext(status)
} else {
self.dataQueue.dispatch {
self.dataQueue.async {
let status: MediaResourceStatus
let path = self.pathForId(resource.id)
@ -98,7 +98,7 @@ public final class MediaBox {
}
}
self.statusQueue.dispatch {
self.statusQueue.async {
if let statusContext = self.statusContexts[resource.id] where statusContext.status == nil {
statusContext.status = status
@ -111,11 +111,11 @@ public final class MediaBox {
}
disposable.set(ActionDisposable {
self.statusQueue.dispatch {
self.statusQueue.async {
if let current = self.statusContexts[resource.id] {
current.subscribers.remove(index)
if current.subscribers.isEmpty {
self.statusContexts.removeValueForKey(resource.id)
self.statusContexts.removeValue(forKey: resource.id)
}
}
}
@ -126,11 +126,11 @@ public final class MediaBox {
}
}
public func resourceData(resource: MediaResource, complete: Bool = true) -> Signal<MediaResourceData, NoError> {
public func resourceData(_ resource: MediaResource, complete: Bool = true) -> Signal<MediaResourceData, NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.dataQueue.dispatch {
self.dataQueue.async {
let path = self.pathForId(resource.id)
let currentSize = fileSize(path)
@ -146,7 +146,7 @@ public final class MediaBox {
self.dataContexts[resource.id] = dataContext
}
let index: Bag<MediaResourceData -> Void>.Index
let index: Bag<(MediaResourceData) -> Void>.Index
if complete {
index = dataContext.completeDataSubscribers.add { data in
subscriber.putNext(data)
@ -170,7 +170,7 @@ public final class MediaBox {
}
disposable.set(ActionDisposable {
self.dataQueue.dispatch {
self.dataQueue.async {
if let dataContext = self.dataContexts[resource.id] {
if complete {
dataContext.completeDataSubscribers.remove(index)
@ -179,7 +179,7 @@ public final class MediaBox {
}
if dataContext.progresiveDataSubscribers.isEmpty && dataContext.completeDataSubscribers.isEmpty && dataContext.fetchSubscribers.isEmpty {
self.dataContexts.removeValueForKey(resource.id)
self.dataContexts.removeValue(forKey: resource.id)
}
}
}
@ -191,11 +191,11 @@ public final class MediaBox {
}
}
public func fetchedResource(resource: MediaResource, interactive: Bool) -> Signal<Void, NoError> {
public func fetchedResource(_ resource: MediaResource, interactive: Bool) -> Signal<Void, NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.dataQueue.dispatch {
self.dataQueue.async {
let path = self.pathForId(resource.id)
let currentSize = fileSize(path)
@ -214,7 +214,7 @@ public final class MediaBox {
if dataContext.fetchDisposable == nil {
let status: MediaResourceStatus = .Fetching(progress: Float(currentSize) / Float(resource.size))
self.statusQueue.dispatch {
self.statusQueue.async {
if let statusContext = self.statusContexts[resource.id] {
statusContext.status = status
for subscriber in statusContext.subscribers.copyItems() {
@ -225,14 +225,14 @@ public final class MediaBox {
var offset = currentSize
var fd: Int32?
dataContext.fetchDisposable = (self.wrappedFetchResource.get() |> mapToSignal { fetch -> Signal<NSData, NoError> in
dataContext.fetchDisposable = (self.wrappedFetchResource.get() |> mapToSignal { fetch -> Signal<Data, NoError> in
return fetch(resource, offset)
} |> afterDisposed {
if let fd = fd {
close(fd)
}
}).start(next: { data in
self.dataQueue.dispatch {
self.dataQueue.async {
let _ = self.ensureDirectoryCreated
if fd == nil {
@ -243,9 +243,11 @@ public final class MediaBox {
}
if let fd = fd {
write(fd, data.bytes, data.length)
data.withUnsafeBytes { bytes in
write(fd, bytes, data.count)
}
offset += data.length
offset += data.count
let updatedSize = offset
for subscriber in dataContext.progresiveDataSubscribers.copyItems() {
@ -265,7 +267,7 @@ public final class MediaBox {
status = .Fetching(progress: Float(updatedSize) / Float(resource.size))
}
self.statusQueue.dispatch {
self.statusQueue.async {
if let statusContext = self.statusContexts[resource.id] {
statusContext.status = status
for subscriber in statusContext.subscribers.copyItems() {
@ -279,7 +281,7 @@ public final class MediaBox {
}
disposable.set(ActionDisposable {
self.dataQueue.dispatch {
self.dataQueue.async {
if let dataContext = self.dataContexts[resource.id] {
dataContext.fetchSubscribers.remove(index)
@ -295,7 +297,7 @@ public final class MediaBox {
status = .Remote
}
self.statusQueue.dispatch {
self.statusQueue.async {
if let statusContext = self.statusContexts[resource.id] where statusContext.status != status {
statusContext.status = status
for subscriber in statusContext.subscribers.copyItems() {
@ -306,7 +308,7 @@ public final class MediaBox {
}
if dataContext.completeDataSubscribers.isEmpty && dataContext.progresiveDataSubscribers.isEmpty && dataContext.fetchSubscribers.isEmpty {
self.dataContexts.removeValueForKey(resource.id)
self.dataContexts.removeValue(forKey: resource.id)
}
}
}
@ -318,8 +320,8 @@ public final class MediaBox {
}
}
public func cancelInteractiveResourceFetch(resource: MediaResource) {
self.dataQueue.dispatch {
public func cancelInteractiveResourceFetch(_ resource: MediaResource) {
self.dataQueue.async {
if let dataContext = self.dataContexts[resource.id] where dataContext.fetchDisposable != nil {
dataContext.fetchDisposable?.dispose()
dataContext.fetchDisposable = nil
@ -332,7 +334,7 @@ public final class MediaBox {
status = .Remote
}
self.statusQueue.dispatch {
self.statusQueue.async {
if let statusContext = self.statusContexts[resource.id] where statusContext.status != status {
statusContext.status = status
for subscriber in statusContext.subscribers.copyItems() {

View File

@ -7,11 +7,11 @@ final class MediaCleanupTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
func add(media: Media, sharedEncoder: Encoder = Encoder()) {
func add(_ media: Media, sharedEncoder: Encoder = Encoder()) {
debugMedia.append(media)
}
func debugList() -> [Media] {
return self.debugMedia
}
}
}

View File

@ -43,7 +43,7 @@ public struct MessageId: Hashable, Comparable, CustomStringConvertible {
buffer.offset += 16
}
public func encodeToBuffer(buffer: WriteBuffer) {
public func encodeToBuffer(_ buffer: WriteBuffer) {
var peerIdNamespace = self.peerId.namespace
var peerIdId = self.peerId.id
var namespace = self.namespace
@ -54,7 +54,7 @@ public struct MessageId: Hashable, Comparable, CustomStringConvertible {
buffer.write(&id, offset: 0, length: 4);
}
public static func encodeArrayToBuffer(array: [MessageId], buffer: WriteBuffer) {
public static func encodeArrayToBuffer(_ array: [MessageId], buffer: WriteBuffer) {
var length: Int32 = Int32(array.count)
buffer.write(&length, offset: 0, length: 4)
for id in array {
@ -62,7 +62,7 @@ public struct MessageId: Hashable, Comparable, CustomStringConvertible {
}
}
public static func decodeArrayFromBuffer(buffer: ReadBuffer) -> [MessageId] {
public static func decodeArrayFromBuffer(_ buffer: ReadBuffer) -> [MessageId] {
var length: Int32 = 0
memcpy(&length, buffer.memory, 4)
buffer.offset += 4
@ -157,7 +157,7 @@ public func <(lhs: MessageIndex, rhs: MessageIndex) -> Bool {
return lhs.id.id < rhs.id.id
}
public struct MessageTags: OptionSetType {
public struct MessageTags: OptionSet {
public var rawValue: UInt32
public init(rawValue: UInt32) {
@ -171,7 +171,7 @@ public struct MessageTags: OptionSetType {
public static let All = MessageTags(rawValue: 0xffffffff)
}
public struct MessageFlags: OptionSetType {
public struct MessageFlags: OptionSet {
public var rawValue: UInt32
public init(rawValue: UInt32) {
@ -292,7 +292,7 @@ public final class Message {
}
}
public struct StoreMessageFlags: OptionSetType {
public struct StoreMessageFlags: OptionSet {
public var rawValue: UInt32
public init(rawValue: UInt32) {

View File

@ -73,7 +73,7 @@ private let HistoryEntryTypeMessage: Int8 = 0
private let HistoryEntryTypeHole: Int8 = 1
private let HistoryEntryMessageFlagIncoming: Int8 = 1 << 1
private func readHistoryIndexEntry(peerId: PeerId, namespace: MessageId.Namespace, key: ValueBoxKey, value: ReadBuffer) -> HistoryIndexEntry {
private func readHistoryIndexEntry(_ peerId: PeerId, namespace: MessageId.Namespace, key: ValueBoxKey, value: ReadBuffer) -> HistoryIndexEntry {
var flags: Int8 = 0
value.read(&flags, offset: 0, length: 1)
var timestamp: Int32 = 0
@ -113,7 +113,7 @@ final class MessageHistoryIndexTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(id: MessageId) -> ValueBoxKey {
private func key(_ id: MessageId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 4 + 4)
key.setInt64(0, value: id.peerId.toInt64())
key.setInt32(8, value: id.namespace)
@ -121,21 +121,21 @@ final class MessageHistoryIndexTable: Table {
return key
}
private func lowerBound(peerId: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
private func lowerBound(_ peerId: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 4)
key.setInt64(0, value: peerId.toInt64())
key.setInt32(8, value: namespace)
return key
}
private func upperBound(peerId: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
private func upperBound(_ peerId: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 4)
key.setInt64(0, value: peerId.toInt64())
key.setInt32(8, value: namespace)
return key.successor
}
private func ensureInitialized(peerId: PeerId, inout operations: [MessageHistoryIndexOperation]) {
private func ensureInitialized(_ peerId: PeerId, operations: inout [MessageHistoryIndexOperation]) {
if !self.metadataTable.isInitialized(peerId) {
for namespace in self.seedConfiguration.initializeMessageNamespacesWithHoles {
self.justInsertHole(MessageHistoryHole(stableId: self.metadataTable.getNextStableMessageIndexId(), maxIndex: MessageIndex(id: MessageId(peerId: peerId, namespace: namespace, id: Int32.max), timestamp: Int32.max), min: 1, tags: MessageTags.All.rawValue), operations: &operations)
@ -145,7 +145,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func addHole(id: MessageId, inout operations: [MessageHistoryIndexOperation]) {
func addHole(_ id: MessageId, operations: inout [MessageHistoryIndexOperation]) {
self.ensureInitialized(id.peerId, operations: &operations)
let adjacent = self.adjacentItems(id)
@ -186,7 +186,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func addMessages(messages: [InternalStoreMessage], location: AddMessagesLocation, inout operations: [MessageHistoryIndexOperation]) {
func addMessages(_ messages: [InternalStoreMessage], location: AddMessagesLocation, operations: inout [MessageHistoryIndexOperation]) {
if messages.count == 0 {
return
}
@ -281,7 +281,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func removeMessage(id: MessageId, inout operations: [MessageHistoryIndexOperation]) {
func removeMessage(_ id: MessageId, operations: inout [MessageHistoryIndexOperation]) {
self.ensureInitialized(id.peerId, operations: &operations)
if let existingEntry = self.get(id) {
@ -332,7 +332,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func updateMessage(id: MessageId, message: InternalStoreMessage, inout operations: [MessageHistoryIndexOperation]) {
func updateMessage(_ id: MessageId, message: InternalStoreMessage, operations: inout [MessageHistoryIndexOperation]) {
if let previousEntry = self.get(id), case let .Message(previousIndex) = previousEntry {
if previousIndex != MessageIndex(message) {
var intermediateOperations: [MessageHistoryIndexOperation] = []
@ -355,7 +355,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func fillHole(id: MessageId, fillType: HoleFill, tagMask: MessageTags?, messages: [InternalStoreMessage], inout operations: [MessageHistoryIndexOperation]) {
func fillHole(_ id: MessageId, fillType: HoleFill, tagMask: MessageTags?, messages: [InternalStoreMessage], operations: inout [MessageHistoryIndexOperation]) {
self.ensureInitialized(id.peerId, operations: &operations)
var upperItem: HistoryIndexEntry?
@ -364,7 +364,7 @@ final class MessageHistoryIndexTable: Table {
return true
}, limit: 1)
let sortedByIdMessages = messages.sort({$0.id < $1.id})
let sortedByIdMessages = messages.sorted(isOrderedBefore: {$0.id < $1.id})
var remainingMessages = sortedByIdMessages
@ -382,7 +382,7 @@ final class MessageHistoryIndexTable: Table {
let message = remainingMessages[i]
if message.id.id >= upperHole.min && message.id.id <= upperHole.maxIndex.id.id {
messagesInRange.append(message)
remainingMessages.removeAtIndex(i)
remainingMessages.remove(at: i)
} else {
i += 1
}
@ -460,7 +460,7 @@ final class MessageHistoryIndexTable: Table {
}
self.justInsertMessage(message, operations: &operations)
remainingMessages.removeAtIndex(i)
remainingMessages.remove(at: i)
} else {
i += 1
}
@ -522,7 +522,7 @@ final class MessageHistoryIndexTable: Table {
}
}
private func justInsertHole(hole: MessageHistoryHole, inout operations: [MessageHistoryIndexOperation]) {
private func justInsertHole(_ hole: MessageHistoryHole, operations: inout [MessageHistoryIndexOperation]) {
let value = WriteBuffer()
var flags: Int8 = HistoryEntryTypeHole
var timestamp: Int32 = hole.maxIndex.timestamp
@ -539,7 +539,7 @@ final class MessageHistoryIndexTable: Table {
operations.append(.InsertHole(hole))
}
private func justInsertMessage(message: InternalStoreMessage, inout operations: [MessageHistoryIndexOperation]) {
private func justInsertMessage(_ message: InternalStoreMessage, operations: inout [MessageHistoryIndexOperation]) {
let index = MessageIndex(id: message.id, timestamp: message.timestamp)
let value = WriteBuffer()
@ -558,7 +558,7 @@ final class MessageHistoryIndexTable: Table {
}
}
private func justRemove(index: MessageIndex, inout operations: [MessageHistoryIndexOperation]) {
private func justRemove(_ index: MessageIndex, operations: inout [MessageHistoryIndexOperation]) {
self.valueBox.remove(self.tableId, key: self.key(index.id))
operations.append(.Remove(index))
@ -567,7 +567,7 @@ final class MessageHistoryIndexTable: Table {
}
}
func adjacentItems(id: MessageId, bindUpper: Bool = true) -> (lower: HistoryIndexEntry?, upper: HistoryIndexEntry?) {
func adjacentItems(_ id: MessageId, bindUpper: Bool = true) -> (lower: HistoryIndexEntry?, upper: HistoryIndexEntry?) {
let key = self.key(id)
var lowerItem: HistoryIndexEntry?
@ -585,7 +585,7 @@ final class MessageHistoryIndexTable: Table {
return (lower: lowerItem, upper: upperItem)
}
func get(id: MessageId) -> HistoryIndexEntry? {
func get(_ id: MessageId) -> HistoryIndexEntry? {
var operations: [MessageHistoryIndexOperation] = []
self.ensureInitialized(id.peerId, operations: &operations)
@ -596,7 +596,7 @@ final class MessageHistoryIndexTable: Table {
return nil
}
func top(peerId: PeerId, namespace: MessageId.Namespace) -> HistoryIndexEntry? {
func top(_ peerId: PeerId, namespace: MessageId.Namespace) -> HistoryIndexEntry? {
var operations: [MessageHistoryIndexOperation] = []
self.ensureInitialized(peerId, operations: &operations)
@ -609,11 +609,11 @@ final class MessageHistoryIndexTable: Table {
return entry
}
func exists(id: MessageId) -> Bool {
func exists(_ id: MessageId) -> Bool {
return self.valueBox.exists(self.tableId, key: self.key(id))
}
func holeContainingId(id: MessageId) -> MessageHistoryHole? {
func holeContainingId(_ id: MessageId) -> MessageHistoryHole? {
var result: MessageHistoryHole?
self.valueBox.range(self.tableId, start: self.key(MessageId(peerId: id.peerId, namespace: id.namespace, id: id.id)).predecessor, end: self.upperBound(id.peerId, namespace: id.namespace), values: { key, value in
if case let .Hole(hole) = readHistoryIndexEntry(id.peerId, namespace: id.namespace, key: key, value: value) {
@ -625,7 +625,7 @@ final class MessageHistoryIndexTable: Table {
return result
}
func incomingMessageCountInRange(peerId: PeerId, namespace: MessageId.Namespace, minId: MessageId.Id, maxId: MessageId.Id) -> (Int, Bool) {
func incomingMessageCountInRange(_ peerId: PeerId, namespace: MessageId.Namespace, minId: MessageId.Id, maxId: MessageId.Id) -> (Int, Bool) {
var count = 0
var holes = false
@ -657,7 +657,7 @@ final class MessageHistoryIndexTable: Table {
return (count, holes)
}
func incomingMessageCountInIds(peerId: PeerId, namespace: MessageId.Namespace, ids: [MessageId.Id]) -> (Int, Bool) {
func incomingMessageCountInIds(_ peerId: PeerId, namespace: MessageId.Namespace, ids: [MessageId.Id]) -> (Int, Bool) {
var count = 0
var holes = false
@ -686,7 +686,7 @@ final class MessageHistoryIndexTable: Table {
return (count, holes)
}
func debugList(peerId: PeerId, namespace: MessageId.Namespace) -> [HistoryIndexEntry] {
func debugList(_ peerId: PeerId, namespace: MessageId.Namespace) -> [HistoryIndexEntry] {
var list: [HistoryIndexEntry] = []
self.valueBox.range(self.tableId, start: self.lowerBound(peerId, namespace: namespace), end: self.upperBound(peerId, namespace: namespace), values: { key, value in
list.append(readHistoryIndexEntry(peerId, namespace: namespace, key: key, value: value))

View File

@ -46,7 +46,7 @@ final class MessageHistorySynchronizeReadStateTable: Table {
return key
}
func set(peerId: PeerId, operation: PeerReadStateSynchronizationOperation?, inout operations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func set(_ peerId: PeerId, operation: PeerReadStateSynchronizationOperation?, operations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
self.updatedPeerIds[peerId] = operation
operations[peerId] = operation
}

View File

@ -25,13 +25,13 @@ final class MessageHistoryMetadataTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func peerHistoryInitializedKey(id: PeerId) -> ValueBoxKey {
private func peerHistoryInitializedKey(_ id: PeerId) -> ValueBoxKey {
self.sharedPeerHistoryInitializedKey.setInt64(0, value: id.toInt64())
self.sharedPeerHistoryInitializedKey.setInt8(8, value: MetadataPrefix.PeerHistoryInitialized.rawValue)
return self.sharedPeerHistoryInitializedKey
}
private func peerNextMessageIdByNamespaceKey(id: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
private func peerNextMessageIdByNamespaceKey(_ id: PeerId, namespace: MessageId.Namespace) -> ValueBoxKey {
self.sharedPeerNextMessageIdByNamespaceKey.setInt64(0, value: id.toInt64())
self.sharedPeerNextMessageIdByNamespaceKey.setInt8(8, value: MetadataPrefix.PeerNextMessageIdByNamespace.rawValue)
self.sharedPeerNextMessageIdByNamespaceKey.setInt32(8 + 1, value: namespace)
@ -39,7 +39,7 @@ final class MessageHistoryMetadataTable: Table {
return self.sharedPeerNextMessageIdByNamespaceKey
}
private func key(prefix: MetadataPrefix) -> ValueBoxKey {
private func key(_ prefix: MetadataPrefix) -> ValueBoxKey {
let key = ValueBoxKey(length: 1)
key.setInt8(0, value: prefix.rawValue)
return key
@ -47,7 +47,7 @@ final class MessageHistoryMetadataTable: Table {
func setInitializedChatList() {
self.initializedChatList = true
self.valueBox.set(self.tableId, key: self.key(MetadataPrefix.ChatListInitialized), value: MemoryBuffer(memory: nil, capacity: 0, length: 0, freeWhenDone: false))
self.valueBox.set(self.tableId, key: self.key(MetadataPrefix.ChatListInitialized), value: MemoryBuffer())
}
func isInitializedChatList() -> Bool {
@ -63,13 +63,13 @@ final class MessageHistoryMetadataTable: Table {
return false
}
func setInitialized(peerId: PeerId) {
func setInitialized(_ peerId: PeerId) {
self.initializedHistoryPeerIds.insert(peerId)
self.sharedBuffer.reset()
self.valueBox.set(self.tableId, key: self.peerHistoryInitializedKey(peerId), value: self.sharedBuffer)
}
func isInitialized(peerId: PeerId) -> Bool {
func isInitialized(_ peerId: PeerId) -> Bool {
if self.initializedHistoryPeerIds.contains(peerId) {
return true
} else {
@ -82,7 +82,7 @@ final class MessageHistoryMetadataTable: Table {
}
}
func getNextMessageIdAndIncrement(peerId: PeerId, namespace: MessageId.Namespace) -> MessageId {
func getNextMessageIdAndIncrement(_ peerId: PeerId, namespace: MessageId.Namespace) -> MessageId {
if let messageIdByNamespace = self.peerNextMessageIdByNamespace[peerId] {
if let nextId = messageIdByNamespace[namespace] {
self.peerNextMessageIdByNamespace[peerId]![namespace] = nextId + 1
@ -166,4 +166,4 @@ final class MessageHistoryMetadataTable: Table {
}
}
}
}
}

View File

@ -21,7 +21,7 @@ final class MessageHistoryReadStateTable: Table {
private let sharedKey = ValueBoxKey(length: 8)
private func key(id: PeerId) -> ValueBoxKey {
private func key(_ id: PeerId) -> ValueBoxKey {
self.sharedKey.setInt64(0, value: id.toInt64())
return self.sharedKey
}
@ -30,7 +30,7 @@ final class MessageHistoryReadStateTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func get(id: PeerId) -> InternalPeerReadStates? {
private func get(_ id: PeerId) -> InternalPeerReadStates? {
if let states = self.cachedPeerReadStates[id] {
return states
} else {
@ -63,14 +63,14 @@ final class MessageHistoryReadStateTable: Table {
}
}
func getCombinedState(peerId: PeerId) -> CombinedPeerReadState? {
func getCombinedState(_ peerId: PeerId) -> CombinedPeerReadState? {
if let states = self.get(peerId) {
return CombinedPeerReadState(states: states.namespaces.map({$0}))
}
return nil
}
func resetStates(peerId: PeerId, namespaces: [MessageId.Namespace: PeerReadState]) -> CombinedPeerReadState? {
func resetStates(_ peerId: PeerId, namespaces: [MessageId.Namespace: PeerReadState]) -> CombinedPeerReadState? {
if traceReadStates {
print("[ReadStateTable] resetStates peerId: \(peerId), namespaces: \(namespaces)")
}
@ -99,7 +99,7 @@ final class MessageHistoryReadStateTable: Table {
}
}
func addIncomingMessages(peerId: PeerId, ids: Set<MessageId>) -> (CombinedPeerReadState?, Bool) {
func addIncomingMessages(_ peerId: PeerId, ids: Set<MessageId>) -> (CombinedPeerReadState?, Bool) {
var idsByNamespace: [MessageId.Namespace: [MessageId.Id]] = [:]
for id in ids {
if idsByNamespace[id.namespace] != nil {
@ -115,7 +115,7 @@ final class MessageHistoryReadStateTable: Table {
}
var updated = false
var invalidated = false
let invalidated = false
for (namespace, ids) in idsByNamespace {
if let currentState = states.namespaces[namespace] {
var addedUnreadCount: Int32 = 0
@ -149,11 +149,9 @@ final class MessageHistoryReadStateTable: Table {
}
return (nil, true)
}
return (nil, false)
}
func deleteMessages(peerId: PeerId, ids: [MessageId], incomingStatsInIds: (PeerId, MessageId.Namespace, [MessageId.Id]) -> (Int, Bool)) -> (CombinedPeerReadState?, Bool) {
func deleteMessages(_ peerId: PeerId, ids: [MessageId], incomingStatsInIds: (PeerId, MessageId.Namespace, [MessageId.Id]) -> (Int, Bool)) -> (CombinedPeerReadState?, Bool) {
var idsByNamespace: [MessageId.Namespace: [MessageId.Id]] = [:]
for id in ids {
if idsByNamespace[id.namespace] != nil {
@ -199,11 +197,9 @@ final class MessageHistoryReadStateTable: Table {
} else {
return (nil, true)
}
return (nil, false)
}
func applyIncomingMaxReadId(messageId: MessageId, incomingStatsInRange: (MessageId.Id, MessageId.Id) -> (count: Int, holes: Bool), topMessageId: MessageId.Id?) -> (CombinedPeerReadState?, Bool) {
func applyIncomingMaxReadId(_ messageId: MessageId, incomingStatsInRange: (MessageId.Id, MessageId.Id) -> (count: Int, holes: Bool), topMessageId: MessageId.Id?) -> (CombinedPeerReadState?, Bool) {
if let states = self.get(messageId.peerId), state = states.namespaces[messageId.namespace] {
if traceReadStates {
print("[ReadStateTable] applyMaxReadId peerId: \(messageId.peerId), maxReadId: \(messageId.id) (before: \(states.namespaces))")
@ -234,7 +230,7 @@ final class MessageHistoryReadStateTable: Table {
return (nil, false)
}
func applyOutgoingMaxReadId(messageId: MessageId) -> (CombinedPeerReadState?, Bool) {
func applyOutgoingMaxReadId(_ messageId: MessageId) -> (CombinedPeerReadState?, Bool) {
if let states = self.get(messageId.peerId), state = states.namespaces[messageId.namespace] {
if state.maxOutgoingReadId < messageId.id {
states.namespaces[messageId.namespace] = PeerReadState(maxIncomingReadId: state.maxIncomingReadId, maxOutgoingReadId: state.maxOutgoingReadId, maxKnownId: state.maxKnownId, count: state.count)
@ -248,7 +244,7 @@ final class MessageHistoryReadStateTable: Table {
return (nil, false)
}
func applyInteractiveMaxReadId(messageId: MessageId, incomingStatsInRange: (MessageId.Id, MessageId.Id) -> (count: Int, holes: Bool), topMessageId: MessageId.Id?) -> (combinedState: CombinedPeerReadState?, ApplyInteractiveMaxReadIdResult) {
func applyInteractiveMaxReadId(_ messageId: MessageId, incomingStatsInRange: (MessageId.Id, MessageId.Id) -> (count: Int, holes: Bool), topMessageId: MessageId.Id?) -> (combinedState: CombinedPeerReadState?, ApplyInteractiveMaxReadIdResult) {
let (combinedState, holes) = self.applyIncomingMaxReadId(messageId, incomingStatsInRange: incomingStatsInRange, topMessageId: topMessageId)
if let combinedState = combinedState {

View File

@ -62,7 +62,7 @@ final class MessageHistoryTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(index: MessageIndex, key: ValueBoxKey = ValueBoxKey(length: 8 + 4 + 4 + 4)) -> ValueBoxKey {
private func key(_ index: MessageIndex, key: ValueBoxKey = ValueBoxKey(length: 8 + 4 + 4 + 4)) -> ValueBoxKey {
key.setInt64(0, value: index.id.peerId.toInt64())
key.setInt32(8, value: index.timestamp)
key.setInt32(8 + 4, value: index.id.namespace)
@ -70,19 +70,19 @@ final class MessageHistoryTable: Table {
return key
}
private func lowerBound(peerId: PeerId) -> ValueBoxKey {
private func lowerBound(_ peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8)
key.setInt64(0, value: peerId.toInt64())
return key
}
private func upperBound(peerId: PeerId) -> ValueBoxKey {
private func upperBound(_ peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8)
key.setInt64(0, value: peerId.toInt64())
return key.successor
}
private func messagesGroupedByPeerId(messages: [StoreMessage]) -> [PeerId: [StoreMessage]] {
private func messagesGroupedByPeerId(_ messages: [StoreMessage]) -> [PeerId: [StoreMessage]] {
var dict: [PeerId: [StoreMessage]] = [:]
for message in messages {
@ -97,7 +97,7 @@ final class MessageHistoryTable: Table {
return dict
}
private func messageIdsByPeerId(ids: [MessageId]) -> [PeerId: [MessageId]] {
private func messageIdsByPeerId(_ ids: [MessageId]) -> [PeerId: [MessageId]] {
var dict: [PeerId: [MessageId]] = [:]
for id in ids {
@ -112,7 +112,7 @@ final class MessageHistoryTable: Table {
return dict
}
private func processIndexOperations(peerId: PeerId, operations: [MessageHistoryIndexOperation], inout processedOperationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
private func processIndexOperations(_ peerId: PeerId, operations: [MessageHistoryIndexOperation], processedOperationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
let sharedKey = self.key(MessageIndex(id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: 0, id: 0), timestamp: 0))
let sharedBuffer = WriteBuffer()
let sharedEncoder = Encoder()
@ -120,7 +120,6 @@ final class MessageHistoryTable: Table {
var outputOperations: [MessageHistoryOperation] = []
var accumulatedRemoveIndices: [MessageIndex] = []
var addedIncomingMessageIds = Set<MessageId>()
var removedMessageIds: [MessageId] = []
for operation in operations {
switch operation {
case let .InsertHole(hole):
@ -202,11 +201,11 @@ final class MessageHistoryTable: Table {
if processedOperationsByPeerId[peerId] == nil {
processedOperationsByPeerId[peerId] = outputOperations
} else {
processedOperationsByPeerId[peerId]!.appendContentsOf(outputOperations)
processedOperationsByPeerId[peerId]!.append(contentsOf: outputOperations)
}
}
private func internalStoreMessages(messages: [StoreMessage]) -> [InternalStoreMessage] {
private func internalStoreMessages(_ messages: [StoreMessage]) -> [InternalStoreMessage] {
var internalStoreMessages: [InternalStoreMessage] = []
for message in messages {
switch message.id {
@ -220,7 +219,7 @@ final class MessageHistoryTable: Table {
return internalStoreMessages
}
func addMessages(messages: [StoreMessage], location: AddMessagesLocation, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func addMessages(_ messages: [StoreMessage], location: AddMessagesLocation, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
let messagesByPeerId = self.messagesGroupedByPeerId(messages)
for (peerId, peerMessages) in messagesByPeerId {
var operations: [MessageHistoryIndexOperation] = []
@ -229,7 +228,7 @@ final class MessageHistoryTable: Table {
}
}
func addHoles(messageIds: [MessageId], inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func addHoles(_ messageIds: [MessageId], operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
for (peerId, messageIds) in self.messageIdsByPeerId(messageIds) {
var operations: [MessageHistoryIndexOperation] = []
for id in messageIds {
@ -239,7 +238,7 @@ final class MessageHistoryTable: Table {
}
}
func removeMessages(messageIds: [MessageId], inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func removeMessages(_ messageIds: [MessageId], operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
for (peerId, messageIds) in self.messageIdsByPeerId(messageIds) {
var operations: [MessageHistoryIndexOperation] = []
@ -259,7 +258,7 @@ final class MessageHistoryTable: Table {
if operationsByPeerId[peerId] == nil {
operationsByPeerId[peerId] = outputOperations
} else {
operationsByPeerId[peerId]!.appendContentsOf(outputOperations)
operationsByPeerId[peerId]!.append(contentsOf: outputOperations)
}
}
@ -269,19 +268,19 @@ final class MessageHistoryTable: Table {
}
}
func fillHole(id: MessageId, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage], inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func fillHole(_ id: MessageId, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage], operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
var operations: [MessageHistoryIndexOperation] = []
self.messageHistoryIndexTable.fillHole(id, fillType: fillType, tagMask: tagMask, messages: self.internalStoreMessages(messages), operations: &operations)
self.processIndexOperations(id.peerId, operations: operations, processedOperationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
func updateMessage(id: MessageId, message: StoreMessage, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func updateMessage(_ id: MessageId, message: StoreMessage, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
var operations: [MessageHistoryIndexOperation] = []
self.messageHistoryIndexTable.updateMessage(id, message: self.internalStoreMessages([message]).first!, operations: &operations)
self.processIndexOperations(id.peerId, operations: operations, processedOperationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
func updateMedia(id: MediaId, media: Media?, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout updatedMedia: [MediaId: Media?]) {
func updateMedia(_ id: MediaId, media: Media?, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedMedia: inout [MediaId: Media?]) {
if let previousMedia = self.messageMediaTable.get(id, embedded: { index, id in
return self.embeddedMediaForIndex(index, id: id)
}) {
@ -307,7 +306,7 @@ final class MessageHistoryTable: Table {
}
}
func resetIncomingReadStates(states: [PeerId: [MessageId.Namespace: PeerReadState]], inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func resetIncomingReadStates(_ states: [PeerId: [MessageId.Namespace: PeerReadState]], operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
for (peerId, namespaces) in states {
if let combinedState = self.readStateTable.resetStates(peerId, namespaces: namespaces) {
if operationsByPeerId[peerId] == nil {
@ -320,7 +319,7 @@ final class MessageHistoryTable: Table {
}
}
func applyIncomingReadMaxId(messageId: MessageId, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func applyIncomingReadMaxId(_ messageId: MessageId, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
var topMessageId: MessageId.Id?
if let topEntry = self.messageHistoryIndexTable.top(messageId.peerId, namespace: messageId.namespace), case let .Message(index) = topEntry {
topMessageId = index.id.id
@ -343,7 +342,7 @@ final class MessageHistoryTable: Table {
}
}
func applyOutgoingReadMaxId(messageId: MessageId, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func applyOutgoingReadMaxId(_ messageId: MessageId, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
let (combinedState, invalidated) = self.readStateTable.applyOutgoingMaxReadId(messageId)
if let combinedState = combinedState {
@ -359,7 +358,7 @@ final class MessageHistoryTable: Table {
}
}
func applyInteractiveMaxReadId(messageId: MessageId, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], inout updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?]) {
func applyInteractiveMaxReadId(_ messageId: MessageId, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?]) {
var topMessageId: MessageId.Id?
if let topEntry = self.messageHistoryIndexTable.top(messageId.peerId, namespace: messageId.namespace), case let .Message(index) = topEntry {
topMessageId = index.id.id
@ -385,7 +384,7 @@ final class MessageHistoryTable: Table {
}
}
func topMessage(peerId: PeerId) -> IntermediateMessage? {
func topMessage(_ peerId: PeerId) -> IntermediateMessage? {
var currentKey = self.upperBound(peerId)
while true {
var entry: IntermediateMessageHistoryEntry?
@ -408,7 +407,7 @@ final class MessageHistoryTable: Table {
return nil
}
func getMessage(index: MessageIndex) -> IntermediateMessage? {
func getMessage(_ index: MessageIndex) -> IntermediateMessage? {
let key = self.key(index)
if let value = self.valueBox.get(self.tableId, key: key) {
let entry = self.readIntermediateEntry(key, value: value)
@ -419,7 +418,7 @@ final class MessageHistoryTable: Table {
return nil
}
private func justInsertMessage(message: InternalStoreMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer, sharedEncoder: Encoder) -> IntermediateMessage {
private func justInsertMessage(_ message: InternalStoreMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer, sharedEncoder: Encoder) -> IntermediateMessage {
sharedBuffer.reset()
var type: Int8 = 0
@ -479,10 +478,10 @@ final class MessageHistoryTable: Table {
sharedBuffer.write(&hasAuthor, offset: 0, length: 1)
}
let data = message.text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var length: Int32 = Int32(data.length)
let data = message.text.data(using: .utf8, allowLossyConversion: true)!
var length: Int32 = Int32(data.count)
sharedBuffer.write(&length, offset: 0, length: 4)
sharedBuffer.write(data.bytes, offset: 0, length: Int(length))
sharedBuffer.write(data)
let attributesBuffer = WriteBuffer()
@ -543,7 +542,7 @@ final class MessageHistoryTable: Table {
return IntermediateMessage(stableId: stableId, id: message.id, timestamp: message.timestamp, flags: flags, tags: message.tags, forwardInfo: intermediateForwardInfo, authorId: message.authorId, text: message.text, attributesData: attributesBuffer.makeReadBufferAndReset(), embeddedMediaData: embeddedMediaBuffer.makeReadBufferAndReset(), referencedMedia: referencedMedia)
}
private func justInsertHole(hole: MessageHistoryHole, sharedBuffer: WriteBuffer = WriteBuffer()) {
private func justInsertHole(_ hole: MessageHistoryHole, sharedBuffer: WriteBuffer = WriteBuffer()) {
sharedBuffer.reset()
var type: Int8 = 1
sharedBuffer.write(&type, offset: 0, length: 1)
@ -556,7 +555,7 @@ final class MessageHistoryTable: Table {
self.valueBox.set(self.tableId, key: self.key(hole.maxIndex), value: sharedBuffer.readBufferNoCopy())
}
private func justRemove(index: MessageIndex, inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation]) {
private func justRemove(_ index: MessageIndex, unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation]) {
let key = self.key(index)
if let value = self.valueBox.get(self.tableId, key: key) {
switch self.readIntermediateEntry(key, value: value) {
@ -595,7 +594,7 @@ final class MessageHistoryTable: Table {
}
for mediaId in message.referencedMedia {
self.messageMediaTable.removeReference(mediaId)
let _ = self.messageMediaTable.removeReference(mediaId)
}
case let .Hole(hole):
let tags = self.messageHistoryIndexTable.seedConfiguration.existingMessageTags.rawValue & hole.tags
@ -618,15 +617,13 @@ final class MessageHistoryTable: Table {
}
}
func embeddedMediaForIndex(index: MessageIndex, id: MediaId) -> Media? {
func embeddedMediaForIndex(_ index: MessageIndex, id: MediaId) -> Media? {
if let message = self.getMessage(index) where message.embeddedMediaData.length > 4 {
var embeddedMediaCount: Int32 = 0
message.embeddedMediaData.read(&embeddedMediaCount, offset: 0, length: 4)
for _ in 0 ..< embeddedMediaCount {
let mediaOffset = message.embeddedMediaData.offset
var mediaLength: Int32 = 0
var copyMedia = true
message.embeddedMediaData.read(&mediaLength, offset: 0, length: 4)
if let readMedia = Decoder(buffer: MemoryBuffer(memory: message.embeddedMediaData.memory + message.embeddedMediaData.offset, capacity: Int(mediaLength), length: Int(mediaLength), freeWhenDone: false)).decodeRootObject() as? Media {
@ -641,16 +638,14 @@ final class MessageHistoryTable: Table {
return nil
}
func updateEmbeddedMedia(index: MessageIndex, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], @noescape update: ([Media]) -> [Media]) {
func updateEmbeddedMedia(_ index: MessageIndex, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], update: @noescape([Media]) -> [Media]) {
if let message = self.getMessage(index) {
var embeddedMediaCount: Int32 = 0
message.embeddedMediaData.read(&embeddedMediaCount, offset: 0, length: 4)
var previousMedia: [Media] = []
for _ in 0 ..< embeddedMediaCount {
let mediaOffset = message.embeddedMediaData.offset
var mediaLength: Int32 = 0
var copyMedia = true
message.embeddedMediaData.read(&mediaLength, offset: 0, length: 4)
if let readMedia = Decoder(buffer: MemoryBuffer(memory: message.embeddedMediaData.memory + message.embeddedMediaData.offset, capacity: Int(mediaLength), length: Int(mediaLength), freeWhenDone: false)).decodeRootObject() as? Media {
previousMedia.append(readMedia)
@ -700,7 +695,7 @@ final class MessageHistoryTable: Table {
}
}
func updateEmbeddedMedia(index: MessageIndex, mediaId: MediaId, media: Media?, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]]) {
func updateEmbeddedMedia(_ index: MessageIndex, mediaId: MediaId, media: Media?, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]]) {
self.updateEmbeddedMedia(index, operationsByPeerId: &operationsByPeerId, update: { previousMedia in
var updatedMedia: [Media] = []
for previous in previousMedia {
@ -716,7 +711,7 @@ final class MessageHistoryTable: Table {
})
}
private func justUpdate(index: MessageIndex, message: InternalStoreMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer, sharedEncoder: Encoder, inout unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation]) -> IntermediateMessage? {
private func justUpdate(_ index: MessageIndex, message: InternalStoreMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer, sharedEncoder: Encoder, unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation]) -> IntermediateMessage? {
if let previousMessage = self.getMessage(index) {
self.valueBox.remove(self.tableId, key: self.key(index))
@ -825,10 +820,10 @@ final class MessageHistoryTable: Table {
sharedBuffer.write(&hasAuthor, offset: 0, length: 1)
}
let data = message.text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var length: Int32 = Int32(data.length)
let data = message.text.data(using: .utf8, allowLossyConversion: true)!
var length: Int32 = Int32(data.count)
sharedBuffer.write(&length, offset: 0, length: 4)
sharedBuffer.write(data.bytes, offset: 0, length: Int(length))
sharedBuffer.write(data)
let attributesBuffer = WriteBuffer()
@ -892,7 +887,7 @@ final class MessageHistoryTable: Table {
}
}
func unembedMedia(index: MessageIndex, id: MediaId) -> Media? {
func unembedMedia(_ index: MessageIndex, id: MediaId) -> Media? {
if let message = self.getMessage(index) where message.embeddedMediaData.length > 4 {
var embeddedMediaCount: Int32 = 0
message.embeddedMediaData.read(&embeddedMediaCount, offset: 0, length: 4)
@ -932,7 +927,7 @@ final class MessageHistoryTable: Table {
return nil
}
func storeIntermediateMessage(message: IntermediateMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer = WriteBuffer()) {
func storeIntermediateMessage(_ message: IntermediateMessage, sharedKey: ValueBoxKey, sharedBuffer: WriteBuffer = WriteBuffer()) {
sharedBuffer.reset()
var type: Int8 = 0
@ -989,10 +984,10 @@ final class MessageHistoryTable: Table {
sharedBuffer.write(&hasAuthor, offset: 0, length: 1)
}
let data = message.text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var length: Int32 = Int32(data.length)
let data = message.text.data(using: .utf8, allowLossyConversion: true)!
var length: Int32 = Int32(data.count)
sharedBuffer.write(&length, offset: 0, length: 4)
sharedBuffer.write(data.bytes, offset: 0, length: Int(length))
sharedBuffer.write(data)
sharedBuffer.write(message.attributesData.memory, offset: 0, length: message.attributesData.length)
sharedBuffer.write(message.embeddedMediaData.memory, offset: 0, length: message.embeddedMediaData.length)
@ -1009,7 +1004,7 @@ final class MessageHistoryTable: Table {
self.valueBox.set(self.tableId, key: self.key(MessageIndex(id: message.id, timestamp: message.timestamp), key: sharedKey), value: sharedBuffer)
}
private func readIntermediateEntry(key: ValueBoxKey, value: ReadBuffer) -> IntermediateMessageHistoryEntry {
private func readIntermediateEntry(_ key: ValueBoxKey, value: ReadBuffer) -> IntermediateMessageHistoryEntry {
let index = MessageIndex(id: MessageId(peerId: PeerId(key.getInt64(0)), namespace: key.getInt32(8 + 4), id: key.getInt32(8 + 4 + 4)), timestamp: key.getInt32(8))
var type: Int8 = 0
@ -1068,7 +1063,7 @@ final class MessageHistoryTable: Table {
var textLength: Int32 = 0
value.read(&textLength, offset: 0, length: 4)
let text = String(data: NSData(bytes: value.memory + value.offset, length: Int(textLength)), encoding: NSUTF8StringEncoding) ?? ""
let text = String(data: Data(bytes: UnsafeMutablePointer<UInt8>(value.memory).advanced(by: value.offset), count: Int(textLength)), encoding: .utf8) ?? ""
//let text = NSString(bytes: value.memory + value.offset, length: Int(textLength), encoding: NSUTF8StringEncoding) ?? ""
value.skip(Int(textLength))
@ -1081,7 +1076,7 @@ final class MessageHistoryTable: Table {
value.skip(Int(attributeLength))
}
let attributesLength = value.offset - attributesOffset
let attributesBytes = malloc(attributesLength)
let attributesBytes = malloc(attributesLength)!
memcpy(attributesBytes, value.memory + attributesOffset, attributesLength)
let attributesData = ReadBuffer(memory: attributesBytes, length: attributesLength, freeWhenDone: true)
@ -1094,7 +1089,7 @@ final class MessageHistoryTable: Table {
value.skip(Int(mediaLength))
}
let embeddedMediaLength = value.offset - embeddedMediaOffset
let embeddedMediaBytes = malloc(embeddedMediaLength)
let embeddedMediaBytes = malloc(embeddedMediaLength)!
memcpy(embeddedMediaBytes, value.memory + embeddedMediaOffset, embeddedMediaLength)
let embeddedMediaData = ReadBuffer(memory: embeddedMediaBytes, length: embeddedMediaLength, freeWhenDone: true)
@ -1123,7 +1118,7 @@ final class MessageHistoryTable: Table {
}
}
func renderMessage(message: IntermediateMessage, peerTable: PeerTable, addAssociatedMessages: Bool = true) -> Message {
func renderMessage(_ message: IntermediateMessage, peerTable: PeerTable, addAssociatedMessages: Bool = true) -> Message {
var parsedAttributes: [MessageAttribute] = []
var parsedMedia: [Media] = []
@ -1212,7 +1207,7 @@ final class MessageHistoryTable: Table {
return Message(stableId: message.stableId, id: message.id, timestamp: message.timestamp, flags: message.flags, tags: message.tags, forwardInfo: forwardInfo, author: author, text: message.text, attributes: parsedAttributes, media: parsedMedia, peers: peers, associatedMessages: associatedMessages)
}
func entriesAround(index: MessageIndex, count: Int) -> (entries: [IntermediateMessageHistoryEntry], lower: IntermediateMessageHistoryEntry?, upper: IntermediateMessageHistoryEntry?) {
func entriesAround(_ index: MessageIndex, count: Int) -> (entries: [IntermediateMessageHistoryEntry], lower: IntermediateMessageHistoryEntry?, upper: IntermediateMessageHistoryEntry?) {
var lowerEntries: [IntermediateMessageHistoryEntry] = []
var upperEntries: [IntermediateMessageHistoryEntry] = []
var lower: IntermediateMessageHistoryEntry?
@ -1247,16 +1242,16 @@ final class MessageHistoryTable: Table {
lower = additionalLowerEntries.last
additionalLowerEntries.removeLast()
}
lowerEntries.appendContentsOf(additionalLowerEntries)
lowerEntries.append(contentsOf: additionalLowerEntries)
}
var entries: [IntermediateMessageHistoryEntry] = []
entries.appendContentsOf(lowerEntries.reverse())
entries.appendContentsOf(upperEntries)
entries.append(contentsOf: lowerEntries.reversed())
entries.append(contentsOf: upperEntries)
return (entries: entries, lower: lower, upper: upper)
}
func entriesAround(tagMask: MessageTags, index: MessageIndex, count: Int) -> (entries: [IntermediateMessageHistoryEntry], lower: IntermediateMessageHistoryEntry?, upper: IntermediateMessageHistoryEntry?) {
func entriesAround(_ tagMask: MessageTags, index: MessageIndex, count: Int) -> (entries: [IntermediateMessageHistoryEntry], lower: IntermediateMessageHistoryEntry?, upper: IntermediateMessageHistoryEntry?) {
let (indices, lower, upper) = self.tagsTable.indicesAround(tagMask, index: index, count: count)
var entries: [IntermediateMessageHistoryEntry] = []
@ -1293,7 +1288,7 @@ final class MessageHistoryTable: Table {
return (entries, lowerEntry, upperEntry)
}
func earlierEntries(peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
func earlierEntries(_ peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
var entries: [IntermediateMessageHistoryEntry] = []
let key: ValueBoxKey
if let index = index {
@ -1308,7 +1303,7 @@ final class MessageHistoryTable: Table {
return entries
}
func earlierEntries(tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
func earlierEntries(_ tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
let indices = self.tagsTable.earlierIndices(tagMask, peerId: peerId, index: index, count: count)
var entries: [IntermediateMessageHistoryEntry] = []
@ -1324,7 +1319,7 @@ final class MessageHistoryTable: Table {
return entries
}
func laterEntries(peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
func laterEntries(_ peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
var entries: [IntermediateMessageHistoryEntry] = []
let key: ValueBoxKey
if let index = index {
@ -1339,7 +1334,7 @@ final class MessageHistoryTable: Table {
return entries
}
func laterEntries(tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
func laterEntries(_ tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [IntermediateMessageHistoryEntry] {
let indices = self.tagsTable.laterIndices(tagMask, peerId: peerId, index: index, count: count)
var entries: [IntermediateMessageHistoryEntry] = []
@ -1355,14 +1350,14 @@ final class MessageHistoryTable: Table {
return entries
}
func maxReadIndex(peerId: PeerId) -> MessageHistoryAnchorIndex? {
func maxReadIndex(_ peerId: PeerId) -> MessageHistoryAnchorIndex? {
if let combinedState = self.readStateTable.getCombinedState(peerId), state = combinedState.states.first where state.1.count != 0 {
return self.anchorIndex(MessageId(peerId: peerId, namespace: state.0, id: state.1.maxIncomingReadId))
}
return nil
}
func anchorIndex(messageId: MessageId) -> MessageHistoryAnchorIndex? {
func anchorIndex(_ messageId: MessageId) -> MessageHistoryAnchorIndex? {
let (lower, upper) = self.messageHistoryIndexTable.adjacentItems(messageId, bindUpper: false)
if let lower = lower, case let .Hole(hole) = lower where messageId.id >= hole.min && messageId.id <= hole.maxIndex.id.id {
return MessageHistoryAnchorIndex(index: MessageIndex(id: messageId, timestamp: lower.index.timestamp), exact: false)
@ -1379,7 +1374,7 @@ final class MessageHistoryTable: Table {
return nil
}
func debugList(peerId: PeerId, peerTable: PeerTable) -> [RenderedMessageHistoryEntry] {
func debugList(_ peerId: PeerId, peerTable: PeerTable) -> [RenderedMessageHistoryEntry] {
return self.laterEntries(peerId, index: nil, count: 1000).map({ entry -> RenderedMessageHistoryEntry in
switch entry {
case let .Hole(hole):
@ -1390,7 +1385,7 @@ final class MessageHistoryTable: Table {
})
}
func debugList(tagMask: MessageTags, peerId: PeerId, peerTable: PeerTable) -> [RenderedMessageHistoryEntry] {
func debugList(_ tagMask: MessageTags, peerId: PeerId, peerTable: PeerTable) -> [RenderedMessageHistoryEntry] {
return self.laterEntries(tagMask, peerId: peerId, index: nil, count: 1000).map({ entry -> RenderedMessageHistoryEntry in
switch entry {
case let .Hole(hole):

View File

@ -7,7 +7,7 @@ class MessageHistoryTagsTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(tagMask: MessageTags, index: MessageIndex, key: ValueBoxKey = ValueBoxKey(length: 8 + 4 + 4 + 4 + 4)) -> ValueBoxKey {
private func key(_ tagMask: MessageTags, index: MessageIndex, key: ValueBoxKey = ValueBoxKey(length: 8 + 4 + 4 + 4 + 4)) -> ValueBoxKey {
key.setInt64(0, value: index.id.peerId.toInt64())
key.setUInt32(8, value: tagMask.rawValue)
key.setInt32(8 + 4, value: index.timestamp)
@ -16,29 +16,29 @@ class MessageHistoryTagsTable: Table {
return key
}
private func lowerBound(tagMask: MessageTags, peerId: PeerId) -> ValueBoxKey {
private func lowerBound(_ tagMask: MessageTags, peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 4)
key.setInt64(0, value: peerId.toInt64())
key.setUInt32(8, value: tagMask.rawValue)
return key
}
private func upperBound(tagMask: MessageTags, peerId: PeerId) -> ValueBoxKey {
private func upperBound(_ tagMask: MessageTags, peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 4)
key.setInt64(0, value: peerId.toInt64())
key.setUInt32(8, value: tagMask.rawValue)
return key.successor
}
func add(tagMask: MessageTags, index: MessageIndex) {
func add(_ tagMask: MessageTags, index: MessageIndex) {
self.valueBox.set(self.tableId, key: self.key(tagMask, index: index, key: self.sharedKey), value: MemoryBuffer())
}
func remove(tagMask: MessageTags, index: MessageIndex) {
func remove(_ tagMask: MessageTags, index: MessageIndex) {
self.valueBox.remove(self.tableId, key: self.key(tagMask, index: index, key: self.sharedKey))
}
func indicesAround(tagMask: MessageTags, index: MessageIndex, count: Int) -> (indices: [MessageIndex], lower: MessageIndex?, upper: MessageIndex?) {
func indicesAround(_ tagMask: MessageTags, index: MessageIndex, count: Int) -> (indices: [MessageIndex], lower: MessageIndex?, upper: MessageIndex?) {
var lowerEntries: [MessageIndex] = []
var upperEntries: [MessageIndex] = []
var lower: MessageIndex?
@ -76,16 +76,16 @@ class MessageHistoryTagsTable: Table {
lower = additionalLowerEntries.last
additionalLowerEntries.removeLast()
}
lowerEntries.appendContentsOf(additionalLowerEntries)
lowerEntries.append(contentsOf: additionalLowerEntries)
}
var entries: [MessageIndex] = []
entries.appendContentsOf(lowerEntries.reverse())
entries.appendContentsOf(upperEntries)
entries.append(contentsOf: lowerEntries.reversed())
entries.append(contentsOf: upperEntries)
return (indices: entries, lower: lower, upper: upper)
}
func earlierIndices(tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [MessageIndex] {
func earlierIndices(_ tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [MessageIndex] {
var indices: [MessageIndex] = []
let key: ValueBoxKey
if let index = index {
@ -101,7 +101,7 @@ class MessageHistoryTagsTable: Table {
return indices
}
func laterIndices(tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [MessageIndex] {
func laterIndices(_ tagMask: MessageTags, peerId: PeerId, index: MessageIndex?, count: Int) -> [MessageIndex] {
var indices: [MessageIndex] = []
let key: ValueBoxKey
if let index = index {

View File

@ -8,7 +8,7 @@ enum IntermediateMessageHistoryUnsentOperation {
final class MessageHistoryUnsentTable: Table {
private let sharedKey = ValueBoxKey(length: 4 + 4 + 4 + 8)
private func key(index: MessageIndex) -> ValueBoxKey {
private func key(_ index: MessageIndex) -> ValueBoxKey {
self.sharedKey.setInt32(0, value: index.timestamp)
self.sharedKey.setInt32(4, value: index.id.namespace)
self.sharedKey.setInt32(4 + 4, value: index.id.id)
@ -33,12 +33,12 @@ final class MessageHistoryUnsentTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
func add(index: MessageIndex, inout operations: [IntermediateMessageHistoryUnsentOperation]) {
func add(_ index: MessageIndex, operations: inout [IntermediateMessageHistoryUnsentOperation]) {
self.valueBox.set(self.tableId, key: self.key(index), value: MemoryBuffer())
operations.append(.Insert(index))
}
func remove(index: MessageIndex, inout operations: [IntermediateMessageHistoryUnsentOperation]) {
func remove(_ index: MessageIndex, operations: inout [IntermediateMessageHistoryUnsentOperation]) {
self.valueBox.remove(self.tableId, key: self.key(index))
operations.append(.Remove(index))
}
@ -55,4 +55,4 @@ final class MessageHistoryUnsentTable: Table {
override func beforeCommit() {
}
}
}

View File

@ -112,7 +112,7 @@ final class MutableMessageHistoryView {
self.id = self.id.nextVersion
}
func updateVisibleRange(earliestVisibleIndex earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex, context: MutableMessageHistoryViewReplayContext) -> Bool {
func updateVisibleRange(earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex, context: MutableMessageHistoryViewReplayContext) -> Bool {
if (true) {
//return false
}
@ -127,7 +127,7 @@ final class MutableMessageHistoryView {
}
}
for i in (0 ..< self.entries.count).reverse() {
for i in (0 ..< self.entries.count).reversed() {
if self.entries[i].index <= latestVisibleIndex {
maxIndex = i
break
@ -180,7 +180,7 @@ final class MutableMessageHistoryView {
return false
}
func updateAnchorIndex(getIndex: (MessageId) -> MessageHistoryAnchorIndex?) -> Bool {
func updateAnchorIndex(_ getIndex: (MessageId) -> MessageHistoryAnchorIndex?) -> Bool {
if !self.anchorIndex.exact {
if let index = getIndex(self.anchorIndex.index.id) {
self.anchorIndex = index
@ -190,7 +190,7 @@ final class MutableMessageHistoryView {
return false
}
func replay(operations: [MessageHistoryOperation], holeFillDirections: [MessageIndex: HoleFillDirection], updatedMedia: [MediaId: Media?], context: MutableMessageHistoryViewReplayContext) -> Bool {
func replay(_ operations: [MessageHistoryOperation], holeFillDirections: [MessageIndex: HoleFillDirection], updatedMedia: [MediaId: Media?], context: MutableMessageHistoryViewReplayContext) -> Bool {
let tagMask = self.tagMask
let unwrappedTagMask: UInt32 = tagMask?.rawValue ?? 0
@ -233,7 +233,7 @@ final class MutableMessageHistoryView {
case let .MessageEntry(message):
var rebuild = false
for media in message.media {
if let mediaId = media.id, updated = updatedMedia[mediaId] {
if let mediaId = media.id, _ = updatedMedia[mediaId] {
rebuild = true
break
}
@ -250,7 +250,7 @@ final class MutableMessageHistoryView {
messageMedia.append(media)
}
}
var updatedMessage = Message(stableId: message.stableId, id: message.id, timestamp: message.timestamp, flags: message.flags, tags: message.tags, forwardInfo: message.forwardInfo, author: message.author, text: message.text, attributes: message.attributes, media: messageMedia, peers: message.peers, associatedMessages: message.associatedMessages)
let updatedMessage = Message(stableId: message.stableId, id: message.id, timestamp: message.timestamp, flags: message.flags, tags: message.tags, forwardInfo: message.forwardInfo, author: message.author, text: message.text, attributes: message.attributes, media: messageMedia, peers: message.peers, associatedMessages: message.associatedMessages)
self.entries[i] = .MessageEntry(updatedMessage)
hasChanges = true
}
@ -284,7 +284,7 @@ final class MutableMessageHistoryView {
return hasChanges
}
private func add(entry: MutableMessageHistoryEntry, holeFillDirections: [MessageIndex: HoleFillDirection]) -> Bool {
private func add(_ entry: MutableMessageHistoryEntry, holeFillDirections: [MessageIndex: HoleFillDirection]) -> Bool {
if self.entries.count == 0 {
self.entries.append(entry)
return true
@ -292,16 +292,11 @@ final class MutableMessageHistoryView {
let latestIndex = self.entries[self.entries.count - 1].index
let earliestIndex = self.entries[0].index
var next: MessageIndex?
if let later = self.later {
next = later.index
}
let index = entry.index
if index < earliestIndex {
if self.earlier == nil || self.earlier!.index < index {
self.entries.insert(entry, atIndex: 0)
self.entries.insert(entry, at: 0)
return true
} else {
return false
@ -326,7 +321,7 @@ final class MutableMessageHistoryView {
}
i -= 1
}
self.entries.insert(entry, atIndex: i)
self.entries.insert(entry, at: i)
return true
} else {
return false
@ -334,7 +329,7 @@ final class MutableMessageHistoryView {
}
}
private func remove(indices: Set<MessageIndex>, context: MutableMessageHistoryViewReplayContext) -> Bool {
private func remove(_ indices: Set<MessageIndex>, context: MutableMessageHistoryViewReplayContext) -> Bool {
var hasChanges = false
if let earlier = self.earlier where indices.contains(earlier.index) {
context.invalidEarlier = true
@ -350,7 +345,7 @@ final class MutableMessageHistoryView {
var i = self.entries.count - 1
while i >= 0 {
if indices.contains(self.entries[i].index) {
self.entries.removeAtIndex(i)
self.entries.remove(at: i)
context.removedEntries = true
hasChanges = true
}
@ -361,7 +356,7 @@ final class MutableMessageHistoryView {
return hasChanges
}
func updatePeers(peers: [PeerId: Peer]) -> Bool {
func updatePeers(_ peers: [PeerId: Peer]) -> Bool {
return false
}
@ -373,7 +368,7 @@ final class MutableMessageHistoryView {
let fetchedEntries = fetchEarlier(anchorIndex, self.fillCount + 2)
if fetchedEntries.count >= self.fillCount + 2 {
self.earlier = fetchedEntries.last
for i in (1 ..< fetchedEntries.count - 1).reverse() {
for i in (1 ..< fetchedEntries.count - 1).reversed() {
self.entries.append(fetchedEntries[i])
}
self.later = fetchedEntries.first
@ -381,7 +376,7 @@ final class MutableMessageHistoryView {
} else {
let fetchedEntries = fetchEarlier(self.entries[0].index, self.fillCount - self.entries.count)
for entry in fetchedEntries {
self.entries.insert(entry, atIndex: 0)
self.entries.insert(entry, at: 0)
}
if context.invalidEarlier {
@ -431,7 +426,7 @@ final class MutableMessageHistoryView {
}
}
func render(renderIntermediateMessage: IntermediateMessage -> Message) {
func render(_ renderIntermediateMessage: (IntermediateMessage) -> Message) {
if let earlier = self.earlier, case let .IntermediateMessageEntry(intermediateMessage) = earlier {
self.earlier = .MessageEntry(renderIntermediateMessage(intermediateMessage))
}
@ -531,7 +526,7 @@ public final class MessageHistoryView {
for (namespace, state) in combinedReadState.states {
var maxNamespaceIndex: MessageIndex?
var index = entries.count - 1
for entry in entries.reverse() {
for entry in entries.reversed() {
if entry.index.id.namespace == namespace && entry.index.id.id <= state.maxIncomingReadId {
maxNamespaceIndex = entry.index
break

View File

@ -29,13 +29,13 @@ final class MessageMediaTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
func key(id: MediaId, key: ValueBoxKey = ValueBoxKey(length: 4 + 8)) -> ValueBoxKey {
func key(_ id: MediaId, key: ValueBoxKey = ValueBoxKey(length: 4 + 8)) -> ValueBoxKey {
key.setInt32(0, value: id.namespace)
key.setInt64(4, value: id.id)
return key
}
func get(id: MediaId, @noescape embedded: (MessageIndex, MediaId) -> Media?) -> Media? {
func get(_ id: MediaId, embedded: @noescape(MessageIndex, MediaId) -> Media?) -> Media? {
if let value = self.valueBox.get(self.tableId, key: self.key(id)) {
var type: Int8 = 0
value.read(&type, offset: 0, length: 1)
@ -63,7 +63,7 @@ final class MessageMediaTable: Table {
return nil
}
func set(media: Media, index: MessageIndex, messageHistoryTable: MessageHistoryTable, sharedWriteBuffer: WriteBuffer = WriteBuffer(), sharedEncoder: Encoder = Encoder()) -> InsertMediaResult {
func set(_ media: Media, index: MessageIndex, messageHistoryTable: MessageHistoryTable, sharedWriteBuffer: WriteBuffer = WriteBuffer(), sharedEncoder: Encoder = Encoder()) -> InsertMediaResult {
if let id = media.id {
if let value = self.valueBox.get(self.tableId, key: self.key(id)) {
var type: Int8 = 0
@ -143,7 +143,7 @@ final class MessageMediaTable: Table {
}
}
func removeReference(id: MediaId, sharedWriteBuffer: WriteBuffer = WriteBuffer()) -> RemoveMediaResult {
func removeReference(_ id: MediaId, sharedWriteBuffer: WriteBuffer = WriteBuffer()) -> RemoveMediaResult {
if let value = self.valueBox.get(self.tableId, key: self.key(id)) {
var type: Int8 = 0
value.read(&type, offset: 0, length: 1)
@ -193,14 +193,14 @@ final class MessageMediaTable: Table {
return .Reference
}
func removeEmbeddedMedia(media: Media) {
func removeEmbeddedMedia(_ media: Media) {
if let id = media.id {
self.valueBox.remove(self.tableId, key: self.key(id))
}
self.mediaCleanupTable.add(media)
}
func update(id: MediaId, media: Media, messageHistoryTable: MessageHistoryTable, inout operationsByPeerId: [PeerId: [MessageHistoryOperation]], sharedWriteBuffer: WriteBuffer = WriteBuffer(), sharedEncoder: Encoder = Encoder()) {
func update(_ id: MediaId, media: Media, messageHistoryTable: MessageHistoryTable, operationsByPeerId: inout [PeerId: [MessageHistoryOperation]], sharedWriteBuffer: WriteBuffer = WriteBuffer(), sharedEncoder: Encoder = Encoder()) {
if let updatedId = media.id {
if let value = self.valueBox.get(self.tableId, key: self.key(id)) {
var type: Int8 = 0
@ -208,7 +208,6 @@ final class MessageMediaTable: Table {
if type == MediaEntryType.Direct.rawValue {
var dataLength: Int32 = 0
value.read(&dataLength, offset: 0, length: 4)
let mediaOffset = value.offset
value.skip(Int(dataLength))
var messageReferenceCount: Int32 = 0
@ -288,4 +287,4 @@ final class MessageMediaTable: Table {
return entries
}
}
}

View File

@ -10,7 +10,7 @@ final class MetadataTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(key: MetadataKey) -> ValueBoxKey {
private func key(_ key: MetadataKey) -> ValueBoxKey {
let valueBoxKey = ValueBoxKey(length: 4)
valueBoxKey.setInt32(0, value: key.rawValue)
return valueBoxKey
@ -25,7 +25,7 @@ final class MetadataTable: Table {
return nil
}
func setUserVersion(version: Int32) {
func setUserVersion(_ version: Int32) {
let buffer = WriteBuffer()
var varVersion: Int32 = version
buffer.write(&varVersion, offset: 0, length: 4)
@ -41,9 +41,9 @@ final class MetadataTable: Table {
return nil
}
func setState(state: Coding) {
func setState(_ state: Coding) {
let encoder = Encoder()
encoder.encodeRootObject(state)
self.valueBox.set(self.tableId, key: self.key(.State), value: encoder.readBufferNoCopy())
}
}
}

View File

@ -21,7 +21,7 @@ public struct PeerId: Hashable, CustomStringConvertible, Comparable {
return (Int64(self.namespace) << 32) | Int64(self.id)
}
public static func encodeArrayToBuffer(array: [PeerId], buffer: WriteBuffer) {
public static func encodeArrayToBuffer(_ array: [PeerId], buffer: WriteBuffer) {
var length: Int32 = Int32(array.count)
buffer.write(&length, offset: 0, length: 4)
for id in array {
@ -30,7 +30,7 @@ public struct PeerId: Hashable, CustomStringConvertible, Comparable {
}
}
public static func decodeArrayFromBuffer(buffer: ReadBuffer) -> [PeerId] {
public static func decodeArrayFromBuffer(_ buffer: ReadBuffer) -> [PeerId] {
var length: Int32 = 0
memcpy(&length, buffer.memory, 4)
buffer.offset += 4
@ -68,7 +68,7 @@ public struct PeerId: Hashable, CustomStringConvertible, Comparable {
self.id = id
}
public func encodeToBuffer(buffer: WriteBuffer) {
public func encodeToBuffer(_ buffer: WriteBuffer) {
var namespace = self.namespace
var id = self.id
buffer.write(&namespace, offset: 0, length: 4);
@ -95,5 +95,5 @@ public func <(lhs: PeerId, rhs: PeerId) -> Bool {
public protocol Peer: Coding {
var id: PeerId { get }
func isEqual(other: Peer) -> Bool
func isEqual(_ other: Peer) -> Bool
}

View File

@ -6,12 +6,12 @@ final class PeerChatStateTable: Table {
private let sharedKey = ValueBoxKey(length: 8)
private func key(id: PeerId) -> ValueBoxKey {
private func key(_ id: PeerId) -> ValueBoxKey {
self.sharedKey.setInt64(0, value: id.toInt64())
return self.sharedKey
}
func get(id: PeerId) -> Coding? {
func get(_ id: PeerId) -> Coding? {
if let state = self.cachedPeerChatStates[id] {
return state
} else {
@ -25,7 +25,7 @@ final class PeerChatStateTable: Table {
}
}
func set(id: PeerId, state: Coding?) {
func set(_ id: PeerId, state: Coding?) {
self.cachedPeerChatStates[id] = state
self.updatedPeerIds.insert(id)
}

View File

@ -11,17 +11,17 @@ final class PeerTable: Table {
super.init(valueBox: valueBox, tableId: tableId)
}
private func key(id: PeerId) -> ValueBoxKey {
private func key(_ id: PeerId) -> ValueBoxKey {
self.sharedKey.setInt64(0, value: id.toInt64())
return self.sharedKey
}
func set(peer: Peer) {
func set(_ peer: Peer) {
self.cachedPeers[peer.id] = peer
self.updatedPeerIds.insert(peer.id)
}
func get(id: PeerId) -> Peer? {
func get(_ id: PeerId) -> Peer? {
if let peer = self.cachedPeers[id] {
return peer
}
@ -46,4 +46,4 @@ final class PeerTable: Table {
self.updatedPeerIds.removeAll()
}
}
}

View File

@ -8,7 +8,7 @@ public enum PreloadedMessageHistoryView {
}
public protocol PeerChatState: Coding {
func equals(other: PeerChatState) -> Bool
func equals(_ other: PeerChatState) -> Bool
}
public final class Modifier {
@ -18,50 +18,50 @@ public final class Modifier {
self.postbox = postbox
}
public func addMessages(messages: [StoreMessage], location: AddMessagesLocation) {
public func addMessages(_ messages: [StoreMessage], location: AddMessagesLocation) {
self.postbox?.addMessages(messages, location: location)
}
public func addHole(messageId: MessageId) {
public func addHole(_ messageId: MessageId) {
self.postbox?.addHole(messageId)
}
public func fillHole(hole: MessageHistoryHole, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage]) {
public func fillHole(_ hole: MessageHistoryHole, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage]) {
self.postbox?.fillHole(hole, fillType: fillType, tagMask: tagMask, messages: messages)
}
public func replaceChatListHole(index: MessageIndex, hole: ChatListHole?) {
public func replaceChatListHole(_ index: MessageIndex, hole: ChatListHole?) {
self.postbox?.replaceChatListHole(index, hole: hole)
}
public func deleteMessages(messageIds: [MessageId]) {
public func deleteMessages(_ messageIds: [MessageId]) {
self.postbox?.deleteMessages(messageIds)
}
public func deleteMessagesWithGlobalIds(ids: [Int32]) {
public func deleteMessagesWithGlobalIds(_ ids: [Int32]) {
if let postbox = self.postbox {
let messageIds = postbox.messageIdsForGlobalIds(ids)
postbox.deleteMessages(messageIds)
}
}
public func resetIncomingReadStates(states: [PeerId: [MessageId.Namespace: PeerReadState]]) {
public func resetIncomingReadStates(_ states: [PeerId: [MessageId.Namespace: PeerReadState]]) {
self.postbox?.resetIncomingReadStates(states)
}
public func confirmSynchronizedIncomingReadState(peerId: PeerId) {
public func confirmSynchronizedIncomingReadState(_ peerId: PeerId) {
self.postbox?.confirmSynchronizedIncomingReadState(peerId)
}
public func applyIncomingReadMaxId(messageId: MessageId) {
public func applyIncomingReadMaxId(_ messageId: MessageId) {
self.postbox?.applyIncomingReadMaxId(messageId)
}
public func applyOutgoingReadMaxId(messageId: MessageId) {
public func applyOutgoingReadMaxId(_ messageId: MessageId) {
self.postbox?.applyOutgoingReadMaxId(messageId)
}
public func applyInteractiveReadMaxId(messageId: MessageId) {
public func applyInteractiveReadMaxId(_ messageId: MessageId) {
self.postbox?.applyInteractiveReadMaxId(messageId)
}
@ -69,39 +69,39 @@ public final class Modifier {
return self.postbox?.getState()
}
public func setState(state: Coding) {
public func setState(_ state: Coding) {
self.postbox?.setState(state)
}
public func getPeerChatState(id: PeerId) -> PeerChatState? {
public func getPeerChatState(_ id: PeerId) -> PeerChatState? {
return self.postbox?.peerChatStateTable.get(id) as? PeerChatState
}
public func setPeerChatState(id: PeerId, state: PeerChatState) {
public func setPeerChatState(_ id: PeerId, state: PeerChatState) {
self.postbox?.peerChatStateTable.set(id, state: state)
}
public func getPeer(id: PeerId) -> Peer? {
public func getPeer(_ id: PeerId) -> Peer? {
return self.postbox?.peerTable.get(id)
}
public func getPeerReadStates(id: PeerId) -> [(MessageId.Namespace, PeerReadState)]? {
public func getPeerReadStates(_ id: PeerId) -> [(MessageId.Namespace, PeerReadState)]? {
return self.postbox?.readStateTable.getCombinedState(id)?.states
}
public func updatePeers(peers: [Peer], update: (Peer, Peer) -> Peer?) {
public func updatePeers(_ peers: [Peer], update: (Peer, Peer) -> Peer?) {
self.postbox?.updatePeers(peers, update: update)
}
public func updateMessage(index: MessageIndex, update: Message -> StoreMessage) {
public func updateMessage(_ index: MessageIndex, update: (Message) -> StoreMessage) {
self.postbox?.updateMessage(index, update: update)
}
public func updateMedia(id: MediaId, update: Media?) {
public func updateMedia(_ id: MediaId, update: Media?) {
self.postbox?.updateMedia(id, update: update)
}
public func getMessage(id: MessageId) -> Message? {
public func getMessage(_ id: MessageId) -> Message? {
if let postbox = self.postbox {
if let entry = postbox.messageHistoryIndexTable.get(id) {
if case let .Message(index) = entry {
@ -114,7 +114,7 @@ public final class Modifier {
return nil
}
public func filterStoredMessageIds(messageIds: Set<MessageId>) -> Set<MessageId> {
public func filterStoredMessageIds(_ messageIds: Set<MessageId>) -> Set<MessageId> {
if let postbox = self.postbox {
return postbox.filterStoredMessageIds(messageIds)
}
@ -133,7 +133,7 @@ public final class Postbox {
private var viewTracker: ViewTracker!
private var nextViewId = 0
private var peerPipes: [PeerId: Pipe<Peer>] = [:]
private var peerPipes: [PeerId: ValuePipe<Peer>] = [:]
private var currentOperationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
private var currentUnsentOperations: [IntermediateMessageHistoryUnsentOperation] = []
@ -145,21 +145,21 @@ public final class Postbox {
private var currentUpdatedPeers: [PeerId: Peer] = [:]
private var currentReplaceChatListHoles: [(MessageIndex, ChatListHole?)] = []
private var statePipe: Pipe<Coding> = Pipe()
private var statePipe: ValuePipe<Coding> = ValuePipe()
private let fetchChatListHoleImpl = Promise<ChatListHole -> Signal<Void, NoError>>()
public func setFetchChatListHole(fetch: ChatListHole -> Signal<Void, NoError>) {
self.fetchChatListHoleImpl.set(single(fetch, NoError.self))
private let fetchChatListHoleImpl = Promise<(ChatListHole) -> Signal<Void, NoError>>()
public func setFetchChatListHole(fetch: (ChatListHole) -> Signal<Void, NoError>) {
self.fetchChatListHoleImpl.set(.single(fetch))
}
private let fetchMessageHistoryHoleImpl = Promise<(MessageHistoryHole, HoleFillDirection, MessageTags?) -> Signal<Void, NoError>>()
public func setFetchMessageHistoryHole(fetch: (MessageHistoryHole, HoleFillDirection, MessageTags?) -> Signal<Void, NoError>) {
self.fetchMessageHistoryHoleImpl.set(single(fetch, NoError.self))
self.fetchMessageHistoryHoleImpl.set(.single(fetch))
}
private let sendUnsentMessageImpl = Promise<Message -> Signal<Void, NoError>>()
public func setSendUnsentMessage(sendUnsentMessage: Message -> Signal<Void, NoError>) {
self.sendUnsentMessageImpl.set(single(sendUnsentMessage, NoError.self))
private let sendUnsentMessageImpl = Promise<(Message) -> Signal<Void, NoError>>()
public func setSendUnsentMessage(sendUnsentMessage: (Message) -> Signal<Void, NoError>) {
self.sendUnsentMessageImpl.set(.single(sendUnsentMessage))
}
private let synchronizePeerReadStateImpl = Promise<(PeerId, PeerReadStateSynchronizationOperation) -> Signal<Void, NoError>>()
@ -193,7 +193,7 @@ public final class Postbox {
self.globalMessageIdsNamespace = globalMessageIdsNamespace
self.seedConfiguration = seedConfiguration
let _ = try? NSFileManager.defaultManager().removeItemAtPath(self.basePath + "/media")
let _ = try? FileManager.default().removeItem(atPath: self.basePath + "/media")
self.mediaBox = MediaBox(basePath: self.basePath + "/media")
self.openDatabase()
@ -202,9 +202,9 @@ public final class Postbox {
private func debugSaveState(name: String) {
self.queue.justDispatch({
let path = self.basePath + name
let _ = try? NSFileManager.defaultManager().removeItemAtPath(path)
let _ = try? FileManager.default().removeItem(atPath: path)
do {
try NSFileManager.defaultManager().copyItemAtPath(self.basePath, toPath: path)
try FileManager.default().copyItem(atPath: self.basePath, toPath: path)
} catch (let e) {
print("(Postbox debugSaveState: error \(e))")
}
@ -214,9 +214,9 @@ public final class Postbox {
private func debugRestoreState(name: String) {
self.queue.justDispatch({
let path = self.basePath + name
let _ = try? NSFileManager.defaultManager().removeItemAtPath(self.basePath)
let _ = try? FileManager.default().removeItem(atPath: self.basePath)
do {
try NSFileManager.defaultManager().copyItemAtPath(path, toPath: self.basePath)
try FileManager.default().copyItem(atPath: path, toPath: self.basePath)
} catch (let e) {
print("(Postbox debugRestoreState: error \(e))")
}
@ -228,7 +228,7 @@ public final class Postbox {
let startTime = CFAbsoluteTimeGetCurrent()
do {
try NSFileManager.defaultManager().createDirectoryAtPath(self.basePath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: self.basePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
@ -305,7 +305,7 @@ public final class Postbox {
private var cachedState: Coding?
private func setState(state: Coding) {
private func setState(_ state: Coding) {
self.queue.justDispatch({
self.cachedState = state
@ -342,34 +342,34 @@ public final class Postbox {
}
}
public func keychainEntryForKey(key: String) -> NSData? {
public func keychainEntryForKey(_ key: String) -> Data? {
return self.keychainTable.get(key)
}
public func setKeychainEntryForKey(key: String, value: NSData) {
public func setKeychainEntryForKey(_ key: String, value: Data) {
self.keychainTable.set(key, value: value)
}
public func removeKeychainEntryForKey(key: String) {
public func removeKeychainEntryForKey(_ key: String) {
self.keychainTable.remove(key)
}
private func addMessages(messages: [StoreMessage], location: AddMessagesLocation) {
private func addMessages(_ messages: [StoreMessage], location: AddMessagesLocation) {
self.messageHistoryTable.addMessages(messages, location: location, operationsByPeerId: &self.currentOperationsByPeerId, unsentMessageOperations: &currentUnsentOperations, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func addHole(id: MessageId) {
private func addHole(_ id: MessageId) {
self.messageHistoryTable.addHoles([id], operationsByPeerId: &self.currentOperationsByPeerId, unsentMessageOperations: &currentUnsentOperations, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func fillHole(hole: MessageHistoryHole, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage]) {
private func fillHole(_ hole: MessageHistoryHole, fillType: HoleFill, tagMask: MessageTags?, messages: [StoreMessage]) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
self.messageHistoryTable.fillHole(hole.id, fillType: fillType, tagMask: tagMask, messages: messages, operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &currentUnsentOperations, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
for (peerId, operations) in operationsByPeerId {
if self.currentOperationsByPeerId[peerId] == nil {
self.currentOperationsByPeerId[peerId] = operations
} else {
self.currentOperationsByPeerId[peerId]!.appendContentsOf(operations)
self.currentOperationsByPeerId[peerId]!.append(contentsOf: operations)
}
var filledMessageIndices: [MessageIndex: HoleFillDirection] = [:]
@ -402,35 +402,35 @@ public final class Postbox {
}
}
private func replaceChatListHole(index: MessageIndex, hole: ChatListHole?) {
private func replaceChatListHole(_ index: MessageIndex, hole: ChatListHole?) {
self.currentReplaceChatListHoles.append((index, hole))
}
private func deleteMessages(messageIds: [MessageId]) {
private func deleteMessages(_ messageIds: [MessageId]) {
self.messageHistoryTable.removeMessages(messageIds, operationsByPeerId: &self.currentOperationsByPeerId, unsentMessageOperations: &currentUnsentOperations, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func resetIncomingReadStates(states: [PeerId: [MessageId.Namespace: PeerReadState]]) {
private func resetIncomingReadStates(_ states: [PeerId: [MessageId.Namespace: PeerReadState]]) {
self.messageHistoryTable.resetIncomingReadStates(states, operationsByPeerId: &self.currentOperationsByPeerId, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func confirmSynchronizedIncomingReadState(peerId: PeerId) {
private func confirmSynchronizedIncomingReadState(_ peerId: PeerId) {
self.synchronizeReadStateTable.set(peerId, operation: nil, operations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func applyIncomingReadMaxId(messageId: MessageId) {
private func applyIncomingReadMaxId(_ messageId: MessageId) {
self.messageHistoryTable.applyIncomingReadMaxId(messageId, operationsByPeerId: &self.currentOperationsByPeerId, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func applyOutgoingReadMaxId(messageId: MessageId) {
private func applyOutgoingReadMaxId(_ messageId: MessageId) {
self.messageHistoryTable.applyOutgoingReadMaxId(messageId, operationsByPeerId: &self.currentOperationsByPeerId, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func applyInteractiveReadMaxId(messageId: MessageId) {
private func applyInteractiveReadMaxId(_ messageId: MessageId) {
self.messageHistoryTable.applyInteractiveMaxReadId(messageId, operationsByPeerId: &self.currentOperationsByPeerId, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
private func fetchEarlierHistoryEntries(peerId: PeerId, index: MessageIndex?, count: Int, tagMask: MessageTags? = nil) -> [MutableMessageHistoryEntry] {
private func fetchEarlierHistoryEntries(_ peerId: PeerId, index: MessageIndex?, count: Int, tagMask: MessageTags? = nil) -> [MutableMessageHistoryEntry] {
let intermediateEntries: [IntermediateMessageHistoryEntry]
if let tagMask = tagMask {
intermediateEntries = self.messageHistoryTable.earlierEntries(tagMask, peerId: peerId, index: index, count: count)
@ -449,7 +449,7 @@ public final class Postbox {
return entries
}
private func fetchAroundHistoryEntries(index: MessageIndex, count: Int, tagMask: MessageTags? = nil) -> (entries: [MutableMessageHistoryEntry], lower: MutableMessageHistoryEntry?, upper: MutableMessageHistoryEntry?) {
private func fetchAroundHistoryEntries(_ index: MessageIndex, count: Int, tagMask: MessageTags? = nil) -> (entries: [MutableMessageHistoryEntry], lower: MutableMessageHistoryEntry?, upper: MutableMessageHistoryEntry?) {
let intermediateEntries: [IntermediateMessageHistoryEntry]
let intermediateLower: IntermediateMessageHistoryEntry?
@ -494,7 +494,7 @@ public final class Postbox {
return (entries: entries, lower: lower, upper: upper)
}
private func fetchLaterHistoryEntries(peerId: PeerId, index: MessageIndex?, count: Int, tagMask: MessageTags? = nil) -> [MutableMessageHistoryEntry] {
private func fetchLaterHistoryEntries(_ peerId: PeerId, index: MessageIndex?, count: Int, tagMask: MessageTags? = nil) -> [MutableMessageHistoryEntry] {
let intermediateEntries: [IntermediateMessageHistoryEntry]
if let tagMask = tagMask {
intermediateEntries = self.messageHistoryTable.laterEntries(tagMask, peerId: peerId, index: index, count: count)
@ -513,7 +513,7 @@ public final class Postbox {
return entries
}
private func fetchAroundChatEntries(index: MessageIndex, count: Int) -> (entries: [MutableChatListEntry], earlier: MutableChatListEntry?, later: MutableChatListEntry?) {
private func fetchAroundChatEntries(_ index: MessageIndex, count: Int) -> (entries: [MutableChatListEntry], earlier: MutableChatListEntry?, later: MutableChatListEntry?) {
let (intermediateEntries, intermediateLower, intermediateUpper) = self.chatListTable.entriesAround(index, messageHistoryTable: self.messageHistoryTable, count: count)
var entries: [MutableChatListEntry] = []
var lower: MutableChatListEntry?
@ -555,7 +555,7 @@ public final class Postbox {
return (entries, lower, upper)
}
private func fetchEarlierChatEntries(index: MessageIndex?, count: Int) -> [MutableChatListEntry] {
private func fetchEarlierChatEntries(_ index: MessageIndex?, count: Int) -> [MutableChatListEntry] {
let intermediateEntries = self.chatListTable.earlierEntries(index, messageHistoryTable: self.messageHistoryTable, count: count)
var entries: [MutableChatListEntry] = []
for entry in intermediateEntries {
@ -571,7 +571,7 @@ public final class Postbox {
return entries
}
private func fetchLaterChatEntries(index: MessageIndex?, count: Int) -> [MutableChatListEntry] {
private func fetchLaterChatEntries(_ index: MessageIndex?, count: Int) -> [MutableChatListEntry] {
let intermediateEntries = self.chatListTable.laterEntries(index, messageHistoryTable: self.messageHistoryTable, count: count)
var entries: [MutableChatListEntry] = []
for entry in intermediateEntries {
@ -587,27 +587,27 @@ public final class Postbox {
return entries
}
private func fetchAnchorIndex(id: MessageId) -> MessageHistoryAnchorIndex? {
private func fetchAnchorIndex(_ id: MessageId) -> MessageHistoryAnchorIndex? {
return self.messageHistoryTable.anchorIndex(id)
}
private func renderIntermediateMessage(message: IntermediateMessage) -> Message {
private func renderIntermediateMessage(_ message: IntermediateMessage) -> Message {
return self.messageHistoryTable.renderMessage(message, peerTable: self.peerTable)
}
private func fetchChatListHoleWrapper(hole: ChatListHole) -> Disposable {
private func fetchChatListHoleWrapper(_ hole: ChatListHole) -> Disposable {
return (self.fetchChatListHoleImpl.get() |> mapToSignal { fetch in
return fetch(hole)
}).start()
}
private func fetchMessageHistoryHoleWrapper(hole: MessageHistoryHole, direction: HoleFillDirection, tagMask: MessageTags?) -> Disposable {
private func fetchMessageHistoryHoleWrapper(_ hole: MessageHistoryHole, direction: HoleFillDirection, tagMask: MessageTags?) -> Disposable {
return (self.fetchMessageHistoryHoleImpl.get() |> mapToSignal { fetch in
return fetch(hole, direction, tagMask)
}).start()
}
private func sendUnsentMessageWrapper(index: MessageIndex) -> Disposable {
private func sendUnsentMessageWrapper(_ index: MessageIndex) -> Disposable {
return (self.sendUnsentMessageImpl.get() |> deliverOn(self.queue) |> mapToSignal { send -> Signal<Void, NoError> in
if let intermediateMessage = self.messageHistoryTable.getMessage(index) {
let message = self.renderIntermediateMessage(intermediateMessage)
@ -618,7 +618,7 @@ public final class Postbox {
}).start()
}
private func synchronizePeerReadStateWrapper(peerId: PeerId, operation: PeerReadStateSynchronizationOperation) -> Disposable {
private func synchronizePeerReadStateWrapper(_ peerId: PeerId, operation: PeerReadStateSynchronizationOperation) -> Disposable {
return (self.synchronizePeerReadStateImpl.get() |> mapToSignal { validate -> Signal<Void, NoError> in
return validate(peerId, operation)
}).start()
@ -647,7 +647,7 @@ public final class Postbox {
}
}
private func messageIdsForGlobalIds(ids: [Int32]) -> [MessageId] {
private func messageIdsForGlobalIds(_ ids: [Int32]) -> [MessageId] {
var result: [MessageId] = []
for globalId in ids {
if let id = self.globalMessageIdsTable.get(globalId) {
@ -657,7 +657,7 @@ public final class Postbox {
return result
}
private func updatePeers(peers: [Peer], update: (Peer, Peer) -> Peer?) {
private func updatePeers(_ peers: [Peer], update: (Peer, Peer) -> Peer?) {
for peer in peers {
if let currentPeer = self.peerTable.get(peer.id) {
if let updatedPeer = update(currentPeer, peer) {
@ -670,18 +670,18 @@ public final class Postbox {
}
}
private func updateMessage(index: MessageIndex, update: Message -> StoreMessage) {
private func updateMessage(_ index: MessageIndex, update: (Message) -> StoreMessage) {
if let intermediateMessage = self.messageHistoryTable.getMessage(index) {
let message = self.renderIntermediateMessage(intermediateMessage)
self.messageHistoryTable.updateMessage(index.id, message: update(message), operationsByPeerId: &self.currentOperationsByPeerId, unsentMessageOperations: &self.currentUnsentOperations, updatedPeerReadStateOperations: &self.currentUpdatedSynchronizeReadStateOperations)
}
}
private func updateMedia(id: MediaId, update: Media?) {
private func updateMedia(_ id: MediaId, update: Media?) {
self.messageHistoryTable.updateMedia(id, media: update, operationsByPeerId: &self.currentOperationsByPeerId, updatedMedia: &self.currentUpdatedMedia)
}
private func filterStoredMessageIds(messageIds: Set<MessageId>) -> Set<MessageId> {
private func filterStoredMessageIds(_ messageIds: Set<MessageId>) -> Set<MessageId> {
var filteredIds = Set<MessageId>()
for id in messageIds {
@ -693,7 +693,7 @@ public final class Postbox {
return filteredIds
}
public func modify<T>(f: Modifier -> T) -> Signal<T, NoError> {
public func modify<T>(_ f: (Modifier) -> T) -> Signal<T, NoError> {
return Signal { subscriber in
self.queue.justDispatch({
//let startTime = CFAbsoluteTimeGetCurrent()
@ -711,11 +711,11 @@ public final class Postbox {
}
}
public func aroundUnreadMessageHistoryViewForPeerId(peerId: PeerId, count: Int, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
public func aroundUnreadMessageHistoryViewForPeerId(_ peerId: PeerId, count: Int, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.queue.dispatch {
var index = MessageHistoryAnchorIndex(index: MessageIndex.upperBound(peerId), exact: true)
self.queue.async {
var index = MessageHistoryAnchorIndex(index: MessageIndex.upperBound(peerId: peerId), exact: true)
if let maxReadIndex = self.messageHistoryTable.maxReadIndex(peerId) {
index = maxReadIndex
}
@ -731,11 +731,11 @@ public final class Postbox {
}
}
public func aroundMessageHistoryViewForPeerId(peerId: PeerId, index: MessageIndex, count: Int, anchorIndex: MessageIndex, fixedCombinedReadState: CombinedPeerReadState?, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
public func aroundMessageHistoryViewForPeerId(_ peerId: PeerId, index: MessageIndex, count: Int, anchorIndex: MessageIndex, fixedCombinedReadState: CombinedPeerReadState?, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
return self.aroundMessageHistoryViewForPeerId(peerId, index: index, count: count, anchorIndex: MessageHistoryAnchorIndex(index: anchorIndex, exact: true), unreadIndex: nil, fixedCombinedReadState: fixedCombinedReadState, tagMask: tagMask)
}
private func aroundMessageHistoryViewForPeerId(peerId: PeerId, index: MessageIndex, count: Int, anchorIndex: MessageHistoryAnchorIndex, unreadIndex: MessageIndex?, fixedCombinedReadState: CombinedPeerReadState?, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
private func aroundMessageHistoryViewForPeerId(_ peerId: PeerId, index: MessageIndex, count: Int, anchorIndex: MessageHistoryAnchorIndex, unreadIndex: MessageIndex?, fixedCombinedReadState: CombinedPeerReadState?, tagMask: MessageTags? = nil) -> Signal<(MessageHistoryView, ViewUpdateType), NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
let startTime = CFAbsoluteTimeGetCurrent()
@ -744,15 +744,7 @@ public final class Postbox {
let (entries, earlier, later) = self.fetchAroundHistoryEntries(index, count: count, tagMask: tagMask)
print("aroundMessageHistoryViewForPeerId fetchAroundHistoryEntries \((CFAbsoluteTimeGetCurrent() - startTime) * 1000.0) ms")
var adjustedAnchorIndex = anchorIndex
/*if entries.count != 0 {
let minIndex = entries[0].index
if anchorIndex < minIndex {
//adjustedAnchorIndex = minIndex
}
}*/
let mutableView = MutableMessageHistoryView(id: MessageHistoryViewId(peerId: peerId, id: self.takeNextViewId()), anchorIndex: adjustedAnchorIndex, combinedReadState: fixedCombinedReadState ?? self.readStateTable.getCombinedState(peerId), earlier: earlier, entries: entries, later: later, tagMask: tagMask, count: count)
let mutableView = MutableMessageHistoryView(id: MessageHistoryViewId(peerId: peerId, id: self.takeNextViewId()), anchorIndex: anchorIndex, combinedReadState: fixedCombinedReadState ?? self.readStateTable.getCombinedState(peerId), earlier: earlier, entries: entries, later: later, tagMask: tagMask, count: count)
mutableView.render(self.renderIntermediateMessage)
//print("+ render \((CFAbsoluteTimeGetCurrent() - startTime) * 1000.0) ms")
@ -774,7 +766,7 @@ public final class Postbox {
pipeDisposable.dispose()
if let strongSelf = self {
strongSelf.queue.dispatch {
strongSelf.queue.async {
strongSelf.viewTracker.removeMessageHistoryView(peerId, index: index)
}
}
@ -786,7 +778,7 @@ public final class Postbox {
}
}
public func messageIndexAtId(id: MessageId) -> Signal<MessageIndex?, NoError> {
public func messageIndexAtId(_ id: MessageId) -> Signal<MessageIndex?, NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
@ -794,7 +786,7 @@ public final class Postbox {
if let entry = self.messageHistoryIndexTable.get(id), case let .Message(index) = entry {
subscriber.putNext(index)
subscriber.putCompletion()
} else if let hole = self.messageHistoryIndexTable.holeContainingId(id) {
} else if let _ = self.messageHistoryIndexTable.holeContainingId(id) {
subscriber.putNext(nil)
subscriber.putCompletion()
} else {
@ -807,11 +799,11 @@ public final class Postbox {
}
}
public func tailChatListView(count: Int) -> Signal<(ChatListView, ViewUpdateType), NoError> {
public func tailChatListView(_ count: Int) -> Signal<(ChatListView, ViewUpdateType), NoError> {
return self.aroundChatListView(MessageIndex.absoluteUpperBound(), count: count)
}
public func aroundChatListView(index: MessageIndex, count: Int) -> Signal<(ChatListView, ViewUpdateType), NoError> {
public func aroundChatListView(_ index: MessageIndex, count: Int) -> Signal<(ChatListView, ViewUpdateType), NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
@ -832,7 +824,7 @@ public final class Postbox {
pipeDisposable.dispose()
if let strongSelf = self {
strongSelf.queue.dispatch {
strongSelf.queue.async {
strongSelf.viewTracker.removeChatListView(index)
}
}
@ -844,7 +836,7 @@ public final class Postbox {
}
}
public func peerWithId(id: PeerId) -> Signal<Peer, NoError> {
public func peerWithId(_ id: PeerId) -> Signal<Peer, NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.queue.justDispatch({
@ -856,7 +848,7 @@ public final class Postbox {
}
}
public func updateMessageHistoryViewVisibleRange(id: MessageHistoryViewId, earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex) {
public func updateMessageHistoryViewVisibleRange(_ id: MessageHistoryViewId, earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex) {
self.queue.justDispatch({
self.viewTracker.updateMessageHistoryViewVisibleRange(id, earliestVisibleIndex: earliestVisibleIndex, latestVisibleIndex: latestVisibleIndex)
})

View File

@ -1,6 +1,6 @@
import Foundation
public struct SimpleDictionary<K: Equatable, V>: SequenceType {
public struct SimpleDictionary<K: Equatable, V>: Sequence {
private var items: [(K, V)] = []
public subscript(key: K) -> V? {
@ -18,7 +18,7 @@ public struct SimpleDictionary<K: Equatable, V>: SequenceType {
if let value = value {
self.items[index] = (k, value)
} else {
self.items.removeAtIndex(index)
self.items.remove(at: index)
}
return
}
@ -30,9 +30,11 @@ public struct SimpleDictionary<K: Equatable, V>: SequenceType {
}
}
public func generate() -> AnyGenerator<(K, V)> {
public func makeIterator() -> AnyIterator<(K, V)> {
var index = 0
return AnyGenerator { () -> (K, V)? in
return AnyIterator { () -> (K, V)? in
if index < self.items.count {
let currentIndex = index
index += 1

View File

@ -6,13 +6,13 @@ public struct SimpleSet<T: Equatable> {
public init() {
}
public mutating func insert(item: T) {
public mutating func insert(_ item: T) {
if !self.contains(item) {
self.items.append(item)
}
}
public func contains(item: T) -> Bool {
public func contains(_ item: T) -> Bool {
for currentItem in self.items {
if currentItem == item {
return true
@ -20,4 +20,4 @@ public struct SimpleSet<T: Equatable> {
}
return false
}
}
}

View File

@ -3,21 +3,21 @@ import sqlcipher
import SwiftSignalKit
private struct SqlitePreparedStatement {
let statement: COpaquePointer
let statement: OpaquePointer?
func bind(index: Int, data: UnsafePointer<Void>, length: Int) {
func bind(_ index: Int, data: UnsafePointer<Void>, length: Int) {
sqlite3_bind_blob(statement, Int32(index), data, Int32(length), nil)
}
func bindNull(index: Int) {
func bindNull(_ index: Int) {
sqlite3_bind_null(statement, Int32(index))
}
func bind(index: Int, number: Int32) {
func bind(_ index: Int, number: Int32) {
sqlite3_bind_int(statement, Int32(index), number)
}
func bind(index: Int, number: Int64) {
func bind(_ index: Int, number: Int64) {
sqlite3_bind_int64(statement, Int32(index), number)
}
@ -34,20 +34,20 @@ private struct SqlitePreparedStatement {
return result == SQLITE_ROW
}
func int64At(index: Int) -> Int64 {
func int64At(_ index: Int) -> Int64 {
return sqlite3_column_int64(statement, Int32(index))
}
func valueAt(index: Int) -> ReadBuffer {
func valueAt(_ index: Int) -> ReadBuffer {
let valueLength = sqlite3_column_bytes(statement, Int32(index))
let valueData = sqlite3_column_blob(statement, Int32(index))
let valueMemory = malloc(Int(valueLength))
let valueMemory = malloc(Int(valueLength))!
memcpy(valueMemory, valueData, Int(valueLength))
return ReadBuffer(memory: valueMemory, length: Int(valueLength), freeWhenDone: true)
}
func keyAt(index: Int) -> ValueBoxKey {
func keyAt(_ index: Int) -> ValueBoxKey {
let valueLength = sqlite3_column_bytes(statement, Int32(index))
let valueData = sqlite3_column_blob(statement, Int32(index))
@ -62,7 +62,7 @@ private struct SqlitePreparedStatement {
}
public final class SqliteValueBox: ValueBox {
private let lock = NSRecursiveLock()
private let lock = RecursiveLock()
private let basePath: String
private var database: Database!
@ -102,7 +102,7 @@ public final class SqliteValueBox: ValueBox {
lock.lock()
do {
try NSFileManager.defaultManager().createDirectoryAtPath(basePath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: basePath, withIntermediateDirectories: true, attributes: nil)
} catch _ { }
let path = basePath + "/db_sqlite"
let database = Database(path)
@ -160,18 +160,18 @@ public final class SqliteValueBox: ValueBox {
self.commitTime += CFAbsoluteTimeGetCurrent() - startTime
}
private func getUserVersion(database: Database) -> Int64 {
var statement: COpaquePointer = nil
private func getUserVersion(_ database: Database) -> Int64 {
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(database.handle, "PRAGMA user_version", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
preparedStatement.step()
let _ = preparedStatement.step()
let value = preparedStatement.int64At(0)
preparedStatement.destroy()
return value
}
private func listTables(database: Database) -> [Int64] {
var statement: COpaquePointer = nil
private func listTables(_ database: Database) -> [Int64] {
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(database.handle, "SELECT name FROM __meta_tables", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
var tables: [Int64] = []
@ -183,13 +183,13 @@ public final class SqliteValueBox: ValueBox {
return tables
}
private func getStatement(table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
private func getStatement(_ table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.getStatements[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT value FROM t\(table) WHERE key=?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.getStatements[table] = preparedStatement
@ -203,13 +203,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeKeyAscStatementLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
private func rangeKeyAscStatementLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeKeyAscStatementsLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key FROM t\(table) WHERE key > ? AND key < ? ORDER BY key ASC LIMIT ?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeKeyAscStatementsLimit[table] = preparedStatement
@ -224,13 +224,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeKeyAscStatementNoLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
private func rangeKeyAscStatementNoLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeKeyAscStatementsNoLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key FROM t\(table) WHERE key > ? AND key < ? ORDER BY key ASC", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeKeyAscStatementsNoLimit[table] = preparedStatement
@ -245,13 +245,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeKeyDescStatementLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
private func rangeKeyDescStatementLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeKeyDescStatementsLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key FROM t\(table) WHERE key > ? AND key < ? ORDER BY key DESC LIMIT ?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeKeyDescStatementsLimit[table] = preparedStatement
@ -267,13 +267,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeKeyDescStatementNoLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
private func rangeKeyDescStatementNoLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeKeyDescStatementsNoLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key FROM t\(table) WHERE key > ? AND key < ? ORDER BY key DESC", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeKeyDescStatementsNoLimit[table] = preparedStatement
@ -288,13 +288,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeValueAscStatementLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
private func rangeValueAscStatementLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeValueAscStatementsLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key, value FROM t\(table) WHERE key > ? AND key < ? ORDER BY key ASC LIMIT ?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeValueAscStatementsLimit[table] = preparedStatement
@ -309,13 +309,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeValueAscStatementNoLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
private func rangeValueAscStatementNoLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeValueAscStatementsNoLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key, value FROM t\(table) WHERE key > ? AND key < ? ORDER BY key ASC", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeValueAscStatementsNoLimit[table] = preparedStatement
@ -330,13 +330,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeValueDescStatementLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
private func rangeValueDescStatementLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, limit: Int) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeValueDescStatementsLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key, value FROM t\(table) WHERE key > ? AND key < ? ORDER BY key DESC LIMIT ?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeValueDescStatementsLimit[table] = preparedStatement
@ -352,13 +352,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func rangeValueDescStatementNoLimit(table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
private func rangeValueDescStatementNoLimit(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.rangeKeyDescStatementsNoLimit[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT key, value FROM t\(table) WHERE key > ? AND key < ? ORDER BY key DESC", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.rangeValueDescStatementsNoLimit[table] = preparedStatement
@ -373,13 +373,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func existsStatement(table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
private func existsStatement(_ table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.existsStatements[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "SELECT rowid FROM t\(table) WHERE key=?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.existsStatements[table] = preparedStatement
@ -393,13 +393,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func updateStatement(table: Int32, key: ValueBoxKey, value: MemoryBuffer) -> SqlitePreparedStatement {
private func updateStatement(_ table: Int32, key: ValueBoxKey, value: MemoryBuffer) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.updateStatements[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "UPDATE t\(table) SET value=? WHERE key=?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.updateStatements[table] = preparedStatement
@ -414,13 +414,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func insertStatement(table: Int32, key: ValueBoxKey, value: MemoryBuffer) -> SqlitePreparedStatement {
private func insertStatement(_ table: Int32, key: ValueBoxKey, value: MemoryBuffer) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.insertStatements[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "INSERT INTO t\(table) (key, value) VALUES(?, ?)", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.insertStatements[table] = preparedStatement
@ -430,7 +430,7 @@ public final class SqliteValueBox: ValueBox {
resultStatement.reset()
resultStatement.bind(1, data: key.memory, length: key.length)
if value.memory == nil {
if value.length == 0 {
resultStatement.bindNull(2)
} else {
resultStatement.bind(2, data: value.memory, length: value.length)
@ -439,13 +439,13 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
private func deleteStatement(table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
private func deleteStatement(_ table: Int32, key: ValueBoxKey) -> SqlitePreparedStatement {
let resultStatement: SqlitePreparedStatement
if let statement = self.deleteStatements[table] {
resultStatement = statement
} else {
var statement: COpaquePointer = nil
var statement: OpaquePointer? = nil
sqlite3_prepare_v2(self.database.handle, "DELETE FROM t\(table) WHERE key=?", -1, &statement, nil)
let preparedStatement = SqlitePreparedStatement(statement: statement)
self.deleteStatements[table] = preparedStatement
@ -459,7 +459,7 @@ public final class SqliteValueBox: ValueBox {
return resultStatement
}
public func get(table: Int32, key: ValueBoxKey) -> ReadBuffer? {
public func get(_ table: Int32, key: ValueBoxKey) -> ReadBuffer? {
let startTime = CFAbsoluteTimeGetCurrent()
if self.tables.contains(table) {
let statement = self.getStatement(table, key: key)
@ -481,14 +481,14 @@ public final class SqliteValueBox: ValueBox {
return nil
}
public func exists(table: Int32, key: ValueBoxKey) -> Bool {
public func exists(_ table: Int32, key: ValueBoxKey) -> Bool {
if let _ = self.get(table, key: key) {
return true
}
return false
}
public func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape values: (ValueBoxKey, ReadBuffer) -> Bool, limit: Int) {
public func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, values: @noescape(ValueBoxKey, ReadBuffer) -> Bool, limit: Int) {
if start == end {
return
}
@ -535,7 +535,7 @@ public final class SqliteValueBox: ValueBox {
}
}
public func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape keys: ValueBoxKey -> Bool, limit: Int) {
public func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, keys: @noescape(ValueBoxKey) -> Bool, limit: Int) {
if self.tables.contains(table) {
let statement: SqlitePreparedStatement
@ -577,7 +577,7 @@ public final class SqliteValueBox: ValueBox {
}
}
public func set(table: Int32, key: ValueBoxKey, value: MemoryBuffer) {
public func set(_ table: Int32, key: ValueBoxKey, value: MemoryBuffer) {
if !self.tables.contains(table) {
self.database.execute("CREATE TABLE t\(table) (key BLOB, value BLOB)")
self.database.execute("CREATE INDEX t\(table)_key ON t\(table) (key)")
@ -609,7 +609,7 @@ public final class SqliteValueBox: ValueBox {
self.writeQueryTime += CFAbsoluteTimeGetCurrent() - startTime
}
public func remove(table: Int32, key: ValueBoxKey) {
public func remove(_ table: Int32, key: ValueBoxKey) {
if self.tables.contains(table) {
let startTime = CFAbsoluteTimeGetCurrent()
@ -697,7 +697,7 @@ public final class SqliteValueBox: ValueBox {
self.database = nil
self.lock.unlock()
let _ = try? NSFileManager.defaultManager().removeItemAtPath(self.basePath)
let _ = try? FileManager.default().removeItem(atPath: self.basePath)
self.database = self.openDatabase()
tables.removeAll()

View File

@ -7,7 +7,7 @@ final class SynchronizePeerReadStatesView {
self.operations = operations
}
func replay(updatedOperations: [PeerId: PeerReadStateSynchronizationOperation?]) -> [PeerId: PeerReadStateSynchronizationOperation?] {
func replay(_ updatedOperations: [PeerId: PeerReadStateSynchronizationOperation?]) -> [PeerId: PeerReadStateSynchronizationOperation?] {
var updates: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
for (peerId, operation) in updatedOperations {
@ -18,7 +18,7 @@ final class SynchronizePeerReadStatesView {
}
} else {
if let _ = self.operations[peerId] {
self.operations.removeValueForKey(peerId)
let _ = self.operations.removeValue(forKey: peerId)
updates[peerId] = nil
}
}

View File

@ -7,7 +7,7 @@ final class UnsentMessageHistoryView {
self.indices = indices
}
func replay(operations: [IntermediateMessageHistoryUnsentOperation]) -> Bool {
func replay(_ operations: [IntermediateMessageHistoryUnsentOperation]) -> Bool {
var updated = false
for operation in operations {
switch operation {
@ -15,7 +15,7 @@ final class UnsentMessageHistoryView {
var inserted = false
for i in 0 ..< self.indices.count {
if self.indices[i] > index {
self.indices.insert(index, atIndex: i)
self.indices.insert(index, at: i)
inserted = true
break
}
@ -27,7 +27,7 @@ final class UnsentMessageHistoryView {
case let .Remove(index):
for i in 0 ..< self.indices.count {
if self.indices[i] == index {
self.indices.removeAtIndex(i)
self.indices.remove(at: i)
updated = true
break
}

View File

@ -7,11 +7,11 @@ public protocol ValueBox {
func beginStats()
func endStats()
func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape values: (ValueBoxKey, ReadBuffer) -> Bool, limit: Int)
func range(table: Int32, start: ValueBoxKey, end: ValueBoxKey, @noescape keys: ValueBoxKey -> Bool, limit: Int)
func get(table: Int32, key: ValueBoxKey) -> ReadBuffer?
func exists(table: Int32, key: ValueBoxKey) -> Bool
func set(table: Int32, key: ValueBoxKey, value: MemoryBuffer)
func remove(table: Int32, key: ValueBoxKey)
func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, values: @noescape(ValueBoxKey, ReadBuffer) -> Bool, limit: Int)
func range(_ table: Int32, start: ValueBoxKey, end: ValueBoxKey, keys: @noescape(ValueBoxKey) -> Bool, limit: Int)
func get(_ table: Int32, key: ValueBoxKey) -> ReadBuffer?
func exists(_ table: Int32, key: ValueBoxKey) -> Bool
func set(_ table: Int32, key: ValueBoxKey, value: MemoryBuffer)
func remove(_ table: Int32, key: ValueBoxKey)
func drop()
}

View File

@ -24,11 +24,11 @@ public struct ValueBoxKey: Comparable, CustomStringConvertible {
}
public init(_ value: String) {
let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
self.memory = malloc(data.length)
self.length = data.length
let data = value.data(using: .utf8, allowLossyConversion: true)!
self.memory = malloc(data.count)
self.length = data.count
self.impl = ValueBoxKeyImpl(memory: self.memory)
memcpy(self.memory, data.bytes, data.length)
data.copyBytes(to: UnsafeMutablePointer<UInt8>(self.memory), count: data.count)
}
public init(_ buffer: MemoryBuffer) {
@ -38,51 +38,51 @@ public struct ValueBoxKey: Comparable, CustomStringConvertible {
memcpy(self.memory, buffer.memory, buffer.length)
}
public func setInt32(offset: Int, value: Int32) {
public func setInt32(_ offset: Int, value: Int32) {
var bigEndianValue = Int32(bigEndian: value)
memcpy(self.memory + offset, &bigEndianValue, 4)
}
public func setUInt32(offset: Int, value: UInt32) {
public func setUInt32(_ offset: Int, value: UInt32) {
var bigEndianValue = UInt32(bigEndian: value)
memcpy(self.memory + offset, &bigEndianValue, 4)
}
public func setInt64(offset: Int, value: Int64) {
public func setInt64(_ offset: Int, value: Int64) {
var bigEndianValue = Int64(bigEndian: value)
memcpy(self.memory + offset, &bigEndianValue, 8)
}
public func setInt8(offset: Int, value: Int8) {
public func setInt8(_ offset: Int, value: Int8) {
var varValue = value
memcpy(self.memory + offset, &varValue, 1)
}
public func getInt32(offset: Int) -> Int32 {
public func getInt32(_ offset: Int) -> Int32 {
var value: Int32 = 0
memcpy(&value, self.memory + offset, 4)
return Int32(bigEndian: value)
}
public func getUInt32(offset: Int) -> UInt32 {
public func getUInt32(_ offset: Int) -> UInt32 {
var value: UInt32 = 0
memcpy(&value, self.memory + offset, 4)
return UInt32(bigEndian: value)
}
public func getInt64(offset: Int) -> Int64 {
public func getInt64(_ offset: Int) -> Int64 {
var value: Int64 = 0
memcpy(&value, self.memory + offset, 8)
return Int64(bigEndian: value)
}
public func getInt8(offset: Int) -> Int8 {
public func getInt8(_ offset: Int) -> Int8 {
var value: Int8 = 0
memcpy(&value, self.memory + offset, 1)
return value
}
public func prefix(length: Int) -> ValueBoxKey {
public func prefix(_ length: Int) -> ValueBoxKey {
assert(length <= self.length, "length <= self.length")
let key = ValueBoxKey(length: length)
memcpy(key.memory, self.memory, length)
@ -144,7 +144,7 @@ public func ==(lhs: ValueBoxKey, rhs: ValueBoxKey) -> Bool {
return lhs.length == rhs.length && memcmp(lhs.memory, rhs.memory, lhs.length) == 0
}
private func mdb_cmp_memn(a_memory: UnsafeMutablePointer<Void>, _ a_length: Int, _ b_memory: UnsafeMutablePointer<Void>, _ b_length: Int) -> Int
private func mdb_cmp_memn(_ a_memory: UnsafeMutablePointer<Void>, _ a_length: Int, _ b_memory: UnsafeMutablePointer<Void>, _ b_length: Int) -> Int
{
var diff: Int = 0
var len_diff: Int = 0

View File

@ -15,14 +15,14 @@ final class ViewTracker {
private let fetchEarlierChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry]
private let fetchLaterChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry]
private let fetchAnchorIndex: (MessageId) -> MessageHistoryAnchorIndex?
private let renderMessage: IntermediateMessage -> Message
private let fetchChatListHole: ChatListHole -> Disposable
private let renderMessage: (IntermediateMessage) -> Message
private let fetchChatListHole: (ChatListHole) -> Disposable
private let fetchMessageHistoryHole: (MessageHistoryHole, HoleFillDirection, MessageTags?) -> Disposable
private let sendUnsentMessage: MessageIndex -> Disposable
private let sendUnsentMessage: (MessageIndex) -> Disposable
private let synchronizeReadState: (PeerId, PeerReadStateSynchronizationOperation) -> Disposable
private var chatListViews = Bag<(MutableChatListView, Pipe<(ChatListView, ViewUpdateType)>)>()
private var messageHistoryViews: [PeerId: Bag<(MutableMessageHistoryView, Pipe<(MessageHistoryView, ViewUpdateType)>)>] = [:]
private var chatListViews = Bag<(MutableChatListView, ValuePipe<(ChatListView, ViewUpdateType)>)>()
private var messageHistoryViews: [PeerId: Bag<(MutableMessageHistoryView, ValuePipe<(MessageHistoryView, ViewUpdateType)>)>] = [:]
private var unsentMessageView: UnsentMessageHistoryView
private var synchronizeReadStatesView: SynchronizePeerReadStatesView
@ -31,7 +31,7 @@ final class ViewTracker {
private var unsentMessageDisposables: [MessageIndex: Disposable] = [:]
private var synchronizeReadStatesDisposables: [PeerId: (PeerReadStateSynchronizationOperation, Disposable)] = [:]
init(queue: Queue, fetchEarlierHistoryEntries: (PeerId, MessageIndex?, Int, MessageTags?) -> [MutableMessageHistoryEntry], fetchLaterHistoryEntries: (PeerId, MessageIndex?, Int, MessageTags?) -> [MutableMessageHistoryEntry], fetchEarlierChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry], fetchLaterChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry], fetchAnchorIndex: (MessageId) -> MessageHistoryAnchorIndex?, renderMessage: IntermediateMessage -> Message, fetchChatListHole: ChatListHole -> Disposable, fetchMessageHistoryHole: (MessageHistoryHole, HoleFillDirection, MessageTags?) -> Disposable, sendUnsentMessage: MessageIndex -> Disposable, unsentMessageIndices: [MessageIndex], synchronizeReadState: (PeerId, PeerReadStateSynchronizationOperation) -> Disposable, synchronizePeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation]) {
init(queue: Queue, fetchEarlierHistoryEntries: (PeerId, MessageIndex?, Int, MessageTags?) -> [MutableMessageHistoryEntry], fetchLaterHistoryEntries: (PeerId, MessageIndex?, Int, MessageTags?) -> [MutableMessageHistoryEntry], fetchEarlierChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry], fetchLaterChatEntries: (MessageIndex?, Int) -> [MutableChatListEntry], fetchAnchorIndex: (MessageId) -> MessageHistoryAnchorIndex?, renderMessage: (IntermediateMessage) -> Message, fetchChatListHole: (ChatListHole) -> Disposable, fetchMessageHistoryHole: (MessageHistoryHole, HoleFillDirection, MessageTags?) -> Disposable, sendUnsentMessage: (MessageIndex) -> Disposable, unsentMessageIndices: [MessageIndex], synchronizeReadState: (PeerId, PeerReadStateSynchronizationOperation) -> Disposable, synchronizePeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation]) {
self.queue = queue
self.fetchEarlierHistoryEntries = fetchEarlierHistoryEntries
self.fetchLaterHistoryEntries = fetchLaterHistoryEntries
@ -67,14 +67,14 @@ final class ViewTracker {
}
}
func addMessageHistoryView(peerId: PeerId, view: MutableMessageHistoryView) -> (Bag<(MutableMessageHistoryView, Pipe<(MessageHistoryView, ViewUpdateType)>)>.Index, Signal<(MessageHistoryView, ViewUpdateType), NoError>) {
let record = (view, Pipe<(MessageHistoryView, ViewUpdateType)>())
func addMessageHistoryView(_ peerId: PeerId, view: MutableMessageHistoryView) -> (Bag<(MutableMessageHistoryView, ValuePipe<(MessageHistoryView, ViewUpdateType)>)>.Index, Signal<(MessageHistoryView, ViewUpdateType), NoError>) {
let record = (view, ValuePipe<(MessageHistoryView, ViewUpdateType)>())
let index: Bag<(MutableMessageHistoryView, Pipe<(MessageHistoryView, ViewUpdateType)>)>.Index
let index: Bag<(MutableMessageHistoryView, ValuePipe<(MessageHistoryView, ViewUpdateType)>)>.Index
if let bag = self.messageHistoryViews[peerId] {
index = bag.add(record)
} else {
let bag = Bag<(MutableMessageHistoryView, Pipe<(MessageHistoryView, ViewUpdateType)>)>()
let bag = Bag<(MutableMessageHistoryView, ValuePipe<(MessageHistoryView, ViewUpdateType)>)>()
index = bag.add(record)
self.messageHistoryViews[peerId] = bag
}
@ -84,7 +84,7 @@ final class ViewTracker {
return (index, record.1.signal())
}
func removeMessageHistoryView(peerId: PeerId, index: Bag<(MutableMessageHistoryView, Pipe<(MessageHistoryView, ViewUpdateType)>)>.Index) {
func removeMessageHistoryView(_ peerId: PeerId, index: Bag<(MutableMessageHistoryView, ValuePipe<(MessageHistoryView, ViewUpdateType)>)>.Index) {
if let bag = self.messageHistoryViews[peerId] {
bag.remove(index)
@ -92,8 +92,8 @@ final class ViewTracker {
}
}
func addChatListView(view: MutableChatListView) -> (Bag<(MutableChatListView, Pipe<(ChatListView, ViewUpdateType)>)>.Index, Signal<(ChatListView, ViewUpdateType), NoError>) {
let record = (view, Pipe<(ChatListView, ViewUpdateType)>())
func addChatListView(_ view: MutableChatListView) -> (Bag<(MutableChatListView, ValuePipe<(ChatListView, ViewUpdateType)>)>.Index, Signal<(ChatListView, ViewUpdateType), NoError>) {
let record = (view, ValuePipe<(ChatListView, ViewUpdateType)>())
let index = self.chatListViews.add(record)
self.updateTrackedChatListHoles()
@ -101,12 +101,12 @@ final class ViewTracker {
return (index, record.1.signal())
}
func removeChatListView(index: Bag<(MutableChatListView, Pipe<ChatListView>)>.Index) {
func removeChatListView(_ index: Bag<(MutableChatListView, ValuePipe<ChatListView>)>.Index) {
self.chatListViews.remove(index)
self.updateTrackedChatListHoles()
}
func updateMessageHistoryViewVisibleRange(id: MessageHistoryViewId, earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex) {
func updateMessageHistoryViewVisibleRange(_ id: MessageHistoryViewId, earliestVisibleIndex: MessageIndex, latestVisibleIndex: MessageIndex) {
if let bag = self.messageHistoryViews[id.peerId] {
for (mutableView, pipe) in bag.copyItems() {
if mutableView.id == id {
@ -116,7 +116,7 @@ final class ViewTracker {
let updateType: ViewUpdateType = .UpdateVisible
if mutableView.updateVisibleRange(earliestVisibleIndex: earliestVisibleIndex, latestVisibleIndex: latestVisibleIndex, context: context) {
mutableView.complete(context, fetchEarlier: { index, count in
mutableView.complete(context: context, fetchEarlier: { index, count in
return self.fetchEarlierHistoryEntries(id.peerId, index, count, mutableView.tagMask)
}, fetchLater: { index, count in
return self.fetchLaterHistoryEntries(id.peerId, index, count, mutableView.tagMask)
@ -138,7 +138,7 @@ final class ViewTracker {
}
}
func updateViews(currentOperationsByPeerId currentOperationsByPeerId: [PeerId: [MessageHistoryOperation]], peerIdsWithFilledHoles: [PeerId: [MessageIndex: HoleFillDirection]], removedHolesByPeerId: [PeerId: [MessageIndex: HoleFillDirection]], chatListOperations: [ChatListOperation], currentUpdatedPeers: [PeerId: Peer], unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], updatedSynchronizePeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?], updatedMedia: [MediaId: Media?]) {
func updateViews(currentOperationsByPeerId: [PeerId: [MessageHistoryOperation]], peerIdsWithFilledHoles: [PeerId: [MessageIndex: HoleFillDirection]], removedHolesByPeerId: [PeerId: [MessageIndex: HoleFillDirection]], chatListOperations: [ChatListOperation], currentUpdatedPeers: [PeerId: Peer], unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation], updatedSynchronizePeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?], updatedMedia: [MediaId: Media?]) {
var updateTrackedHolesPeerIds: [PeerId] = []
for (peerId, bag) in self.messageHistoryViews {
@ -158,7 +158,7 @@ final class ViewTracker {
}
if mutableView.replay(operations ?? [], holeFillDirections: peerIdsWithFilledHoles[peerId] ?? [:], updatedMedia: updatedMedia, context: context) {
mutableView.complete(context, fetchEarlier: { index, count in
mutableView.complete(context: context, fetchEarlier: { index, count in
return self.fetchEarlierHistoryEntries(peerId, index, count, mutableView.tagMask)
}, fetchLater: { index, count in
return self.fetchLaterHistoryEntries(peerId, index, count, mutableView.tagMask)
@ -193,7 +193,7 @@ final class ViewTracker {
for (mutableView, pipe) in self.chatListViews.copyItems() {
let context = MutableChatListViewReplayContext()
if mutableView.replay(chatListOperations, context: context) {
mutableView.complete(context, fetchEarlier: self.fetchEarlierChatEntries, fetchLater: self.fetchLaterChatEntries)
mutableView.complete(context: context, fetchEarlier: self.fetchEarlierChatEntries, fetchLater: self.fetchLaterChatEntries)
mutableView.render(self.renderMessage)
pipe.putNext((ChatListView(mutableView), .Generic))
}
@ -246,7 +246,7 @@ final class ViewTracker {
}
if !exists {
disposeHoles.append(disposable)
self.chatListHoleDisposables.removeAtIndex(i)
self.chatListHoleDisposables.remove(at: i)
} else {
i += 1
}
@ -271,7 +271,7 @@ final class ViewTracker {
}
}
private func updateTrackedHoles(peerId: PeerId) {
private func updateTrackedHoles(_ peerId: PeerId) {
if let bag = self.messageHistoryViews[peerId] {
var disposeHoles: [Disposable] = []
var firstHolesAndTags: [(MessageHistoryHole, HoleFillDirection, MessageTags?)] = []
@ -294,7 +294,7 @@ final class ViewTracker {
}
if !exists {
disposeHoles.append(disposable)
self.holeDisposablesByPeerId[peerId]!.removeAtIndex(i)
self.holeDisposablesByPeerId[peerId]!.remove(at: i)
} else {
i += 1
}
@ -352,7 +352,7 @@ final class ViewTracker {
}
for index in removeIndices {
self.unsentMessageDisposables.removeValueForKey(index)?.dispose()
self.unsentMessageDisposables.removeValue(forKey: index)?.dispose()
}
for index in self.unsentMessageView.indices {
@ -370,9 +370,9 @@ final class ViewTracker {
}
}
private func synchronizeReadStateViewUpdated(updates: [PeerId: PeerReadStateSynchronizationOperation?]) {
private func synchronizeReadStateViewUpdated(_ updates: [PeerId: PeerReadStateSynchronizationOperation?]) {
for (peerId, operation) in updates {
if let (_, disposable) = self.synchronizeReadStatesDisposables.removeValueForKey(peerId) {
if let (_, disposable) = self.synchronizeReadStatesDisposables.removeValue(forKey: peerId) {
disposable.dispose()
}

View File

@ -85,7 +85,7 @@ class ChatListTableTests: XCTestCase {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
path = NSTemporaryDirectory().stringByAppendingString("\(randomId)")
path = NSTemporaryDirectory() + "\(randomId)"
self.valueBox = SqliteValueBox(basePath: path!)
let seedConfiguration = SeedConfiguration(initializeChatListWithHoles: [], initializeMessageNamespacesWithHoles: [], existingMessageTags: [])
@ -115,11 +115,11 @@ class ChatListTableTests: XCTestCase {
self.chatListTable = nil
self.valueBox = nil
let _ = try? NSFileManager.defaultManager().removeItemAtPath(path!)
let _ = try? FileManager.default().removeItem(atPath: path!)
self.path = nil
}
private func addMessage(peerId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = []) {
private func addMessage(_ peerId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = []) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
@ -128,7 +128,7 @@ class ChatListTableTests: XCTestCase {
self.chatListTable!.replay(operationsByPeerId, messageHistoryTable: self.historyTable!, operations: &operations)
}
private func addHole(peerId: Int32, _ id: Int32) {
private func addHole(_ peerId: Int32, _ id: Int32) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
@ -137,22 +137,22 @@ class ChatListTableTests: XCTestCase {
self.chatListTable!.replay(operationsByPeerId, messageHistoryTable: self.historyTable!, operations: &operations)
}
private func addChatListHole(peerId: Int32, _ id: Int32, _ timestamp: Int32) {
private func addChatListHole(_ peerId: Int32, _ id: Int32, _ timestamp: Int32) {
var operations: [ChatListOperation] = []
self.chatListTable!.addHole(ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: namespace, id: peerId), namespace: namespace, id: id), timestamp: timestamp)), operations: &operations)
}
private func replaceChatListHole(peerId: Int32, _ id: Int32, _ timestamp: Int32, _ otherPeerId: Int32, _ otherId: Int32, _ otherTimestamp: Int32) {
private func replaceChatListHole(_ peerId: Int32, _ id: Int32, _ timestamp: Int32, _ otherPeerId: Int32, _ otherId: Int32, _ otherTimestamp: Int32) {
var operations: [ChatListOperation] = []
self.chatListTable!.replaceHole(MessageIndex(id: MessageId(peerId: PeerId(namespace: namespace, id: peerId), namespace: namespace, id: id), timestamp: timestamp), hole: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: namespace, id: otherPeerId), namespace: namespace, id: otherId), timestamp: otherTimestamp)), operations: &operations)
}
private func removeChatListHole(peerId: Int32, _ id: Int32, _ timestamp: Int32) {
private func removeChatListHole(_ peerId: Int32, _ id: Int32, _ timestamp: Int32) {
var operations: [ChatListOperation] = []
self.chatListTable!.replaceHole(MessageIndex(id: MessageId(peerId: PeerId(namespace: namespace, id: peerId), namespace: namespace, id: id), timestamp: timestamp), hole: nil, operations: &operations)
}
private func removeMessages(peerId: Int32, _ ids: [Int32]) {
private func removeMessages(_ peerId: Int32, _ ids: [Int32]) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
@ -161,7 +161,7 @@ class ChatListTableTests: XCTestCase {
self.chatListTable!.replay(operationsByPeerId, messageHistoryTable: self.historyTable!, operations: &operations)
}
private func fillHole(peerId: Int32, _ id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32, String, [Media])]) {
private func fillHole(_ peerId: Int32, _ id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32, String, [Media])]) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
@ -170,7 +170,7 @@ class ChatListTableTests: XCTestCase {
self.chatListTable!.replay(operationsByPeerId, messageHistoryTable: self.historyTable!, operations: &operations)
}
private func expectEntries(entries: [Entry]) {
private func expectEntries(_ entries: [Entry]) {
let actualEntries = self.chatListTable!.debugList(self.historyTable!).map({ entry -> Entry in
switch entry {
case let .Message(message):
@ -276,4 +276,4 @@ class ChatListTableTests: XCTestCase {
removeChatListHole(1, 100, 100)
expectEntries([])
}
}
}

View File

@ -14,7 +14,7 @@ class TestParent: Coding, Equatable {
self.parentInt32 = parentInt32
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
encoder.encodeInt32(self.parentInt32, forKey: "parentInt32")
}
}
@ -47,7 +47,7 @@ class TestObject: TestParent {
super.init(parentInt32: parentInt32)
}
override func encode(encoder: Encoder) {
override func encode(_ encoder: Encoder) {
encoder.encodeInt32(self.int32, forKey: "int32")
encoder.encodeInt64(self.int64, forKey: "int64")
encoder.encodeDouble(self.double, forKey: "double")
@ -68,7 +68,7 @@ class TestKey: Coding, Hashable {
self.value = value
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
encoder.encodeInt32(Int32(self.value), forKey: "value")
}
@ -101,7 +101,7 @@ class EmptyState: Coding {
required init(decoder: Decoder) {
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
}
}

View File

@ -72,7 +72,7 @@ class MessageHistoryIndexTableTests: XCTestCase {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
path = NSTemporaryDirectory().stringByAppendingString("\(randomId)")
path = NSTemporaryDirectory() + "\(randomId)"
self.valueBox = SqliteValueBox(basePath: path!)
let seedConfiguration = SeedConfiguration(initializeChatListWithHoles: [], initializeMessageNamespacesWithHoles: [], existingMessageTags: [])
@ -88,28 +88,28 @@ class MessageHistoryIndexTableTests: XCTestCase {
self.indexTable = nil
self.valueBox = nil
let _ = try? NSFileManager.defaultManager().removeItemAtPath(path!)
let _ = try? FileManager.default().removeItem(atPath: path!)
self.path = nil
}
func addHole(id: Int32) {
func addHole(_ id: Int32) {
var operations: [MessageHistoryIndexOperation] = []
self.indexTable!.addHole(MessageId(peerId: peerId, namespace: namespace, id: id), operations: &operations)
}
func addMessage(id: Int32, _ timestamp: Int32) {
func addMessage(_ id: Int32, _ timestamp: Int32) {
var operations: [MessageHistoryIndexOperation] = []
self.indexTable!.addMessages([InternalStoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: [], tags: [], forwardInfo: nil, authorId: peerId, text: "", attributes: [], media: [])], location: .Random, operations: &operations)
}
func addMessagesUpperBlock(messages: [(Int32, Int32)]) {
func addMessagesUpperBlock(_ messages: [(Int32, Int32)]) {
var operations: [MessageHistoryIndexOperation] = []
self.indexTable!.addMessages(messages.map { (id, timestamp) in
return InternalStoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: [], tags: [], forwardInfo: nil, authorId: peerId, text: "", attributes: [], media: [])
}, location: .UpperHistoryBlock, operations: &operations)
}
func fillHole(id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32)], _ tagMask: MessageTags? = nil) {
func fillHole(_ id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32)], _ tagMask: MessageTags? = nil) {
var operations: [MessageHistoryIndexOperation] = []
self.indexTable!.fillHole(MessageId(peerId: peerId, namespace: namespace, id: id), fillType: fillType, tagMask: tagMask, messages: messages.map({
@ -117,12 +117,12 @@ class MessageHistoryIndexTableTests: XCTestCase {
}), operations: &operations)
}
func removeMessage(id: Int32) {
func removeMessage(_ id: Int32) {
var operations: [MessageHistoryIndexOperation] = []
self.indexTable!.removeMessage(MessageId(peerId: peerId, namespace: namespace, id: id), operations: &operations)
}
private func expect(items: [Item]) {
private func expect(_ items: [Item]) {
let actualList = self.indexTable!.debugList(peerId, namespace: namespace)
let actualItems = actualList.map { return Item($0) }
if items != actualItems {

View File

@ -70,11 +70,11 @@ private class TestEmbeddedMedia: Media, CustomStringConvertible {
self.data = decoder.decodeStringForKey("s")
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
encoder.encodeString(self.data, forKey: "s")
}
func isEqual(other: Media) -> Bool {
func isEqual(_ other: Media) -> Bool {
if let other = other as? TestEmbeddedMedia {
return self.data == other.data
}
@ -101,13 +101,13 @@ private class TestExternalMedia: Media {
self.data = decoder.decodeStringForKey("s")
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
encoder.encodeInt32(self.id!.namespace, forKey: "i.n")
encoder.encodeInt64(self.id!.id, forKey: "i.i")
encoder.encodeString(self.data, forKey: "s")
}
func isEqual(other: Media) -> Bool {
func isEqual(_ other: Media) -> Bool {
if let other = other as? TestExternalMedia {
return self.id == other.id && self.data == other.data
}
@ -133,13 +133,13 @@ private class TestPeer: Peer {
self.data = decoder.decodeStringForKey("s")
}
func encode(encoder: Encoder) {
func encode(_ encoder: Encoder) {
encoder.encodeInt32(self.id.namespace, forKey: "i.n")
encoder.encodeInt32(self.id.id, forKey: "i.i")
encoder.encodeString(self.data, forKey: "s")
}
func isEqual(other: Peer) -> Bool {
func isEqual(_ other: Peer) -> Bool {
if let other = other as? TestPeer {
return self.id == other.id && self.data == other.data
}
@ -218,7 +218,7 @@ class MessageHistoryTableTests: XCTestCase {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
path = NSTemporaryDirectory().stringByAppendingString("\(randomId)")
path = NSTemporaryDirectory() + "\(randomId)"
self.valueBox = SqliteValueBox(basePath: path!)
let seedConfiguration = SeedConfiguration(initializeChatListWithHoles: [], initializeMessageNamespacesWithHoles: [], existingMessageTags: [.First, .Second])
@ -248,46 +248,46 @@ class MessageHistoryTableTests: XCTestCase {
self.historyMetadataTable = nil
self.valueBox = nil
let _ = try? NSFileManager.defaultManager().removeItemAtPath(path!)
let _ = try? FileManager.default().removeItem(atPath: path!)
self.path = nil
}
private func addMessage(id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags = [], _ tags: MessageTags = []) {
private func addMessage(_ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags = [], _ tags: MessageTags = []) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.addMessages([StoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: flags, tags: tags, forwardInfo: nil, authorId: authorPeerId, text: text, attributes: [], media: media)], location: .Random, operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func updateMessage(previousId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags, _ tags: MessageTags) {
private func updateMessage(_ previousId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags, _ tags: MessageTags) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.updateMessage(MessageId(peerId: peerId, namespace: namespace, id: previousId), message: StoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: flags, tags: tags, forwardInfo: nil, authorId: authorPeerId, text: text, attributes: [], media: media), operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func addHole(id: Int32) {
private func addHole(_ id: Int32) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.addHoles([MessageId(peerId: peerId, namespace: namespace, id: id)], operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func removeMessages(ids: [Int32]) {
private func removeMessages(_ ids: [Int32]) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.removeMessages(ids.map({ MessageId(peerId: peerId, namespace: namespace, id: $0) }), operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func fillHole(id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32, String, [Media])], _ tagMask: MessageTags? = nil) {
private func fillHole(_ id: Int32, _ fillType: HoleFill, _ messages: [(Int32, Int32, String, [Media])], _ tagMask: MessageTags? = nil) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.fillHole(MessageId(peerId: peerId, namespace: namespace, id: id), fillType: fillType, tagMask: tagMask, messages: messages.map({ StoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: $0.0), timestamp: $0.1, flags: [], tags: [], forwardInfo: nil, authorId: authorPeerId, text: $0.2, attributes: [], media: $0.3) }), operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func expectEntries(entries: [Entry], tagMask: MessageTags? = nil) {
private func expectEntries(_ entries: [Entry], tagMask: MessageTags? = nil) {
var stableIds = Set<UInt32>()
let list: [RenderedMessageHistoryEntry]
@ -330,7 +330,7 @@ class MessageHistoryTableTests: XCTestCase {
}
}
private func expectUnsent(indices: [(Int32, Int32)]) {
private func expectUnsent(_ indices: [(Int32, Int32)]) {
let actualUnsent = self.unsentTable!.get().map({ ($0.id.id, $0.timestamp) })
var match = true
if actualUnsent.count == indices.count {
@ -348,14 +348,14 @@ class MessageHistoryTableTests: XCTestCase {
}
}
private func expectMedia(media: [MediaEntry]) {
private func expectMedia(_ media: [MediaEntry]) {
let actualMedia = self.mediaTable!.debugList().map({MediaEntry($0)})
if media != actualMedia {
XCTFail("Expected\n\(media)\nActual\n\(actualMedia)")
}
}
private func expectCleanupMedia(media: [Media]) {
private func expectCleanupMedia(_ media: [Media]) {
let actualMedia = self.mediaCleanupTable!.debugList()
var equal = true
if media.count != actualMedia.count {

View File

@ -82,7 +82,7 @@ class ReadStateTableTests: XCTestCase {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
path = NSTemporaryDirectory().stringByAppendingString("\(randomId)")
path = NSTemporaryDirectory() + "\(randomId)"
self.valueBox = SqliteValueBox(basePath: path!)
let seedConfiguration = SeedConfiguration(initializeChatListWithHoles: [], initializeMessageNamespacesWithHoles: [], existingMessageTags: [.First, .Second])
@ -110,39 +110,39 @@ class ReadStateTableTests: XCTestCase {
self.historyMetadataTable = nil
self.valueBox = nil
let _ = try? NSFileManager.defaultManager().removeItemAtPath(path!)
let _ = try? FileManager.default().removeItem(atPath: path!)
self.path = nil
}
private func addMessage(id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags = [], _ tags: MessageTags = []) {
private func addMessage(_ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags = [], _ tags: MessageTags = []) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.addMessages([StoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: flags, tags: tags, forwardInfo: nil, authorId: authorPeerId, text: text, attributes: [], media: media)], location: .Random, operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func updateMessage(previousId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags, _ tags: MessageTags) {
private func updateMessage(_ previousId: Int32, _ id: Int32, _ timestamp: Int32, _ text: String = "", _ media: [Media] = [], _ flags: StoreMessageFlags, _ tags: MessageTags) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.updateMessage(MessageId(peerId: peerId, namespace: namespace, id: previousId), message: StoreMessage(id: MessageId(peerId: peerId, namespace: namespace, id: id), timestamp: timestamp, flags: flags, tags: tags, forwardInfo: nil, authorId: authorPeerId, text: text, attributes: [], media: media), operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func addHole(id: Int32) {
private func addHole(_ id: Int32) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.addHoles([MessageId(peerId: peerId, namespace: namespace, id: id)], operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func removeMessages(ids: [Int32]) {
private func removeMessages(_ ids: [Int32]) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var unsentMessageOperations: [IntermediateMessageHistoryUnsentOperation] = []
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.removeMessages(ids.map({ MessageId(peerId: peerId, namespace: namespace, id: $0) }), operationsByPeerId: &operationsByPeerId, unsentMessageOperations: &unsentMessageOperations, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
}
private func expectApplyRead(messageId: Int32, _ expectInvalidate: Bool) {
private func expectApplyRead(_ messageId: Int32, _ expectInvalidate: Bool) {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.applyIncomingReadMaxId(MessageId(peerId: peerId, namespace: namespace, id: messageId), operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
@ -153,20 +153,20 @@ class ReadStateTableTests: XCTestCase {
}
}
private func expectReadState(maxReadId: Int32, _ maxKnownId: Int32, _ count: Int32) {
private func expectReadState(_ maxReadId: Int32, _ maxKnownId: Int32, _ count: Int32) {
if let state = self.readStateTable!.getCombinedState(peerId)?.states.first?.1 {
if state.maxReadId != maxReadId || state.maxKnownId != maxKnownId || state.count != count {
XCTFail("Expected\nmaxReadId: \(maxReadId), maxKnownId: \(maxKnownId), count: \(count)\nActual\nmaxReadId: \(state.maxReadId), maxKnownId: \(state.maxKnownId), count: \(state.count)")
if state.maxIncomingReadId != maxReadId || state.maxKnownId != maxKnownId || state.count != count {
XCTFail("Expected\nmaxIncomingReadId: \(maxReadId), maxKnownId: \(maxKnownId), count: \(count)\nActual\nmaxIncomingReadId: \(state.maxIncomingReadId), maxKnownId: \(state.maxKnownId), count: \(state.count)")
}
} else {
XCTFail("Expected\nmaxReadId: (maxReadId), maxKnownId: \(maxKnownId), count: \(count)\nActual\nnil")
XCTFail("Expected\nmaxReadId: \(maxReadId), maxKnownId: \(maxKnownId), count: \(count)\nActual\nnil")
}
}
func testResetState() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
expectReadState(100, 120, 130)
}
@ -174,7 +174,7 @@ class ReadStateTableTests: XCTestCase {
func testAddIncomingBeforeKnown() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.addMessage(99, 99, "", [], [.Incoming])
@ -184,7 +184,7 @@ class ReadStateTableTests: XCTestCase {
func testAddIncomingAfterKnown() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 120, count: 130)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.addMessage(130, 130, "", [], [.Incoming])
@ -194,19 +194,19 @@ class ReadStateTableTests: XCTestCase {
func testApplyReadThenAddIncoming() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.expectApplyRead(200, false)
self.addMessage(130, 130, "", [], [.Incoming])
expectReadState(200, 200, 0)
expectReadState(200, 100, 0)
}
func testApplyAddIncomingThenRead() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.addMessage(130, 130, "", [], [.Incoming])
@ -214,13 +214,13 @@ class ReadStateTableTests: XCTestCase {
self.expectApplyRead(200, false)
expectReadState(200, 200, 0)
expectReadState(200, 100, 0)
}
func testIgnoreOldRead() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.expectApplyRead(90, false)
@ -230,14 +230,14 @@ class ReadStateTableTests: XCTestCase {
func testInvalidateReadHole() {
var operationsByPeerId: [PeerId: [MessageHistoryOperation]] = [:]
var updatedPeerReadStateOperations: [PeerId: PeerReadStateSynchronizationOperation?] = [:]
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxReadId: 100, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.historyTable!.resetIncomingReadStates([peerId: [namespace: PeerReadState(maxIncomingReadId: 100, maxOutgoingReadId: 0, maxKnownId: 100, count: 0)]], operationsByPeerId: &operationsByPeerId, updatedPeerReadStateOperations: &updatedPeerReadStateOperations)
self.addMessage(200, 200)
self.addHole(1)
self.expectApplyRead(200, true)
expectReadState(200, 200, 0)
expectReadState(200, 100, 0)
}

@ -1 +1 @@
Subproject commit 1b1e295b293aceb3071c0f1a56ec26096aa87caf
Subproject commit 95e5898eb392626957d0cb25662c98c38c6b4677