Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 820262e99c621f3a20995d268efcd57eced7767f (plain) (blame)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*******************************************************************************
 * Copyright (c) 2010, 2018 SAP AG
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Lazar Kirchev, SAP AG - initial API and implementation 
 *******************************************************************************/

package org.eclipse.equinox.console.common;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * A helper class, which implements history.
 */
public class HistoryHolder {

    private static final int MAX = 100;
    private final byte[][] history;
    private int size;
    private int pos;

    public HistoryHolder() {
        history = new byte[MAX][];
    }

    public synchronized void reset() {
        size = 0;
        pos = 0;
        for (int i = 0; i < MAX; i++) {
            history[i] = null;
        }
    }

    public synchronized void add(byte[] data) {
        data = new String(data, StandardCharsets.US_ASCII).trim().getBytes(StandardCharsets.US_ASCII);
        if (data.length == 0) {
            pos = size;
            return;
        }
        for (int i = 0; i < size; i++) {
            if (Arrays.equals(history[i], data)) {
                System.arraycopy(history, i + 1, history, i, size - i - 1);
                history[size - 1] = data;
                pos = size;
                return;
            }
        }
        if (size >= MAX) {
            System.arraycopy(history, 1, history, 0, size - 1);
            size--;
        }
        history[size++] = data;
        pos = size;
    }

    public synchronized byte[] next() {
        if (pos >= size - 1) {
            return null;
        }
        return history[++pos];
    }

    public synchronized byte[] last() {
        if (size > 0) {
            pos = size - 1;
            return history[pos];
        } else {
            return null;
        }
    }

    public synchronized byte[] first() {
        if (size > 0) {
            pos = 0;
            return history[pos];
        } else {
            return null;
        }
    }

    public synchronized byte[] prev() {
        if (size == 0) {
            return null;
        }
        if (pos == 0) {
            return history[pos];
        } else {
            return history[--pos];
        }
    }
}

Back to the top