001package org.biojava.utils;
002
003/**
004 *
005 *
006 * @author Matthew Pocock
007 */
008public class RepeatedCharSequence
009        implements CharSequence
010{
011  private int length;
012  private char character;
013  private StringBuffer sbuf;
014  private String string;
015
016  public RepeatedCharSequence(int length, char character)
017  {
018    this.length = length;
019    this.character = character;
020  }
021
022  public RepeatedCharSequence()
023  {
024    this(0, ' ');
025  }
026
027  public int getLength()
028  {
029    return length;
030  }
031
032  public void setLength(int length)
033  {
034    if(length < 0) {
035      throw new IllegalArgumentException("Length can't be negative: " + length);
036    }
037
038    // optimization
039    if(sbuf != null) {
040      if(length < this.length) {
041        sbuf.setLength(length);
042      } else {
043        for(int i = this.length; i < length; i++) {
044          sbuf.append(character);
045        }
046      }
047    }
048
049    if(this.length != length) {
050      string = null;
051    }
052
053    this.length = length;
054  }
055
056  public char getCharacter()
057  {
058    return character;
059  }
060
061  public void setCharacter(char character)
062  {
063    this.character = character;
064    flush();
065  }
066
067  public void flush()
068  {
069    sbuf = null;
070    string = null;
071  }
072
073  public int length()
074  {
075    return length;
076  }
077
078  public char charAt(int index)
079  {
080    if(index < 0 || index >= length) {
081      throw new IndexOutOfBoundsException(
082              "Attempted to read from index " + index + " of " + length);
083    }
084
085    return character;
086  }
087
088  public CharSequence subSequence(int start, int end)
089  {
090    if(
091            start < 0 ||
092            start >= length ||
093            end < start ||
094            end > length)
095    {
096      throw new IndexOutOfBoundsException(
097              "Illegal indexes: " + start + "," + end +
098              " of sequence length " + length);
099    }
100
101    return new RepeatedCharSequence(end - start, character);
102  }
103
104  public String toString()
105  {
106    if(string == null) {
107      if(sbuf == null) {
108        sbuf = new StringBuffer(length);
109        for(int i = 0; i < length; i++) {
110          sbuf.append(character);
111        }
112      }
113
114      string = sbuf.toString();
115    }
116
117    return string;
118  }
119}