add comments explaining what is going on (since long file names are really weird), rewrite the second loop to do one UTF16 char at a time instead of byte, and fix coding style.
Signed-off-by: Michael Tokarev <m...@tls.msk.ru> --- block/vvfat.c | 54 +++++++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 23 deletions(-) on top of the previous patch diff --git a/block/vvfat.c b/block/vvfat.c index b53e3b452b..4827288756 100644 --- a/block/vvfat.c +++ b/block/vvfat.c @@ -401,7 +401,7 @@ static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs) static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename) { - int number_of_entries, i; + unsigned nents, i; glong length; gunichar2 *longname = g_utf8_to_utf16(filename, -1, NULL, &length, NULL); @@ -410,31 +410,39 @@ static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename) return NULL; } - number_of_entries = DIV_ROUND_UP(length * 2, 26); - - for(i=0;i<number_of_entries;i++) { - direntry_t *entry=array_get_next(&(s->directory)); - entry->attributes=0xf; - entry->reserved[0]=0; - entry->begin=0; - entry->name[0]=(number_of_entries-i)|(i==0?0x40:0); - } - for(i=0;i<26*number_of_entries;i++) { - unsigned char *entry=array_get(&(s->directory),s->directory.next-1-(i/26)); - int offset=(i%26); - if(offset<10) offset=1+offset; - else if(offset<22) offset=14+offset-10; - else offset=28+offset-22; - if (i >= 2 * length + 2) { - entry[offset] = 0xff; - } else if (i % 2 == 0) { - entry[offset] = longname[i / 2] & 0xff; - } else { - entry[offset] = longname[i / 2] >> 8; + /* + * long file name is split into multiple directory entries, + * 13 UTF16 chars (26 bytes) in each, + * in reverse order. + */ + nents = DIV_ROUND_UP(length, 13); + + for (i = 0; i < nents; ++i) { /* allocate and basic init */ + direntry_t *entry = array_get_next(&s->directory); + entry->attributes = 0xf; + entry->reserved[0] = 0; + entry->begin = 0; + entry->name[0] = (nents - i) | (i == 0 ? 0x40 : 0); + } + + /* write 13 chars of name to each entry, entries in reverse order */ + for (i = 0; i < nents * 13; ++i) { + unsigned char *entry = + array_get(&s->directory, s->directory.next - 1 - i / 13); + unsigned off = i % 13; + /* each entry has 3 different places for the name: */ + off = off < 5 ? off * 2 + 1 /* bytes 1..10, 5 chars 0..4, unaligned */ + : off < 11 ? (off - 5) * 2 + 14 /* bytes 14..25, 6 chars 5..10 */ + : (off - 11) * 2 + 28; /* bytes 28..31, 2 chars 11..12 */ + if (i <= length) { /* name and trailing U+0000 */ + entry[off + 0] = longname[i] & 0xff; + entry[off + 1] = longname[i] >> 8; + } else { /* fill remaining parts with U+FFFF */ + entry[off + 0] = entry[off + 1] = 0xff; } } g_free(longname); - return array_get(&(s->directory),s->directory.next-number_of_entries); + return array_get(&s->directory, s->directory.next - nents); } static char is_free(const direntry_t* direntry) -- 2.39.5