# automatically generated by the FlatBuffers compiler, do not modify

# namespace: tosa

import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()

class CondIfAttribute(object):
    __slots__ = ['_tab']

    @classmethod
    def GetRootAs(cls, buf, offset=0):
        n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
        x = CondIfAttribute()
        x.Init(buf, n + offset)
        return x

    @classmethod
    def GetRootAsCondIfAttribute(cls, buf, offset=0):
        """This method is deprecated. Please switch to GetRootAs."""
        return cls.GetRootAs(buf, offset)
    @classmethod
    def CondIfAttributeBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
        return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x4F\x53\x41", size_prefixed=size_prefixed)

    # CondIfAttribute
    def Init(self, buf, pos):
        self._tab = flatbuffers.table.Table(buf, pos)

    # CondIfAttribute
    def ThenBranch(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
        if o != 0:
            return self._tab.String(o + self._tab.Pos)
        return None

    # CondIfAttribute
    def ElseBranch(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
        if o != 0:
            return self._tab.String(o + self._tab.Pos)
        return None

def CondIfAttributeStart(builder):
    builder.StartObject(2)

def Start(builder):
    CondIfAttributeStart(builder)

def CondIfAttributeAddThenBranch(builder, thenBranch):
    builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(thenBranch), 0)

def AddThenBranch(builder, thenBranch):
    CondIfAttributeAddThenBranch(builder, thenBranch)

def CondIfAttributeAddElseBranch(builder, elseBranch):
    builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(elseBranch), 0)

def AddElseBranch(builder, elseBranch):
    CondIfAttributeAddElseBranch(builder, elseBranch)

def CondIfAttributeEnd(builder):
    return builder.EndObject()

def End(builder):
    return CondIfAttributeEnd(builder)
