001/*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005package org.anarres.qemu.exec;
006
007import java.util.List;
008import java.util.Map;
009import javax.annotation.CheckForNull;
010import javax.annotation.Nonnull;
011
012/**
013 *
014 * @author shevek
015 */
016public abstract class AbstractQEmuOption implements QEmuOption {
017
018    protected static void appendTo(@Nonnull StringBuilder buf, @Nonnull String key, @CheckForNull Object value) {
019        if (value == null)
020            return;
021        if (buf.length() > 0)
022            buf.append(",");
023        buf.append(key).append("=").append(value);
024    }
025
026    /** Allows use of ImmutableMap.of() patterns. */
027    protected static void appendTo(@Nonnull StringBuilder buf, @Nonnull Map<? extends String, ? extends Object> values) {
028        for (Map.Entry<? extends String, ? extends Object> e : values.entrySet()) {
029            if (buf.length() > 0)
030                buf.append(",");
031            buf.append(e.getKey());
032            Object value = e.getValue();
033            if (value != null)
034                buf.append('=').append(value);
035        }
036    }
037
038    @CheckForNull
039    protected static CharSequence join(@Nonnull String sep, @CheckForNull Iterable<?> values) {
040        if (values == null)
041            return null;
042        StringBuilder buf = new StringBuilder();
043        int i = 0;
044        for (Object value: values) {
045            if (i++ > 0)
046                buf.append(sep);
047            buf.append(value);
048        }
049        return buf;
050    }
051
052    protected static void add(@Nonnull List<? super String> line, @Nonnull Object... words) {
053        for (Object word : words)
054            line.add(word.toString());  // Deliberate NPE if word is null.
055    }
056}