Skip to content

Commit 85c1e74

Browse files
timfelppisl
authored andcommitted
add simple form of bytes.replace
1 parent 33a942b commit 85c1e74

File tree

1 file changed

+22
-0
lines changed
  • graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/bytes

1 file changed

+22
-0
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/bytes/BytesBuiltins.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import static com.oracle.graal.python.nodes.SpecialMethodNames.__SETITEM__;
4545
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
4646

47+
import java.io.UnsupportedEncodingException;
4748
import java.nio.charset.CodingErrorAction;
4849
import java.util.List;
4950

@@ -540,6 +541,27 @@ public PDict maketrans(PBytes from, PBytes to,
540541
}
541542

542543
return translation;
544+
@Builtin(name = "replace", fixedNumOfPositionalArgs = 3)
545+
@GenerateNodeFactory
546+
abstract static class ReplaceNode extends PythonTernaryBuiltinNode {
547+
@Child BytesNodes.ToBytesNode toBytes = BytesNodes.ToBytesNode.create();
548+
549+
@Specialization
550+
@TruffleBoundary
551+
PBytes replace(PBytes self, PBytes substr, PBytes replacement) {
552+
byte[] bytes = toBytes.execute(self);
553+
byte[] subBytes = toBytes.execute(substr);
554+
byte[] replacementBytes = toBytes.execute(replacement);
555+
try {
556+
String string = new String(bytes, "ASCII");
557+
String subString = new String(subBytes, "ASCII");
558+
String replacementString = new String(replacementBytes, "ASCII");
559+
byte[] newBytes = string.replace(subString, replacementString).getBytes("ASCII");
560+
return factory().createBytes(newBytes);
561+
} catch (UnsupportedEncodingException e) {
562+
CompilerDirectives.transferToInterpreter();
563+
throw new IllegalStateException();
564+
}
543565
}
544566
}
545567
}

0 commit comments

Comments
 (0)