DRILL-8194: Fix the function of REPLACE throws IndexOutOfBoundsException If text's length is more than previously applied (#2522)

diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/StringFunctions.java b/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/StringFunctions.java
index 27b0644..305cfcd 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/StringFunctions.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/StringFunctions.java
@@ -894,10 +894,15 @@
 
     @Override
     public void eval() {
-      out.buffer = buffer;
       out.start = out.end = 0;
       int fromL = from.end - from.start;
       int textL = text.end - text.start;
+      if (buffer.capacity() < textL) {
+        // We realloc buffer, if actual length is more than previously applied.
+        out.buffer = buffer.reallocIfNeeded(textL);
+      } else {
+        out.buffer = buffer;
+      }
 
       if (fromL > 0 && fromL <= textL) {
         //If "from" is not empty and it's length is no longer than text's length
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/expr/fn/impl/TestStringFunctions.java b/exec/java-exec/src/test/java/org/apache/drill/exec/expr/fn/impl/TestStringFunctions.java
index 555323b..8dc1093 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/exec/expr/fn/impl/TestStringFunctions.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/expr/fn/impl/TestStringFunctions.java
@@ -19,6 +19,7 @@
 
 import static org.junit.Assert.assertTrue;
 
+import org.apache.commons.lang3.RandomStringUtils;
 import org.apache.drill.categories.UnlikelyTest;
 import org.apache.drill.test.BaseTestQuery;
 import org.apache.drill.categories.SqlFunctionTest;
@@ -336,6 +337,19 @@
   }
 
   @Test
+  public void testReplaceOutBuffer() throws Exception {
+    String originValue = RandomStringUtils.randomAlphabetic(8192).toLowerCase() + "12345";
+    String expectValue = originValue.replace("12345", "67890");
+    String sql = "select replace(c1, '12345', '67890') as col from (values('" + originValue + "')) as t(c1)";
+    testBuilder()
+      .sqlQuery(sql)
+      .ordered()
+      .baselineColumns("col")
+      .baselineValues(expectValue)
+      .go();
+  }
+
+  @Test
   public void testLikeStartsWith() throws Exception {
 
     // all ASCII.