001/* 002 * This file is part of the JDrupes non-blocking HTTP Codec 003 * Copyright (C) 2016, 2017 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Lesser General Public License as published 007 * by the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 013 * License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.httpcodec.util; 020 021import java.nio.ByteBuffer; 022 023/** 024 * Utilities for handling `ByteBuffer`s 025 */ 026public class ByteBufferUtils { 027 028 private ByteBufferUtils() { 029 } 030 031 /** 032 * Put as many bytes as possible from the src buffer into the destination 033 * buffer. 034 * 035 * @param dest 036 * the destination buffer 037 * @param src 038 * the source buffer 039 * @return {@code true} if {@code src.remaining() == 0} 040 */ 041 public static boolean putAsMuchAsPossible(ByteBuffer dest, ByteBuffer src) { 042 if (dest.remaining() >= src.remaining()) { 043 dest.put(src); 044 return true; 045 } 046 if (dest.remaining() > 0) { 047 int oldLimit = src.limit(); 048 src.limit(src.position() + dest.remaining()); 049 dest.put(src); 050 src.limit(oldLimit); 051 } 052 return false; 053 } 054 055 /** 056 * Put as many bytes as possible from the src buffer into the destination 057 * buffer but not more than specified by limit. 058 * 059 * @param dest 060 * the destination buffer 061 * @param src 062 * the source buffer 063 * @param limit 064 * the maximum number of bytes to transfer 065 * @return {@code true} if {@code src.remaining() == 0} 066 */ 067 public static boolean putAsMuchAsPossible(ByteBuffer dest, ByteBuffer src, 068 int limit) { 069 if (src.remaining() <= limit) { 070 return putAsMuchAsPossible(dest, src); 071 } 072 int oldLimit = src.limit(); 073 try { 074 src.limit(src.position() + limit); 075 return putAsMuchAsPossible(dest, src); 076 } finally { 077 src.limit(oldLimit); 078 } 079 } 080 081}