Collection of enums from arrays of enum cases

yeah, i ran into similar issues when pursuing a struct EncodingView<Element> -based idea.

extension Letters
    struct EncodingView<Element> where Element:BSONDocumentEncodable
        let elements:[Element]

        init(_ elements:[Element])
            self.elements = elements
extension Letters.EncodingView:RandomAccessCollection
    var startIndex:Int { self.elements.startIndex }
    var endIndex:Int { self.elements.endIndex }

    subscript(index:Int) -> any BSONDocumentEncodable { self.elements[index] }

but one cannot actually construct any such views, because the individual Letter case payloads don’t conform to BSONDocumentEncodable (and they shouldn’t!), only Letter itself does.

with enough effort, you could work around that by introducing a LetterProtocol abstraction, but then you’ve got a

FlattenCollection<[any RandomAccessCollection<any BSONDocumentEncodable>]>

which isn’t a valid type because any RandomAccessCollection doesn’t conform to Collection.

now, if i haven’t hinted at it enough yet, i don’t actually need to do a lot of Collection things with this structure, it just needs to conform to Collection in order to serialize itself to BSON. the procedure is basically this:

//  Requires Collection
let count:Int = self.letters.count

//  Requires Sequence<some BSONDocumentEncodable>
let insert:Mongo.Insert = .init(documents: self.letters)
guard count == try await insert)

i’m trying to avoid intermediate buffers as much as possible because in reality, the “letters” arrays are quite large and encoding them is a very memory-intensive operation.