package com.tqmall.search.commons.match;

import com.tqmall.search.commons.ac.AcNormalNode;

/**
 * Created by xing on 16/1/28.
 * 匹配到的结果, 位置为[), 左开右闭
 */
public class Hit<V> implements Comparable<Hit<V>> {
    /**
     * 匹配到的开始位置
     */
    private int start;
    /**
     * 匹配结果的结束位置, 即最后一个字符的下一个位置
     */
    private int end;

    private V value;

    public Hit(int start, int end, V value) {
        this.start = start;
        this.end = end;
        this.value = value;
    }

    public int getStart() {
        return start;
    }

    public int getEnd() {
        return end;
    }

    public int length() {
        return end - start;
    }

    public void changePosition(int start, int end) {
        this.start = start;
        this.end = end;
    }

    /**
     * 修改匹配结果的value
     */
    public void changeValue(V value) {
        this.value = value;
    }

    public V getValue() {
        return value;
    }

    public static <V> Hit<V> valueOf(int start, int end, V value) {
        return new Hit<>(start, end, value);
    }

    public static <V> Hit<V> valueOf(int endPos, AcNormalNode<V> acNode) {
        if (!acNode.accept()) {
            throw new IllegalArgumentException("acNode: " + acNode + " accept is false");
        }
        return new Hit<>(endPos - acNode.getSingleOutput().length(), endPos, acNode.getValue());
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(start).append(',').append(end);
        if (value != null) {
            sb.append(':').append(value);
        }
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Hit)) return false;

        Hit<?> hit = (Hit<?>) o;
        return start == hit.start && end == hit.end;
    }

    @Override
    public int hashCode() {
        int result = start;
        result = 31 * result + end;
        return result;
    }

    @Override
    public int compareTo(Hit<V> o) {
        int cmp = Integer.compare(start, o.start);
        if (cmp == 0) {
            cmp = Integer.compare(end, o.end);
        }
        return cmp;
    }

}

@@ -86,16 +86,40 @@
 lNode;%0A%0A
+import java.util.List;%0A%0A
 /**%0A * C
@@ -168,16 +168,155 @@
 ), %E5%B7%A6%E5%BC%80%E5%8F%B3%E9%97%AD%0A
+ * %E8%BE%93%E5%87%BA%E7%BB%93%E6%9E%9C%E5%8F%AA%E6%9C%89%E5%BC%80%E5%A7%8B, %E7%BB%93%E6%9D%9F%E4%BD%8D%E7%BD%AE, %E5%A6%82%E6%9E%9C%E9%9C%80%E8%A6%81%E5%8C%B9%E9%85%8D%E5%88%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2, %E9%80%9A%E8%BF%87%7B@link Hits%7D%E5%8F%AF%E4%BB%A5%E6%96%B9%E4%BE%BF%E6%95%B4%E5%88%B0%0A *%0A * @see Hits%0A * @see Hits#valueOf(char%5B%5D, List)%0A * @see Hits#valueOf(String, List)%0A
  */%0Apubl

add comment for Hit.java