From 1d7b97574341dc2db0cca1c106256d5f7ef280b8 Mon Sep 17 00:00:00 2001 From: Manuel Carmona Date: Thu, 7 Sep 2017 14:17:56 +0200 Subject: [PATCH] fix getLanguage when arguments are null --- .../main/java/tech/sourced/enry/GoUtils.java | 22 +++++++++++++++---- .../test/java/tech/sourced/enry/EnryTest.java | 11 ++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/java/src/main/java/tech/sourced/enry/GoUtils.java b/java/src/main/java/tech/sourced/enry/GoUtils.java index c845841c..3deb6f44 100644 --- a/java/src/main/java/tech/sourced/enry/GoUtils.java +++ b/java/src/main/java/tech/sourced/enry/GoUtils.java @@ -15,12 +15,19 @@ static GoString.ByValue toGoString(String str) { bytes = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { bytes = str.getBytes(); + } catch (NullPointerException e) { + bytes = null; + } + + int length = 0; + Pointer ptr = null; + if (bytes != null) { + length = bytes.length; + ptr = ptrFromBytes(bytes); } GoString.ByValue val = new GoString.ByValue(); - val.n = bytes.length; - Pointer ptr = new Memory(bytes.length); - ptr.write(0, bytes, 0, bytes.length); + val.n = length; val.p = ptr; return val; } @@ -49,7 +56,14 @@ static String[] toJavaStringArray(GoSlice slice) { } static GoSlice.ByValue toGoByteSlice(byte[] bytes) { - return sliceFromPtr(bytes.length, ptrFromBytes(bytes)); + int length = 0; + Pointer ptr = null; + if (bytes != null) { + length = bytes.length; + ptr = ptrFromBytes(bytes); + } + + return sliceFromPtr(length, ptr); } static GoSlice.ByValue sliceFromPtr(int len, Pointer ptr) { diff --git a/java/src/test/java/tech/sourced/enry/EnryTest.java b/java/src/test/java/tech/sourced/enry/EnryTest.java index 69f142e7..0b599c58 100644 --- a/java/src/test/java/tech/sourced/enry/EnryTest.java +++ b/java/src/test/java/tech/sourced/enry/EnryTest.java @@ -18,6 +18,17 @@ public void getLanguage() { assertEquals("PHP", Enry.getLanguage("foobar.php", code.getBytes())); } + @Test + public void getLanguageWithNullContent() { + assertEquals("Python", Enry.getLanguage("foo.py", null)); + } + + @Test + public void getLanguageWithNullFilename() { + byte[] content = "#!/usr/bin/env python".getBytes(); + assertEquals("Python", Enry.getLanguage(null, content)); + } + @Test public void getLanguageByContent() { String code = "