001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package org.pgpainless.algorithm;
006
007import java.util.Map;
008import java.util.concurrent.ConcurrentHashMap;
009
010import org.bouncycastle.openpgp.PGPLiteralData;
011
012/**
013 * Enumeration of possible encoding formats of the content of the literal data packet.
014 *
015 * @see <a href="https://tools.ietf.org/html/rfc4880#section-5.9">RFC4880: Literal Data Packet</a>
016 */
017public enum StreamEncoding {
018
019    /**
020     * The Literal packet contains binary data.
021     */
022    BINARY(PGPLiteralData.BINARY),
023
024    /**
025     * The Literal packet contains text data, and thus may need line ends converted to local form, or other
026     * text-mode changes.
027     */
028    TEXT(PGPLiteralData.TEXT),
029
030    /**
031     * Indication that the implementation believes that the literal data contains UTF-8 text.
032     */
033    UTF8(PGPLiteralData.UTF8),
034
035    /**
036     * Early versions of PGP also defined a value of 'l' as a 'local' mode for machine-local conversions.
037     * RFC 1991 [RFC1991] incorrectly stated this local mode flag as '1' (ASCII numeral one).
038     * Both of these local modes are deprecated.
039     */
040    @Deprecated
041    LOCAL('l'),
042    ;
043
044    private final char code;
045
046    private static final Map<Character, StreamEncoding> MAP = new ConcurrentHashMap<>();
047    static {
048        for (StreamEncoding f : StreamEncoding.values()) {
049            MAP.put(f.code, f);
050        }
051        // RFC 1991 [RFC1991] incorrectly stated local mode flag as '1', see doc of LOCAL.
052        MAP.put('1', LOCAL);
053    }
054
055    StreamEncoding(char code) {
056        this.code = code;
057    }
058
059    /**
060     * Return the code identifier of the encoding.
061     *
062     * @return identifier
063     */
064    public char getCode() {
065        return code;
066    }
067
068    /**
069     * Return the {@link StreamEncoding} corresponding to the provided code identifier.
070     *
071     * @param code identifier
072     * @return encoding enum
073     */
074    public static StreamEncoding fromCode(int code) {
075        return MAP.get((char) code);
076    }
077}