<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _elements_to_dict(data, position, obj_end, opts, result=None):
 """Decode a BSON document into result."""

    if result is None:
        result = opts.document_class()
    end = obj_end - 1
    while position < end:
        key, value, position = _element_to_dict(data, position, obj_end, opts)
        result[key] = value
    if position != obj_end:
        raise InvalidBSON('bad object or element length')
    return result