| 1 | /* |
| 2 | * This file is part of JON. |
| 3 | * |
| 4 | * JON is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Lesser General Public License as published by |
| 6 | * the Free Software Foundation; either version 3 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * JON is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Lesser General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Lesser General Public License |
| 15 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | * |
| 17 | * Copyright 2007 Michael Doberenz |
| 18 | */ |
| 19 | package org.fuwjax.jon; |
| 20 | |
| 21 | import java.io.IOException; |
| 22 | import java.util.IdentityHashMap; |
| 23 | import java.util.Map; |
| 24 | |
| 25 | /** |
| 26 | * A basic implementation of {@link CachedAppendable} that is backed by an |
| 27 | * {@link IdentityHashMap}. |
| 28 | * @author michaeldoberenz |
| 29 | */ |
| 30 | public class DefaultCachedAppender implements CachedAppendable{ |
| 31 | private Appendable appender; |
| 32 | private Map<Object, String> map; |
| 33 | |
| 34 | /** |
| 35 | * Creates a new instance backed by an internal buffer. |
| 36 | */ |
| 37 | public DefaultCachedAppender(){ |
| 38 | this(new StringBuilder()); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * creates a new writer backed by the specified appender. |
| 43 | * @param appender the destination of this instance's write methods |
| 44 | */ |
| 45 | public DefaultCachedAppender(final Appendable appender){ |
| 46 | this.appender = appender; |
| 47 | map = new IdentityHashMap<Object, String>(); |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public String toString(){ |
| 52 | return appender.toString(); |
| 53 | } |
| 54 | |
| 55 | public String store(final Object object) throws ReferenceExistsException{ |
| 56 | final String ret = Integer.toString(map.size()); |
| 57 | final String prev = map.put(object, ret); |
| 58 | if(prev != null){ |
| 59 | map.put(object, prev); |
| 60 | throw new ReferenceExistsException(prev, object); |
| 61 | } |
| 62 | return ret; |
| 63 | } |
| 64 | |
| 65 | public void write(final char token) throws SerialFormatException{ |
| 66 | try{ |
| 67 | appender.append(token); |
| 68 | }catch(IOException e){ |
| 69 | throw SerialFormatException.Messages.OutputError.exception(e); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | public void write(final CharSequence seq) throws SerialFormatException{ |
| 74 | try{ |
| 75 | appender.append(seq); |
| 76 | }catch(IOException e){ |
| 77 | throw SerialFormatException.Messages.OutputError.exception(e); |
| 78 | } |
| 79 | } |
| 80 | } |