github.com/matrixorigin/matrixone@v0.7.0/pkg/vectorize/lpad/lpad.go (about)

     1  // Copyright 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lpad
    16  
    17  func lpadOne(a string, b0 int, c string) string {
    18  	c0 := len(c)
    19  	if c0 == 0 {
    20  		panic("Pad with empty string")
    21  	}
    22  	if len(a) > b0 {
    23  		return string([]byte(a)[:b0])
    24  	} else {
    25  		lens := b0 - len(a)
    26  		t1 := lens / c0
    27  		t2 := lens % c0
    28  		tmps := []byte{}
    29  		for j := 0; j < t1; j++ {
    30  			tmps = append(tmps, c...)
    31  		}
    32  		tmps = append(tmps, []byte(c)[:t2]...)
    33  		tmps = append(tmps, a...)
    34  		return string(tmps)
    35  	}
    36  }
    37  
    38  func LpadVarchar(a []string, b []int64, c []string) []string {
    39  	// XXX This function, always take b[0] and c[0], is this correct?
    40  	b0 := int(b[0])
    41  	c0 := c[0]
    42  	res := make([]string, len(a))
    43  	//in fact,the length of three slice is the same with each other
    44  	for i := range a {
    45  		res[i] = lpadOne(a[i], b0, c0)
    46  	}
    47  	return res
    48  }
    49  
    50  func Lpad(res []string, src []string, length uint32, pad []string) []string {
    51  	for idx, str := range src {
    52  		res[idx] = lpadOne(str, int(length), pad[idx])
    53  	}
    54  	return res
    55  }