package textbender.g; // Copyright 2005, 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. import java.util.List; import textbender.g.hold.*; /** Utilities for instance lists. */ public class InstanceList { private InstanceList() {} /** Registers an instance, and spools it to be unregistered on disposal. * The instance is stored in place of the first null element in the list; * or, if there is no null element, an element is appended to the end of the list. * When unspooled, that element is set to null, effectively unregistering the instance. * * @param i instance to register * @param iList list in which to register instance * @param spool for internal holds. When unwound, this instance * releases its internal holds, and is thence disabled. * * @return index at which instance is registered in the list * * @throws AssertionError on attempt to double-register an instance */ public static int register( final I i, final List iList, final Spool spool ) { assert iList.indexOf(i) == -1 : "instances may not register twice in instance list"; final int iIndex; { int ii = iList.indexOf( null ); if( ii == -1 ) { ii = iList.size(); iList.add( null ); } iIndex = ii; } iList.set( iIndex, i ); spool.add( new Hold() { public void release() { assert iList.get(iIndex) == i; iList.set( iIndex, null ); } }); return iIndex; } }