** Simple charset converter. Converts string from specified encoding to UTF-8. ** The return value must be freed by the caller. */
| 1656 | ** The return value must be freed by the caller. |
| 1657 | */ |
| 1658 | char *msGetEncodedString(const char *string, const char *encoding) |
| 1659 | { |
| 1660 | #ifdef USE_ICONV |
| 1661 | iconv_t cd = NULL; |
| 1662 | const char *inp; |
| 1663 | char *outp, *out = NULL; |
| 1664 | size_t len, bufsize, bufleft, iconv_status; |
| 1665 | |
| 1666 | #ifdef USE_FRIBIDI |
| 1667 | if(fribidi_parse_charset ((char*)encoding)) |
| 1668 | return msGetFriBidiEncodedString(string, encoding); |
| 1669 | #endif |
| 1670 | len = strlen(string); |
| 1671 | |
| 1672 | if (len == 0 || (encoding && strcasecmp(encoding, "UTF-8")==0)) |
| 1673 | return msStrdup(string); /* Nothing to do: string already in UTF-8 */ |
| 1674 | |
| 1675 | cd = iconv_open("UTF-8", encoding); |
| 1676 | if(cd == (iconv_t)-1) { |
| 1677 | msSetError(MS_IDENTERR, "Encoding not supported by libiconv (%s).", |
| 1678 | "msGetEncodedString()", encoding); |
| 1679 | return NULL; |
| 1680 | } |
| 1681 | |
| 1682 | bufsize = len * 6 + 1; /* Each UTF-8 char can be up to 6 bytes */ |
| 1683 | inp = string; |
| 1684 | out = (char*) malloc(bufsize); |
| 1685 | if(out == NULL){ |
| 1686 | msSetError(MS_MEMERR, NULL, "msGetEncodedString()"); |
| 1687 | iconv_close(cd); |
| 1688 | return NULL; |
| 1689 | } |
| 1690 | strlcpy(out, string, bufsize); |
| 1691 | outp = out; |
| 1692 | |
| 1693 | bufleft = bufsize; |
| 1694 | iconv_status = -1; |
| 1695 | |
| 1696 | while (len > 0){ |
| 1697 | iconv_status = iconv(cd, (char**)&inp, &len, &outp, &bufleft); |
| 1698 | if(iconv_status == -1){ |
| 1699 | msFree(out); |
| 1700 | iconv_close(cd); |
| 1701 | return msStrdup(string); |
| 1702 | } |
| 1703 | } |
| 1704 | out[bufsize - bufleft] = '\0'; |
| 1705 | |
| 1706 | iconv_close(cd); |
| 1707 | |
| 1708 | return out; |
| 1709 | #else |
| 1710 | if (*string == '\0' || (encoding && strcasecmp(encoding, "UTF-8")==0)) |
| 1711 | return msStrdup(string); /* Nothing to do: string already in UTF-8 */ |
| 1712 | |
| 1713 | msSetError(MS_MISCERR, "Not implemeted since Iconv is not enabled.", "msGetEncodedString()"); |
| 1714 | return NULL; |
| 1715 | #endif |
no test coverage detected