-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageSplitter.swift
41 lines (31 loc) · 1021 Bytes
/
MessageSplitter.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// MessageSplitter.swift
// Ble
//
// Created by AndrewNadraliev on 28.11.2022.
// Copyright © 2022 Facebook. All rights reserved.
//
import Foundation
func splitMessage(data: Data, maxChunkLength: Int) -> [Data] {
if data.isEmpty {
return []
}
var result: [Data] = []
var index = 0
repeat {
let bottomBar = index * maxChunkLength
let upperBar = min(data.count, (index + 1) * maxChunkLength)
result.append(data.subdata(in: bottomBar..<upperBar))
index += 1
} while index * maxChunkLength < data.count
let lastChunk = result.last
if var lastChunk = lastChunk, lastChunk.count < maxChunkLength {
// there is enough space for terminal operator
lastChunk.append(contentsOf: [0])
result[result.count - 1] = lastChunk
} else {
// not enough space in the last chunk, create a new one
result.append(Data(repeating: 0, count: 1))
}
return result
}