| 1 |
/* |
| 2 |
* JBoss, Home of Professional Open Source. |
| 3 |
* |
| 4 |
* Copyright 2012 Red Hat, Inc. |
| 5 |
* |
| 6 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
* you may not use this file except in compliance with the License. |
| 8 |
* You may obtain a copy of the License at |
| 9 |
* |
| 10 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
* |
| 12 |
* Unless required by applicable law or agreed to in writing, software |
| 13 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
* See the License for the specific language governing permissions and |
| 16 |
* limitations under the License. |
| 17 |
*/ |
| 18 |
package org.jboss.classfilewriter.util; |
| 19 |
|
| 20 |
import java.io.ByteArrayOutputStream; |
| 21 |
import java.io.DataOutputStream; |
| 22 |
import java.io.IOException; |
| 23 |
import java.util.ArrayList; |
| 24 |
import java.util.List; |
| 25 |
|
| 26 |
/** |
| 27 |
* DataOutputStream sub class that allows for the lazy writing of length values. |
| 28 |
* <p/> |
| 29 |
* These length values are inserted into the bytes when then final bytes are read. |
| 30 |
* @author Stuart Douglas |
| 31 |
*/ |
| 32 |
public class ByteArrayDataOutputStream extends DataOutputStream { |
| 33 |
|
| 34 |
private final ByteArrayOutputStream bytes; |
| 35 |
private final List<LazySizeImpl> sizes = new ArrayList<LazySizeImpl>(); |
| 36 |
|
| 37 |
public ByteArrayDataOutputStream(ByteArrayOutputStream bytes) { |
| 38 |
super(bytes); |
| 39 |
this.bytes = bytes; |
| 40 |
} |
| 41 |
|
| 42 |
public ByteArrayDataOutputStream() { |
| 43 |
this(new ByteArrayOutputStream()); |
| 44 |
} |
| 45 |
|
| 46 |
public LazySize writeSize() throws IOException { |
| 47 |
LazySizeImpl sv = new LazySizeImpl(this.written); |
| 48 |
sizes.add(sv); |
| 49 |
writeInt(0); |
| 50 |
return sv; |
| 51 |
} |
| 52 |
|
| 53 |
public byte[] getBytes() { |
| 54 |
byte[] data = bytes.toByteArray(); |
| 55 |
for (final LazySizeImpl i : sizes) { |
| 56 |
overwriteInt(data, i.position, i.value); |
| 57 |
} |
| 58 |
return data; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* overwrites a 32 bit value in the already written bytecode data |
| 63 |
*/ |
| 64 |
private void overwriteInt(byte[] bytecode, int offset, int value) { |
| 65 |
bytecode[offset] = (byte) (value >> 24); |
| 66 |
bytecode[offset + 1] = (byte) (value >> 16); |
| 67 |
bytecode[offset + 2] = (byte) (value >> 8); |
| 68 |
bytecode[offset + 3] = (byte) (value); |
| 69 |
} |
| 70 |
|
| 71 |
private class LazySizeImpl implements LazySize { |
| 72 |
private final int position; |
| 73 |
private int value; |
| 74 |
|
| 75 |
public LazySizeImpl(int position) { |
| 76 |
this.position = position; |
| 77 |
} |
| 78 |
|
| 79 |
@Override |
| 80 |
public void markEnd() { |
| 81 |
value = written - position - 4; |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
} |