hazelcast-master/hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/builtin/BigDecimalCodec.java
/*
 * Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hazelcast.client.impl.protocol.codec.builtin;

import com.hazelcast.client.impl.protocol.ClientMessage;

import java.math.BigDecimal;
import java.math.BigInteger;

import static com.hazelcast.client.impl.protocol.ClientMessage.NULL_FRAME;
import static com.hazelcast.client.impl.protocol.codec.builtin.CodecUtil.nextFrameIsNullEndFrame;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.INT_SIZE_IN_BYTES;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.decodeInt;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.encodeInt;

public final class BigDecimalCodec {

    private BigDecimalCodec() {
    }

    public static void encode(ClientMessage clientMessage, BigDecimal value) {
        byte[] body = value.unscaledValue().toByteArray();

        byte[] buffer = new byte[INT_SIZE_IN_BYTES + body.length + INT_SIZE_IN_BYTES];
        encodeInt(buffer, 0, body.length);
        System.arraycopy(body, 0, buffer, INT_SIZE_IN_BYTES, body.length);
        encodeInt(buffer, INT_SIZE_IN_BYTES + body.length, value.scale());

        clientMessage.add(new ClientMessage.Frame(buffer));
    }

    public static void encodeNullable(ClientMessage clientMessage, BigDecimal value) {
        if (value == null) {
            clientMessage.add(NULL_FRAME.copy());
        } else {
            encode(clientMessage, value);
        }
    }

    public static BigDecimal decode(ClientMessage.ForwardFrameIterator iterator) {
        byte[] buffer = iterator.next().content;

        int contentSize = decodeInt(buffer, 0);
        byte[] body = new byte[contentSize];
        System.arraycopy(buffer, INT_SIZE_IN_BYTES, body, 0, contentSize);
        int scale = decodeInt(buffer, INT_SIZE_IN_BYTES + contentSize);

        return new BigDecimal(new BigInteger(body), scale);
    }

    public static BigDecimal decodeNullable(ClientMessage.ForwardFrameIterator iterator) {
        return nextFrameIsNullEndFrame(iterator) ? null : decode(iterator);
    }
}
