001    // Copyright 2008 Waterken Inc. under the terms of the MIT X license
002    // found at http://www.opensource.org/licenses/mit-license.html
003    package org.waterken.trace;
004    
005    import java.io.Serializable;
006    
007    import org.joe_e.Struct;
008    import org.ref_send.log.Anchor;
009    import org.ref_send.log.Turn;
010    import org.ref_send.promise.Receiver;
011    
012    /**
013     * An event loop turn counter.
014     */
015    public class
016    TurnCounter extends Struct implements Serializable {
017        static private final long serialVersionUID = 1L;
018        
019        /**
020         * URI for the event loop
021         */
022        public final String loop;
023    
024        /**
025         * increment the turn counter
026         */
027        public final Receiver<?> flip;
028        
029        /**
030         * increment the anchor counter
031         */
032        public final Marker mark;
033        
034        private
035        TurnCounter(final String loop, final Receiver<?> flip, final Marker mark) {
036            this.loop = loop;
037            this.flip = flip;
038            this.mark = mark;
039        }
040        
041        /**
042         * Constructs an instance.
043         * @param loop  {@link #loop}
044         */
045        static public TurnCounter
046        make(final String loop) {
047            class State implements Serializable {
048                static private final long serialVersionUID = 1L;
049    
050                long turns = 1;     // id of current turn
051                long anchors = 1;   // id of next anchor
052            }
053            final State m = new State();
054            class Flip extends Struct implements Receiver<Object>, Serializable {
055                static private final long serialVersionUID = 1L;
056    
057                public void
058                apply(final Object ignored) {
059                    m.turns += 1;
060                    m.anchors = 1;
061                }
062            }
063            class Mark extends Struct implements Marker, Serializable {
064                static private final long serialVersionUID = 1L;
065    
066                public Anchor
067                apply() { return new Anchor(new Turn(loop, m.turns), m.anchors++); }
068            }
069            return new TurnCounter(loop, new Flip(), new Mark());
070        }
071    }