]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.fastlz/src/org/simantics/fastlz/FastLZ.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.fastlz / src / org / simantics / fastlz / FastLZ.java
diff --git a/bundles/org.simantics.fastlz/src/org/simantics/fastlz/FastLZ.java b/bundles/org.simantics.fastlz/src/org/simantics/fastlz/FastLZ.java
new file mode 100644 (file)
index 0000000..1bd02f8
--- /dev/null
@@ -0,0 +1,315 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.fastlz;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.io.UnsupportedEncodingException;\r
+import java.net.URL;\r
+import java.net.URLDecoder;\r
+import java.nio.ByteBuffer;\r
+\r
+import org.simantics.compressions.impl.Buffers;\r
+import org.simantics.fastlz.impl.FastLZConfig;\r
+import org.simantics.fastlz.impl.FastLZInputStream;\r
+import org.simantics.fastlz.impl.FastLZOutputStream;\r
+import org.simantics.fastlz.impl.OS;\r
+import org.simantics.fastlz.java.FastLZJavaInputStream;\r
+import org.simantics.fastlz.java.FastLZJavaOutputStream;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+@SuppressWarnings("resource")\r
+public class FastLZ {\r
+\r
+    private static boolean nativeInitialized = false;\r
+\r
+    public static boolean isNativeInitialized() {\r
+        return nativeInitialized;\r
+    }\r
+\r
+    private static boolean isNativeDisabled() {\r
+        return "false".equalsIgnoreCase(System.getProperty("fastlz.native", "true"));\r
+    }\r
+\r
+    public synchronized static void initialize(File path) {\r
+        if (nativeInitialized || isNativeDisabled())\r
+            return;\r
+\r
+//        System.out.println("INITIALIZE FASTLZ: " + path);\r
+\r
+        String osName = System.getProperty("os.name");\r
+        String osArch = System.getProperty("os.arch");\r
+        String lib = "fastlz";\r
+\r
+        try {\r
+            if (path == null) {\r
+                lib += OS.formOsArchSuffix();\r
+                System.loadLibrary(lib);\r
+            } else {\r
+                if (path.isDirectory()) {\r
+                    lib = System.mapLibraryName(lib + OS.formOsArchSuffix());\r
+                    lib = new File(path, lib).toString();\r
+                } else if (path.isFile()) {\r
+                    lib = path.toString();\r
+                } else {\r
+                    throw new IllegalArgumentException("Invalid path for FastLZ library: " + path);\r
+                }\r
+                try {\r
+                    System.load(lib);\r
+                } catch (UnsatisfiedLinkError e) {\r
+                    String fallback = "fastlz";\r
+                    fallback += OS.formOsArchSuffix();\r
+                    System.loadLibrary(fallback);\r
+                }\r
+            }\r
+            nativeInitialized = true;\r
+        } catch (UnsatisfiedLinkError e) {\r
+            System.err.println("Couldn't load library '" + lib + "' for os '" + osName + "' and architecture '" + osArch + "'");\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+    static {\r
+        if (!isNativeDisabled() && FastLZConfig.attemptStaticInitialization) {\r
+            String osName = System.getProperty("os.name");\r
+            String osArch = System.getProperty("os.arch");\r
+            String libName = OS.resolveLibName();\r
+            URL libURL = FastLZ.class.getResource("/" + libName);\r
+//            System.out.println("FastLZ libURL: " + libURL);\r
+//            System.out.println(".: " + FastLZ.class.getResource("."));\r
+//            System.out.println("..: " + FastLZ.class.getResource("../../../" + resolveLibName()));\r
+//            System.out.println("libname: " + FastLZ.class.getResource(resolveLibName()));\r
+//            System.out.println("/libname: " + FastLZ.class.getResource("/" + resolveLibName()));\r
+//            System.out.println("libname stream: " + FastLZ.class.getResourceAsStream(resolveLibName()));\r
+//            System.out.println("/libname stream: " + FastLZ.class.getResourceAsStream("/" + resolveLibName()));\r
+            if (libURL != null) {\r
+                if ("file".equals(libURL.getProtocol())) {\r
+                    try {\r
+                        File path = new File(URLDecoder.decode(libURL.getPath(), "UTF-8"));\r
+                        initialize(path);\r
+                    } catch (UnsupportedEncodingException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                } else if ("jar".equals(libURL.getProtocol())) {\r
+                    try {\r
+                        File libFile = OS.extractLib(libURL, libName);\r
+                        initialize(libFile);\r
+                    } catch (FileNotFoundException e) {\r
+                        e.printStackTrace();\r
+                    } catch (IOException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                } else {\r
+                    System.err.println("Unsupported URL protocol '" + libURL + "' for FastLZ native library file '" + libName + "' for os '" + osName + "' and architecture '" + osArch + "'");\r
+                }\r
+            } else {\r
+                initialize(null); // Final fallback. (Needed when running DB tests by ant script).\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * The output buffer must be at least 5% larger than the input buffer and\r
+     * can not be smaller than 66 bytes.\r
+     * \r
+     * @param inputSize size of uncompressed input data in bytes\r
+     * @return maximum amount of bytes needed for the compressed data\r
+     */\r
+    public static int compressBound(int inputSize) {\r
+        return Math.max(66, inputSize + inputSize/20+1);\r
+    }\r
+\r
+    /**\r
+     * Compress a block of data in the input buffer and returns the size of\r
+     * compressed block. The size of input buffer is specified by length. The\r
+     * minimum input buffer size is 16.\r
+     * \r
+     * <p>\r
+     * The output buffer must be at least 5% larger than the input buffer and\r
+     * can not be smaller than 66 bytes.\r
+     * \r
+     * <p>\r
+     * If the input is not compressible, the return value might be larger than\r
+     * length (input buffer size).\r
+     * \r
+     * <p>\r
+     * The input buffer and the output buffer can not overlap.\r
+     * \r
+     * <p>\r
+     * The input and output buffers are assumed to be direct byte buffers.\r
+     */\r
+    static native int compress(ByteBuffer input, int inputOffset, int length,\r
+            ByteBuffer output, int outputOffset);\r
+\r
+    /**\r
+     * Decompress a block of compressed data and returns the size of the\r
+     * decompressed block. If error occurs, e.g. the compressed data is\r
+     * corrupted or the output buffer is not large enough, then 0 (zero) will be\r
+     * returned instead.\r
+     * \r
+     * <p>\r
+     * The input buffer and the output buffer can not overlap.\r
+     * \r
+     * <p>\r
+     * Decompression is memory safe and guaranteed not to write the output\r
+     * buffer more than what is specified in maxout.\r
+     * \r
+     * <p>\r
+     * The input and output buffers are assumed to be direct byte buffers.\r
+     */\r
+    static native int decompress(ByteBuffer input, int inputOffset, int length,\r
+            ByteBuffer output, int outputOffset, int maxout);\r
+\r
+    /**\r
+     * Compress a block of data in the input buffer and returns the size of\r
+     * compressed block. The size of input buffer is specified by length. The\r
+     * minimum input buffer size is 16.\r
+     * \r
+     * <p>\r
+     * The output buffer must be at least 5% larger than the input buffer and\r
+     * can not be smaller than 66 bytes.\r
+     * \r
+     * <p>\r
+     * If the input is not compressible, the return value might be larger than\r
+     * length (input buffer size).\r
+     * \r
+     * <p>\r
+     * The input buffer and the output buffer can not overlap.\r
+     * \r
+     * <p>\r
+     * It is recommended to have both input buffers as direct or heap buffers,\r
+     * not mixed. Mixing different types of buffers will hurt performance a lot.\r
+     * If both buffers are direct byte buffers and native decompression is\r
+     * available, it will be employed.\r
+     */\r
+    public static int compressBuffer(ByteBuffer input, int inputOffset, int length,\r
+            ByteBuffer output, int outputOffset) {\r
+        if (output.isReadOnly())\r
+            throw new IllegalArgumentException("read-only output buffer");\r
+\r
+        if (isNativeInitialized()) {\r
+            if (input.isDirect() && output.isDirect())\r
+                return compress(input, inputOffset, length, output, outputOffset);\r
+        }\r
+\r
+        byte[] inarr = Buffers.getInputArray(input);\r
+        byte[] outarr = Buffers.getOutputArray(output);\r
+        int result = FastLZJava.compress(inarr, inputOffset, length, outarr, outputOffset);\r
+        Buffers.writeOutput(output, outarr);\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Decompress a block of compressed data and returns the size of the\r
+     * decompressed block. If error occurs, e.g. the compressed data is\r
+     * corrupted or the output buffer is not large enough, then 0 (zero) will be\r
+     * returned instead.\r
+     * \r
+     * <p>\r
+     * The input buffer and the output buffer can not overlap.\r
+     * \r
+     * <p>\r
+     * Decompression is memory safe and guaranteed not to write the output\r
+     * buffer more than what is specified in maxout.\r
+     * \r
+     * <p>\r
+     * It is recommended to have both input buffers as direct or heap buffers,\r
+     * not mixed. Mixing different types of buffers will hurt performance a lot.\r
+     * If both buffers are direct byte buffers and native decompression is\r
+     * available, it will be employed.\r
+     */\r
+    public static int decompressBuffer(ByteBuffer input, int inputOffset, int length,\r
+            ByteBuffer output, int outputOffset, int maxout) {\r
+        if (output.isReadOnly())\r
+            throw new IllegalArgumentException("read-only output buffer");\r
+\r
+        if (isNativeInitialized()) {\r
+            if (input.isDirect() && output.isDirect())\r
+                return decompress(input, inputOffset, length, output, outputOffset, maxout);\r
+        }\r
+\r
+        byte[] inarr = Buffers.getInputArray(input);\r
+        byte[] outarr = Buffers.getOutputArray(output);\r
+        int result = FastLZJava.decompress(inarr, inputOffset, length, outarr, outputOffset, maxout);\r
+        Buffers.writeOutput(output, outarr);\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * @param file the FastLZ-compressed file to read\r
+     * @return input stream that decompresses its output using the FastLZ\r
+     *         algorithm. Caller is responsible of closing the returned stream.\r
+     * @throws FileNotFoundException see\r
+     *         {@link FileOutputStream#FileOutputStream(File)} for when this is\r
+     *         thrown\r
+     */\r
+    public static InputStream read(File file) throws FileNotFoundException {\r
+        return nativeInitialized ? new FastLZInputStream(file)\r
+                : new FastLZJavaInputStream(file);\r
+    }\r
+\r
+    /**\r
+     * @param input\r
+     * @return\r
+     * @param input\r
+     *            the input stream to decompress\r
+     * @return a stream that decompresses the specified FastLZ compressed input\r
+     *         stream\r
+     */\r
+    public static InputStream read(InputStream input) {\r
+        return nativeInitialized ? new FastLZInputStream(input)\r
+                : new FastLZJavaInputStream(input);\r
+    }\r
+\r
+    /**\r
+     * @param file the FastLZ-compressed file to write\r
+     * @return output stream that compresses its input using the FastLZ\r
+     *         algorithm. Caller is responsible of closing the returned stream.\r
+     * @throws FileNotFoundException see\r
+     *         {@link FileOutputStream#FileOutputStream(File)} for when this is\r
+     *         thrown\r
+     */\r
+    public static OutputStream write(File file) throws FileNotFoundException {\r
+        return nativeInitialized ? new FastLZOutputStream(file)\r
+                : new FastLZJavaOutputStream(file);\r
+    }\r
+\r
+    /**\r
+     * @param output\r
+     *            the stream to write compressed output into\r
+     * @return a stream that compresses into the specified output stream with\r
+     *         FastLZ\r
+     */\r
+    public static OutputStream write(OutputStream output) {\r
+        return nativeInitialized ? new FastLZOutputStream(output)\r
+                : new FastLZJavaOutputStream(output);\r
+    }\r
+\r
+    /**\r
+     * Warning: custom utility for performance reasons. Only used by\r
+     * org.simantics.db.procore. Do not use elsewhere.\r
+     * \r
+     * @param deflated\r
+     * @param deflatedSize\r
+     * @param inflatedSize\r
+     * @param arrays\r
+     * @return\r
+     */\r
+    public static synchronized native int decompressCluster(ByteBuffer deflated, int deflatedSize, int inflatedSize, Object[] arrays);\r
+\r
+}\r