package textbender.g.util; // Copyright 2001-2003, 2006, Michael Allan. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Textbender Software"), to deal in the Textbender Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Textbender Software, and to permit persons to whom the Textbender Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Textbender Software. THE TEXTBENDER SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE TEXTBENDER SOFTWARE OR THE USE OR OTHER DEALINGS IN THE TEXTBENDER SOFTWARE. /** Circular indexing for a fixed-length sequence. *

* Thread safe, except where marked. *

*/ public final class SequenceCircler // cf. votorla.g.OffestIndexing { /** Constructs a SequenceCircler. * * @param s size per {@linkplain #size() size}() */ public SequenceCircler( int s ) { size = s; } // ------------------------------------------------------------------------------------ /** Returns the index of the cursor. */ public int getCursor() { return cursor; } private int cursor = 0; // to start /** Sets the index of the cursor. *

* Thread-safe iff setters sync (and getters touch-sync) on SequenceCircler.this * for cross-thread visibility/ordering of writes. *

* * @param c new index of the cursor * * @throws ArrayIndexOutOfBoundsException if c < 0 or c >= size() */ public void setCursor( int c ) { if( c < 0 || c >= size ) throw new ArrayIndexOutOfBoundsException( c ); cursor = c; } /** Returns the circular (wrapped) index of an offset * from the {@linkplain #getCursor() cursor}. * * @param offset (positive or negative) from the cursor * @return index in sequence of cursor + offset, * wrapped as necessary around the ends of the sequence * * @throws ArrayIndexOutOfBoundsException if |offset| >= size(), * which would wrap past the cursor */ public int indexOf( int offset ) { // if( Math.abs(offset) > size ) throw new ArrayIndexOutOfBoundsException( offset ); if( Math.abs(offset) >= size ) throw new ArrayIndexOutOfBoundsException( offset ); int index = cursor + offset; if( index >= size ) index -= size; else if( index < 0 ) index += size; return index; } /** Returns the size of the sequence. */ public int size() { return size; } private final int size; }