From http://www.jwz.org/xscreensaver/xscreensaver-5.34.tar.gz
[xscreensaver] / android / project / xscreensaver / src / org / jwz / xscreensaver / BufferFactory.java
1 package org.jwz.xscreensaver;
2
3 import java.nio.ByteBuffer;
4 import java.nio.ByteOrder;
5 import java.nio.FloatBuffer;
6 import java.nio.ShortBuffer;
7
8 /**
9  * A utility class to create buffers.
10  *
11  * All public methods are static. The Singleton pattern was avoided to avoid concerns about
12  * threading and the Android life cycle. If needed, It can be implemented later given some research.
13  */
14 public class BufferFactory {
15     // This class cannot and should not be instantiated
16     private BufferFactory() {}
17
18     // We use Buffer.allocateDirect() to get memory outside of
19     // the normal, garbage collected heap. I think this is done
20     // because the buffer is subject to native I/O.
21     // See http://download.oracle.com/javase/1.4.2/docs/api/java/nio/ByteBuffer.html#direct
22
23     /**
24      * Creates a buffer of floats using memory outside the normal, garbage collected heap
25      *
26      * @param capacity          The number of primitives to create in the buffer.
27      */
28     public static FloatBuffer createFloatBuffer(int capacity) {
29         // 4 is the number of bytes in a float
30         ByteBuffer vbb = ByteBuffer.allocateDirect(capacity * 4);
31         vbb.order(ByteOrder.nativeOrder());
32         return vbb.asFloatBuffer();
33     }
34
35     /**
36      * Creates a buffer of shorts using memory outside the normal, garbage collected heap
37      *
38      * @param capacity          The number of primitives to create in the buffer.
39      */
40     public static ShortBuffer createShortBuffer(int capacity) {
41         // 2 is the number of bytes in a short
42         ByteBuffer vbb = ByteBuffer.allocateDirect(capacity * 2);
43         vbb.order(ByteOrder.nativeOrder());
44         return vbb.asShortBuffer();
45     }
46 }