From 4b713862c86297979aef91f429a66d5a541884dc Mon Sep 17 00:00:00 2001 From: Masaki Mori Date: Mon, 14 Sep 2015 13:45:08 +0900 Subject: [PATCH] Support index access on primitive arrays --- .../samskivert/mustache/DefaultCollector.java | 21 ++++++++++++++++++- .../com/samskivert/mustache/MustacheTest.java | 13 ++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/samskivert/mustache/DefaultCollector.java b/src/main/java/com/samskivert/mustache/DefaultCollector.java index 9e3a8f6..673310e 100644 --- a/src/main/java/com/samskivert/mustache/DefaultCollector.java +++ b/src/main/java/com/samskivert/mustache/DefaultCollector.java @@ -43,8 +43,15 @@ public class DefaultCollector extends BasicCollector Mustache.VariableFetcher fetcher = super.createFetcher(ctx, name); if (fetcher != null) return fetcher; - // first check for a getter which provides the value Class cclass = ctx.getClass(); + + // try generic 'indexing' fetcher for primitive arrays + char c = name.charAt(0); + if (c >= '0' && c <= '9') { + if (cclass.isArray()) return GENERIC_ARRAY_FETCHER; + } + + // first check for a getter which provides the value final Method m = getMethod(cclass, name); if (m != null) { return new Mustache.VariableFetcher() { @@ -162,4 +169,16 @@ public class DefaultCollector extends BasicCollector } return null; } + + protected static final Mustache.VariableFetcher GENERIC_ARRAY_FETCHER = new Mustache.VariableFetcher() { + public Object get (Object ctx, String name) throws Exception { + try { + return Array.get(ctx, Integer.parseInt(name)); + } catch (NumberFormatException nfe) { + return Template.NO_FETCHER_FOUND; + } catch (IndexOutOfBoundsException e) { + return Template.NO_FETCHER_FOUND; + } + } + }; } diff --git a/src/test/java/com/samskivert/mustache/MustacheTest.java b/src/test/java/com/samskivert/mustache/MustacheTest.java index 0b14a5f..84d139b 100644 --- a/src/test/java/com/samskivert/mustache/MustacheTest.java +++ b/src/test/java/com/samskivert/mustache/MustacheTest.java @@ -89,6 +89,19 @@ public class MustacheTest }); } + @Test public void testPrimitiveArrayIndexVariable () { + test("1", "{{foo.0}}", new Object() { + int[] getFoo () { return new int[] { 1, 2, 3, 4 }; } + }); + } + + @Test public void testPrimitiveArrayIndexOutOfBoundsVariable () { + Mustache.Compiler comp = Mustache.compiler().defaultValue("?"); + test(comp, "?", "{{foo.4}}", new Object() { + int[] getFoo () { return new int[] { 1, 2, 3, 4 }; } + }); + } + @Test public void testCallSiteReuse () { Template tmpl = Mustache.compiler().compile("{{foo}}"); Object ctx = new Object() {