How does htslib/samtools access optional BAM fields?
How does htslib access each of the optional fields, given this structure?


htslib uses a macro, bam_get_aux, for this purpose. You can check the source code of this macro — it essentially just advances the data pointer of the current record to the start of the optional data, which is after all other data. But you shouldn’t care about this, and just use the relevant exported functions for reading optional (“auxiliary”) data:


bam_aux_get returns a pointer to an optional record, given by its two-character tag name.
bam_aux2‹C› converts the pointer returned by the previous function to the actual type of the optional tag; here, ‹C› is a type identifier: i for an integer, Z for a zero-terminated character string, etc. Refer to the documentation and the htslib/sam.h file for a complete list.



  Does it keep the order of the optional fields, or is this information unavailable?


As long as you don’t modify optional fields, the order is kept, but unspecified. Do not rely on the order!


  When a user runs htslib or even samtools view, how does the BAM row "end"


BAM records store a header that contains the record size.