All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hedera.hapi.node.base.codec.AccountIDProtoCodec Maven / Gradle / Ivy

The newest version!
package com.hedera.hapi.node.base.codec;

import com.hedera.pbj.runtime.*;
import com.hedera.pbj.runtime.io.*;
import com.hedera.pbj.runtime.io.buffer.*;
import com.hedera.pbj.runtime.io.stream.EOFException;
import java.io.IOException;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
import edu.umd.cs.findbugs.annotations.NonNull;

import com.hedera.hapi.node.base.AccountID;

import com.hedera.hapi.node.base.*;
import com.hedera.hapi.node.base.schema.*;
import com.hedera.pbj.runtime.*;
import com.hedera.pbj.runtime.io.buffer.*;

import static com.hedera.hapi.node.base.schema.AccountIDSchema.*;
import static com.hedera.pbj.runtime.ProtoWriterTools.*;
import static com.hedera.pbj.runtime.ProtoParserTools.*;
import static com.hedera.pbj.runtime.ProtoConstants.*;

/**
 * Protobuf Codec for AccountID model object. Generated based on protobuf schema.
 */
public final class AccountIDProtoCodec implements Codec {
    
    /** Constant for an unset oneof for account */
    public static final OneOf ACCOUNT_UNSET = new OneOf<>(AccountID.AccountOneOfType.UNSET,null);

        /**
     * Parses a AccountID object from ProtoBuf bytes in a {@link ReadableSequentialData}. Throws if in strict mode ONLY.
     *
     * @param input The data input to parse data from, it is assumed to be in a state ready to read with position at start
     *              of data to read and limit set at the end of data to read. The data inputs limit will be changed by this
     *              method. If there are no bytes remaining in the data input,
     *              then the method also returns immediately.
     * @param strictMode when {@code true}, the parser errors out on unknown fields; otherwise they'll be simply skipped.
     * @param maxDepth a ParseException will be thrown if the depth of nested messages exceeds the maxDepth value.
     * @return Parsed AccountID model object or null if data input was null or empty
     * @throws ParseException If parsing fails
     */
    public @NonNull AccountID parse(
            @NonNull final ReadableSequentialData input,
            final boolean strictMode,
            final int maxDepth) throws ParseException {
        if (maxDepth < 0) {
            throw new ParseException("Reached maximum allowed depth of nested messages");
        }
        try {
            // -- TEMP STATE FIELDS --------------------------------------
                long temp_shardNum = 0;
        long temp_realmNum = 0;
        OneOf temp_account = ACCOUNT_UNSET;
    
                        // -- PARSE LOOP ---------------------------------------------
                // Continue to parse bytes out of the input stream until we get to the end.
                while (input.hasRemaining()) {
                    // Note: ReadableStreamingData.hasRemaining() won't flip to false
                    // until the end of stream is actually hit with a read operation.
                    // So we catch this exception here and **only** here, because an EOFException
                    // anywhere else suggests that we're processing malformed data and so
                    // we must re-throw the exception then.
                    final int tag;
                    try {
                        // Read the "tag" byte which gives us the field number for the next field to read
                        // and the wire type (way it is encoded on the wire).
                        tag = input.readVarInt(false);
                    } catch (EOFException e) {
                        // There's no more fields. Stop the parsing loop.
                        break;
                    }
        
                    // The field is the top 5 bits of the byte. Read this off
                    final int field = tag >>> TAG_FIELD_OFFSET;
        
                    // Ask the Schema to inform us what field this represents.
                    final var f = getField(field);
        
                    // Given the wire type and the field type, parse the field
                    switch (tag) {
                        case 8 /* type=0 [INT64] field=1 [shardNum] */ -> {
                            final var value = readInt64(input);
                            temp_shardNum = value;
                        }
                        case 16 /* type=0 [INT64] field=2 [realmNum] */ -> {
                            final var value = readInt64(input);
                            temp_realmNum = value;
                        }
                        case 24 /* type=0 [INT64] field=3 [accountNum] */ -> {
                            final var value = readInt64(input);
                            temp_account =  new OneOf<>(AccountID.AccountOneOfType.ACCOUNT_NUM, value);
                        }
                        case 34 /* type=2 [BYTES] field=4 [alias] */ -> {
                            final var value = readBytes(input, 2097152);
                            temp_account =  new OneOf<>(AccountID.AccountOneOfType.ALIAS, value);
                        }
        
                        default -> {
                            // The wire type is the bottom 3 bits of the byte. Read that off
                            final int wireType = tag & TAG_WIRE_TYPE_MASK;
                            // handle error cases here, so we do not do if statements in normal loop
                            // Validate the field number is valid (must be > 0)
                            if (field == 0) {
                                throw new IOException("Bad protobuf encoding. We read a field value of "
                                    + field);
                            }
                            // Validate the wire type is valid (must be >=0 && <= 5).
                            // Otherwise we cannot parse this.
                            // Note: it is always >= 0 at this point (see code above where it is defined).
                            if (wireType > 5) {
                                throw new IOException("Cannot understand wire_type of " + wireType);
                            }
                            // It may be that the parser subclass doesn't know about this field
                            if (f == null) {
                                if (strictMode) {
                                    // Since we are parsing is strict mode, this is an exceptional condition.
                                    throw new UnknownFieldException(field);
                                } else {
                                    // We just need to read off the bytes for this field to skip it
                                    // and move on to the next one.
                                    skipField(input, ProtoConstants.get(wireType), 2097152);
                                }
                            } else {
                                throw new IOException("Bad tag [" + tag + "], field [" + field
                                        + "] wireType [" + wireType + "]");
                            }
                        }
                    }
                }
    
            return new AccountID(temp_shardNum, temp_realmNum, temp_account);
        } catch (final Exception anyException) {
            if (anyException instanceof ParseException parseException) {
                throw parseException;
            }
            throw new ParseException(anyException);
        }
    }

        /**
     * Write out a AccountID model to output stream in protobuf format.
     *
     * @param data The input model data to write
     * @param out The output stream to write to
     * @throws IOException If there is a problem writing
     */
    public void write(@NonNull AccountID data, @NonNull final WritableSequentialData out) throws IOException {
            // [1] - shardNum
        writeLong(out, SHARD_NUM, data.shardNum(), true);
        // [2] - realmNum
        writeLong(out, REALM_NUM, data.realmNum(), true);
        // [3] - accountNum
        if (data.account().kind() == AccountID.AccountOneOfType.ACCOUNT_NUM)
        writeLong(out, ACCOUNT_NUM, data.account().as(), true);
        // [4] - alias
        if (data.account().kind() == AccountID.AccountOneOfType.ALIAS)
        writeBytes(out, ALIAS, data.account().as(), true);
    
    }

        /**
     * Reads from this data input the length of the data within the input. The implementation may
     * read all the data, or just some special serialized data, as needed to find out the length of
     * the data.
     *
     * @param input The input to use
     * @return The length of the data item in the input
     * @throws ParseException If parsing fails
     */
    public int measure(@NonNull final ReadableSequentialData input) throws ParseException {
        final var start = input.position();
        parse(input);
        final var end = input.position();
        return (int)(end - start);
    }

        /**
     * Compute number of bytes that would be written when calling {@code write()} method.
     *
     * @param data The input model data to measure write bytes for
     * @return The length in bytes that would be written
     */
    public int measureRecord(AccountID data) {
        int size = 0;
            // [1] - shardNum
        size += sizeOfLong(SHARD_NUM, data.shardNum(), true);
        // [2] - realmNum
        size += sizeOfLong(REALM_NUM, data.realmNum(), true);
        // [3] - accountNum
        if (data.account().kind() == AccountID.AccountOneOfType.ACCOUNT_NUM)
        size += sizeOfLong(ACCOUNT_NUM, data.account().as(), true);
        // [4] - alias
        if (data.account().kind() == AccountID.AccountOneOfType.ALIAS)
        size += sizeOfBytes(ALIAS, data.account().as(), true);
    
        return size;
    }

        /**
     * Compares the given item with the bytes in the input, and returns false if it determines that
     * the bytes in the input could not be equal to the given item. Sometimes we need to compare an
     * item in memory with serialized bytes and don't want to incur the cost of deserializing the
     * entire object, when we could have determined the bytes do not represent the same object very
     * cheaply and quickly.
     *
     * @param item The item to compare. Cannot be null.
     * @param input The input with the bytes to compare
     * @return true if the bytes represent the item, false otherwise.
     * @throws ParseException If parsing fails
     */
    public boolean fastEquals(@NonNull AccountID item, @NonNull final ReadableSequentialData input) throws ParseException {
        return item.equals(parse(input));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy