public void write_compressed ( final OtpErlangObject o , final int level ) { @ SuppressWarnings ( "resource" ) final OtpOutputStream oos = new OtpOutputStream ( o ) ; /* * similar to erts_term_to_binary() in external.c: We don't want to * compress if compression actually increases the size. Since * compression uses 5 extra bytes (COMPRESSED tag + size), don't * compress if the original term is smaller. */ if ( oos . size ( ) < 5 ) { // fast path for small terms try { oos . writeToAndFlush ( this ) ; // if the term is written as a compressed term, the output // stream is closed, so we do this here, too close ( ) ; } catch ( final IOException e ) { throw new java . lang . IllegalArgumentException ( "Intermediate stream failed for Erlang object " + o ) ; } } else { final int startCount = super . count ; // we need destCount bytes for an uncompressed term // -> if compression uses more, use the uncompressed term! final int destCount = startCount + oos . size ( ) ; fixedSize = destCount ; final Deflater def = new Deflater ( level ) ; final java . util . zip . DeflaterOutputStream dos = new java . util . zip . DeflaterOutputStream ( this , def ) ; try { write1 ( OtpExternal . compressedTag ) ; write4BE ( oos . size ( ) ) ; oos . writeTo ( dos ) ; dos . close ( ) ; // note: closes this, too! } catch ( final IllegalArgumentException e ) { /* * Discard further un-compressed data (if not called, there may * be memory leaks). * * After calling java.util.zip.Deflater.end(), the deflater * should not be used anymore, not even the close() method of * dos. Calling dos.close() before def.end() is prevented since * an unfinished DeflaterOutputStream will try to deflate its * unprocessed data to the (fixed) byte array which is prevented * by ensureCapacity() and would also unnecessarily process * further data that is discarded anyway. * * Since we are re-using the byte array of this object below, we * must not call close() in e.g. a finally block either (with or * without a call to def.end()). */ def . end ( ) ; // could not make the value smaller than originally // -> reset to starting count, write uncompressed super . count = startCount ; try { oos . writeTo ( this ) ; // if the term is written as a compressed term, the output // stream is closed, so we do this here, too close ( ) ; } catch ( final IOException e2 ) { throw new java . lang . IllegalArgumentException ( "Intermediate stream failed for Erlang object " + o ) ; } } catch ( final IOException e ) { throw new java . lang . IllegalArgumentException ( "Intermediate stream failed for Erlang object " + o ) ; } finally { fixedSize = Integer . MAX_VALUE ; } } }
Write an arbitrary Erlang term to the stream in compressed format .