Prechádzať zdrojové kódy

new: SimpleStreamer

Mariusz Sieroń 6 rokov pred
rodič
commit
1574688592

+ 53 - 0
assira/src/main/java/net/ranides/assira/lexer/SimpleStreamer.java

@@ -0,0 +1,53 @@
+package net.ranides.assira.lexer;
+
+import net.ranides.assira.functional.CharPredicate;
+
+public class SimpleStreamer {
+
+    private final char content[];
+
+    private int position;
+
+    public SimpleStreamer(String content) {
+        this.content = content.toCharArray();
+        this.position = 0;
+    }
+
+    public boolean end() {
+        return content.length == position;
+    }
+
+    public char peek() {
+        return content[position];
+    }
+
+    public String peek(CharPredicate pred) {
+        int begin = position;
+        int current = position;
+        while (content.length != current && pred.test(content[current])) {
+            current++;
+        }
+        return new String(content, begin, current - begin);
+    }
+
+    public void skip() {
+        position++;
+    }
+
+    public void skip(CharPredicate pred) {
+        while (!end() && pred.test(peek())) {
+            next();
+        }
+    }
+
+    public char next() {
+        return content[position++];
+    }
+
+    public String next(CharPredicate pred) {
+        int begin = position;
+        skip(pred);
+        return new String(content, begin, position - begin);
+    }
+
+}

+ 45 - 0
assira/src/test/java/net/ranides/assira/lexer/SimpleStreamerTest.java

@@ -0,0 +1,45 @@
+package net.ranides.assira.lexer;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class SimpleStreamerTest {
+
+
+    @Test
+    public void usage() {
+        SimpleStreamer streamer = new SimpleStreamer("hello world  text ");
+
+        assertEquals("hello", streamer.next(c -> c!=' '));
+        assertEquals(" ", streamer.next(c -> c==' '));
+        assertEquals("", streamer.next(c -> c==' '));
+        assertEquals("world", streamer.next(c -> c!=' '));
+        assertEquals("  ", streamer.next(c -> c==' '));
+
+        assertEquals('t', streamer.peek());
+        assertEquals("text", streamer.peek(c -> c!=' '));
+    }
+
+    @Test
+    public void peek() {
+        SimpleStreamer streamer = new SimpleStreamer("hello world!");
+
+        assertEquals("hello", streamer.peek(c -> c!=' '));
+        assertEquals("hello world", streamer.peek(c -> c!='!'));
+        assertEquals("hello world!", streamer.peek(c -> c!='?'));
+    }
+
+    @Test
+    public void next() {
+        SimpleStreamer streamer1 = new SimpleStreamer("hello world!");
+        SimpleStreamer streamer2 = new SimpleStreamer("hello world!");
+        SimpleStreamer streamer3 = new SimpleStreamer("hello world!");
+
+        assertEquals("hello", streamer1.next(c -> c!=' '));
+        assertEquals("hello world", streamer2.next(c -> c!='!'));
+        assertEquals("hello world!", streamer3.next(c -> c!='?'));
+
+    }
+
+}