目录
最近在做presto源码改造和业务功能支持,需要做一个返回map的udf,网上例子比较少,记录下。
Slice,Block,Page
Slice,Block和Page都是Presto常用数据结构,Map返回类型也需要通过这三个数据结构构造出来。下面的总结大部分摘自网络。
Slice
Slice所在包是io.airlift.slice,他定义了一段虚拟内存,可以通过他构造出我们常用的String,Int,Float,Byte等基本常用变量。网上都有很多例子了。
public void SliceTest() {
//分配空间,这个slice是可以反复使用的
Slice slice = Slices.allocate(20);
String a = "hello world";
slice.setBytes(0, a.getBytes());
System.out.println(new String(slice.getBytes(0, a.length())));//a
String b = "hello presto";
slice.setBytes(0, b.getBytes()); //内存索引从0开始,会覆盖a
System.out.println(new String(slice.getBytes(0, b .length())));//b
int c = 6;
slice.setInt(0, c);
System.out.println(slice.getInt(0));//c
}
Block
Block所在包为com.facebook.presto.common.block,Block 可以认为是同一类数据(int,long,Slice等)的数组。每个数据项都有一个位置信息Position,可以理解为索引。总位置个数代表 Block 中数据的总行数,常用的实现类有RowBlock,ArrayBlock和MapBlock等,等会要返回的Map类型也是通过Block构造。
下面是Presto中MapBlock实现读写的源码:
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.common.block;
import com.facebook.presto.common.block.AbstractMapBlock.HashTables;
import com.facebook.presto.common.type.MapType;
import io.airlift.slice.SliceInput;
import io.airlift.slice.SliceOutput;
import java.util.Optional;
import static com.facebook.presto.common.block.AbstractMapBlock.HASH_MULTIPLIER;
import static io.airlift.slice.S