Fix bugs, Add more document/bag methods

This commit is contained in:
MrLetsplay 2024-06-05 22:06:14 +02:00
parent 0a603a41df
commit 6e7cc64b43
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg
3 changed files with 32 additions and 8 deletions

View File

@ -41,6 +41,11 @@ public class ArrayCharBag implements CharBag {
return chars.get(index);
}
@Override
public void clear() {
chars.clear();
}
@Override
public int size() {
return chars.size();

View File

@ -26,6 +26,11 @@ public interface CharBag {
*/
public Char get(int index);
/**
* Removes all chars from this bag
*/
public void clear();
/**
* Returns the number of chars in this bag
* @return The number of chars

View File

@ -38,25 +38,24 @@ public class SharedDocument implements MessageListener {
}
public SharedDocument(RemoteConnection connection, String path, String initialContents) {
this(connection, path, initialContents.getBytes(StandardCharsets.UTF_8));
this(connection, path, initialContents == null ? null : initialContents.getBytes(StandardCharsets.UTF_8));
}
public SharedDocument(RemoteConnection connection, String path) {
this(connection, path, null);
this(connection, path, (byte[]) null);
}
private Change[] insert(int index, String str, int site) {
private Change[] insert(int index, byte[] bytes, int site) throws IllegalArgumentException {
if(index < 0 || index >= charBag.size() - 1) throw new IllegalArgumentException("Index out of bounds");
Char charBefore = charBag.get(index);
Char charAfter = charBag.get(index +1);
byte[] chars = str.getBytes(StandardCharsets.UTF_8);
Change[] changes = new Change[chars.length];
for(int i = 0; i < chars.length; i++) {
Change[] changes = new Change[bytes.length];
for(int i = 0; i < bytes.length; i++) {
Identifier[] newPos = Util.generatePositionBetween(charBefore.position(), charAfter.position(), site);
lamport++;
Char ch = new Char(newPos, lamport, chars[i]);
Char ch = new Char(newPos, lamport, bytes[i]);
charBag.add(ch);
changes[i] = new Change(path, ChangeType.ADD, ch);
charBefore = ch;
@ -65,6 +64,21 @@ public class SharedDocument implements MessageListener {
return changes;
}
private Change[] insert(int index, String str, int site) throws IllegalArgumentException {
return insert(index, str.getBytes(StandardCharsets.UTF_8), site);
}
/**
* Removes all characters from this document.<br>
* <br>
* <b>Note:</b> This is not the same as calling {@link #getCharBag() getCharBag()}.{@link CharBag#clear() clear()}, because documents rely on the {@link Char#START_OF_DOCUMENT} and {@link Char#END_OF_DOCUMENT} characters to exist in the document.
*/
public void clear() {
charBag.clear();
charBag.add(Char.START_OF_DOCUMENT);
charBag.add(Char.END_OF_DOCUMENT);
}
/**
* Inserts characters into the document at the specified index
* @param index The index to insert at