Skip to content

Commit

Permalink
GROOVY-3173
Browse files Browse the repository at this point in the history
Partial Fix for GROOVY-3173. Added support for assigning single character string/GString to Character[] elements.

git-svn-id: http://svn.codehaus.org/groovy/trunk/groovy/groovy-core@14535 a5544e8c-8a19-0410-ba12-f9af4593a198
  • Loading branch information
roshandawrani committed Dec 20, 2008
1 parent 9b200b2 commit 7e3a29d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
Expand Up @@ -15,6 +15,7 @@
*/
package org.codehaus.groovy.runtime.dgmimpl.arrays;

import groovy.lang.GString;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaMethod;
import org.codehaus.groovy.reflection.CachedClass;
Expand All @@ -39,15 +40,26 @@ public final CachedClass getDeclaringClass() {
public Object invoke(Object object, Object[] arguments) {
final Object[] objects = (Object[]) object;
Object newValue = arguments[1];
Class arrayComponentClass = objects.getClass().getComponentType();
final int index = normaliseIndex(((Integer) arguments[0]).intValue(), objects.length);
if (newValue instanceof Number) {
Class arrayComponentClass = objects.getClass().getComponentType();
if (!arrayComponentClass.equals(newValue.getClass())) {
Object newVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass);
objects[normaliseIndex(((Integer) arguments[0]).intValue(), objects.length)] = newVal;
objects[index] = newVal;
return null;
}
} else if (Character.class.isAssignableFrom(arrayComponentClass)) {
if (newValue instanceof GString) newValue = newValue.toString();
if (newValue instanceof String) {
String s = (String) newValue;
if (s.length() != 1) throw new IllegalArgumentException("String of length 1 expected but got a bigger one");
objects[index] = s.charAt(0);
} else {
objects[index] = ((Character) newValue).charValue();
}
return null;
}
objects[normaliseIndex(((Integer) arguments[0]).intValue(), objects.length)] = arguments[1];
objects[index] = arguments[1];
return null;
}

Expand Down
23 changes: 23 additions & 0 deletions src/test/groovy/ArrayTest.groovy
Expand Up @@ -222,4 +222,27 @@ class ArrayTest extends GroovyTestCase {
assertEquals 100, doubles[0]
assertEquals 50, doubles[1]
}

void testCharacterArrayElementAssignments() {
Character[] ca = new Character[1]

// Assignments statements.
ca[0] = 'b' as char
assert ca[0] == 'b'

ca[0] = '\u00A1' as char
assert ca[0] == '\u00A1'

ca[0] = 'a'
assert ca[0] == 'a'

ca[0] = '\u00A0'
assert ca[0] == '\u00A0'

def foo = 'z'

ca[0] = "$foo"
assert ca[0] == 'z'
}

}

0 comments on commit 7e3a29d

Please sign in to comment.