forked from thunderbird/thunderbird-android
/
ImapCommandSplitter.java
67 lines (54 loc) · 2.4 KB
/
ImapCommandSplitter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.fsck.k9.mail.store.imap;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import com.fsck.k9.mail.store.imap.IdGrouper.ContiguousIdGroup;
import com.fsck.k9.mail.store.imap.IdGrouper.GroupedIds;
class ImapCommandSplitter {
static List<String> splitCommand(String prefix, String suffix, GroupedIds groupedIds, int lengthLimit) {
List<String> commands = new ArrayList<>();
Set<Long> workingIdSet = new TreeSet<>(groupedIds.ids);
List<ContiguousIdGroup> workingIdGroups = new ArrayList<>(groupedIds.idGroups);
int suffixLength = suffix.length();
int staticCommandLength = prefix.length() + suffixLength + 2;
while (!workingIdSet.isEmpty() || !workingIdGroups.isEmpty()) {
StringBuilder commandBuilder = new StringBuilder(prefix).append(' ');
int length = staticCommandLength;
while (length < lengthLimit) {
if (!workingIdSet.isEmpty()) {
Long id = workingIdSet.iterator().next();
String idString = Long.toString(id);
length += idString.length() + 1;
if (length >= lengthLimit) {
break;
}
commandBuilder.append(idString).append(',');
workingIdSet.remove(id);
} else if (!workingIdGroups.isEmpty()) {
ContiguousIdGroup idGroup = workingIdGroups.iterator().next();
String idGroupString = idGroup.toString();
length += idGroupString.length() + 1;
if (length >= lengthLimit) {
break;
}
commandBuilder.append(idGroupString).append(',');
workingIdGroups.remove(idGroup);
} else {
break;
}
}
if (suffixLength != 0) {
// Replace the last comma with a space
commandBuilder.setCharAt(commandBuilder.length() - 1, ' ');
commandBuilder.append(suffix);
} else {
// Remove last comma
commandBuilder.setLength(commandBuilder.length() - 1);
}
String command = commandBuilder.toString();
commands.add(command);
}
return commands;
}
}