From: Robert Varga Date: Fri, 29 Jul 2022 09:59:50 +0000 (+0200) Subject: Reuse encoder X-Git-Tag: v4.0.0~1 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=commitdiff_plain;h=refs%2Fchanges%2F94%2F101894%2F1;hp=41ec700376a5129c69db75e92125f93b25b2fb97;p=netconf.git Reuse encoder This is a tiny improvement: reuse the encoder for initilization of all three byte arrays. Change-Id: Ic01e9fcf1667ca6f28e089dae291f9a7acfecd30 Signed-off-by: Robert Varga --- diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java index 2921a84796..6802507b2c 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java @@ -7,9 +7,9 @@ */ package org.opendaylight.netconf.nettyutil.handler; -import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; +import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import org.opendaylight.netconf.util.messages.FramingMechanism; @@ -20,27 +20,32 @@ import org.opendaylight.netconf.util.messages.FramingMechanism; * @author Thomas Pantelis */ final class MessageParts { - static final byte[] END_OF_MESSAGE = asciiBytes(FramingMechanism.EOM_STR); - static final byte[] START_OF_CHUNK = asciiBytes(FramingMechanism.CHUNK_START_STR); - static final byte[] END_OF_CHUNK = asciiBytes(FramingMechanism.CHUNK_END_STR); + static final byte[] END_OF_MESSAGE; + static final byte[] START_OF_CHUNK; + static final byte[] END_OF_CHUNK; - private MessageParts() { - // Hidden on purpose - } + static { + final var encoder = StandardCharsets.US_ASCII.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); - private static byte[] asciiBytes(final String str) { - final ByteBuffer buf; try { - buf = StandardCharsets.US_ASCII.newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(str)); + END_OF_MESSAGE = getBytes(encoder, FramingMechanism.EOM_STR); + START_OF_CHUNK = getBytes(encoder, FramingMechanism.CHUNK_START_STR); + END_OF_CHUNK = getBytes(encoder, FramingMechanism.CHUNK_END_STR); } catch (CharacterCodingException e) { throw new ExceptionInInitializerError(e); } + } + + private MessageParts() { + // Hidden on purpose + } - final byte[] ret = new byte[buf.remaining()]; - buf.get(ret); - return ret; + private static byte[] getBytes(final CharsetEncoder encoder, final String str) throws CharacterCodingException { + final var buf = encoder.encode(CharBuffer.wrap(str)); + final var bytes = new byte[buf.remaining()]; + buf.get(bytes); + return bytes; } }