--!strict --!optimize 2 -- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is -- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from -- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. local Text = {} -- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) Text.CP1252 = { [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, } function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end -- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) end if utf8.len(text) then return text end if warnings then table.insert(warnings, "text is not UTF-8: read as Windows-1252") end local out = table.create(#text) for i = 1, #text do local b = string.byte(text, i) if b < 0x80 then out[i] = string.char(b) else out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b) end end return table.concat(out) end function Text.lines(text: string): { string } text = string.gsub(text, "\r\n?", "\n") local out = {} for line in string.gmatch(text .. "\n", "([^\n]*)\n") do table.insert(out, line) end return out end return Text