aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/main/java/com/yahoo/document/PrimitiveDataType.java
blob: 7acb32eda23fe58d731b79d2cd63c18abbf9cf7e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document;

import com.yahoo.document.datatypes.FieldValue;
import com.yahoo.vespa.objects.Ids;
import com.yahoo.vespa.objects.ObjectVisitor;

import java.util.Objects;

/**
 * @author Einar M R Rosenvinge
 */
public class PrimitiveDataType extends DataType {

    public static abstract class Factory {
        public abstract FieldValue create();
        public abstract FieldValue create(String value);
    }

    // The global class identifier shared with C++.
    public static final int classId = registerClass(Ids.document + 51, PrimitiveDataType.class);
    private final Class<? extends FieldValue> valueClass;
    private final Factory factory;

    /**
     * Creates a datatype
     *
     * @param name     the name of the type
     * @param code     the code (id) of the type
     * @param factory  the factory for creating field values of this type
     */
    protected PrimitiveDataType(java.lang.String name, int code, Class<? extends FieldValue> valueClass, Factory factory) {
        super(name, code);
        Objects.requireNonNull(valueClass, "valueClass");
        Objects.requireNonNull(factory, "factory");
        this.valueClass = valueClass;
        this.factory = factory;
    }

    @Override
    public PrimitiveDataType clone() {
        return (PrimitiveDataType)super.clone();
    }

    @Override
    public FieldValue createFieldValue() {
        return factory.create();
    }
    @Override
    public FieldValue createFieldValue(Object arg) {
        if (arg == null) return factory.create();
        if (arg instanceof String) return factory.create((String)arg);
        return super.createFieldValue(arg);
    }

    @Override
    public Class<? extends FieldValue> getValueClass() {
        return valueClass;
    }

    @Override
    public boolean isValueCompatible(FieldValue value) {
        return value != null && valueClass.isAssignableFrom(value.getClass());
    }

    @Override
    public PrimitiveDataType getPrimitiveType() {
        return this;
    }

    @Override
    public void visitMembers(ObjectVisitor visitor) {
        super.visitMembers(visitor);
        visitor.visit("valueclass", valueClass.getName());
    }
}