|
| 1 | +// |
| 2 | +// MessagePack for Java |
| 3 | +// |
| 4 | +// Copyright (C) 2009-2011 FURUHASHI Sadayuki |
| 5 | +// |
| 6 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +// you may not use this file except in compliance with the License. |
| 8 | +// You may obtain a copy of the License at |
| 9 | +// |
| 10 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +// |
| 12 | +// Unless required by applicable law or agreed to in writing, software |
| 13 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +// See the License for the specific language governing permissions and |
| 16 | +// limitations under the License. |
| 17 | +// |
| 18 | +package org.msgpack.template; |
| 19 | + |
| 20 | +import java.io.IOException; |
| 21 | +import java.util.HashSet; |
| 22 | +import java.util.Set; |
| 23 | + |
| 24 | +import org.msgpack.packer.Packer; |
| 25 | +import org.msgpack.unpacker.Unpacker; |
| 26 | +import org.msgpack.MessageTypeException; |
| 27 | + |
| 28 | +public class SetTemplate<E> extends AbstractTemplate<Set<E>> { |
| 29 | + private Template<E> elementTemplate; |
| 30 | + |
| 31 | + public SetTemplate(Template<E> elementTemplate) { |
| 32 | + this.elementTemplate = elementTemplate; |
| 33 | + } |
| 34 | + |
| 35 | + public void write(Packer pk, Set<E> target, boolean required) |
| 36 | + throws IOException { |
| 37 | + if (!(target instanceof Set)) { |
| 38 | + if (target == null) { |
| 39 | + if (required) { |
| 40 | + throw new MessageTypeException("Attempted to write null"); |
| 41 | + } |
| 42 | + pk.writeNil(); |
| 43 | + return; |
| 44 | + } |
| 45 | + throw new MessageTypeException("Target is not a List but " |
| 46 | + + target.getClass()); |
| 47 | + } |
| 48 | + pk.writeArrayBegin(target.size()); |
| 49 | + for (E e : target) { |
| 50 | + elementTemplate.write(pk, e); |
| 51 | + } |
| 52 | + pk.writeArrayEnd(); |
| 53 | + } |
| 54 | + |
| 55 | + public Set<E> read(Unpacker u, Set<E> to, boolean required) |
| 56 | + throws IOException { |
| 57 | + if (!required && u.trySkipNil()) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + int n = u.readArrayBegin(); |
| 61 | + if (to == null) { |
| 62 | + to = new HashSet<E>(n); |
| 63 | + } else { |
| 64 | + to.clear(); |
| 65 | + } |
| 66 | + for (int i = 0; i < n; i++) { |
| 67 | + E e = elementTemplate.read(u, null); |
| 68 | + to.add(e); |
| 69 | + } |
| 70 | + u.readArrayEnd(); |
| 71 | + return to; |
| 72 | + } |
| 73 | +} |
0 commit comments