001/*
002 * Copyright 2008-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2008-2020 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2008-2020 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.asn1;
037
038
039
040import java.io.IOException;
041import java.io.OutputStream;
042import java.nio.BufferOverflowException;
043import java.nio.ByteBuffer;
044
045import com.unboundid.util.ByteStringBuffer;
046import com.unboundid.util.Debug;
047import com.unboundid.util.ThreadSafety;
048import com.unboundid.util.ThreadSafetyLevel;
049
050
051
052/**
053 * This class provides an efficient mechanism for writing ASN.1 elements to
054 * output streams.
055 */
056@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
057public final class ASN1Writer
058{
059  /**
060   * The thread-local buffers that will be used for encoding the elements.
061   */
062  private static final ThreadLocal<ByteStringBuffer> buffers =
063       new ThreadLocal<>();
064
065
066
067  /**
068   * The maximum amount of memory that will be used for a thread-local buffer.
069   */
070  private static final int MAX_BUFFER_LENGTH = 524_288;
071
072
073
074  /**
075   * Prevent this class from being instantiated.
076   */
077  private ASN1Writer()
078  {
079    // No implementation is required.
080  }
081
082
083
084  /**
085   * Writes an encoded representation of the provided ASN.1 element to the
086   * given output stream.
087   *
088   * @param  element       The ASN.1 element to be written.
089   * @param  outputStream  The output stream to which the encoded representation
090   *                       of the element should be written.
091   *
092   * @throws  IOException  If a problem occurs while writing the element.
093   */
094  public static void writeElement(final ASN1Element element,
095                                  final OutputStream outputStream)
096         throws IOException
097  {
098    Debug.debugASN1Write(element);
099
100    ByteStringBuffer buffer = buffers.get();
101    if (buffer == null)
102    {
103      buffer = new ByteStringBuffer();
104      buffers.set(buffer);
105    }
106
107    element.encodeTo(buffer);
108
109    try
110    {
111      buffer.write(outputStream);
112    }
113    finally
114    {
115      if (buffer.capacity() > MAX_BUFFER_LENGTH)
116      {
117        buffer.setCapacity(MAX_BUFFER_LENGTH);
118      }
119      buffer.clear();
120    }
121  }
122
123
124
125  /**
126   * Appends an encoded representation of the provided ASN.1 element to the
127   * given byte buffer.  When this method completes, the position will be at the
128   * beginning of the written element, and the limit will be at the end.
129   *
130   * @param  element  The ASN.1 element to be written.
131   * @param  buffer   The buffer to which the element should be added.
132   *
133   * @throws  BufferOverflowException  If the provided buffer does not have
134   *                                   enough space between the position and
135   *                                   the limit to hold the encoded element.
136   */
137  public static void writeElement(final ASN1Element element,
138                                  final ByteBuffer buffer)
139         throws BufferOverflowException
140  {
141    Debug.debugASN1Write(element);
142
143    ByteStringBuffer b = buffers.get();
144    if (b == null)
145    {
146      b = new ByteStringBuffer();
147      buffers.set(b);
148    }
149
150    element.encodeTo(b);
151
152    try
153    {
154      if (buffer.remaining() < b.length())
155      {
156        throw new BufferOverflowException();
157      }
158
159      final int pos = buffer.position();
160      buffer.put(b.getBackingArray(), 0, b.length());
161      buffer.limit(buffer.position());
162      buffer.position(pos);
163    }
164    finally
165    {
166      if (b.capacity() > MAX_BUFFER_LENGTH)
167      {
168        b.setCapacity(MAX_BUFFER_LENGTH);
169      }
170      b.clear();
171    }
172  }
173}