+
+static void
+smart_strlcpy(char *dst, /* I - Output buffer */
+ const char *src, /* I - Input string */
+ size_t dstsize) /* I - Size of output buffer */
+{
+ const unsigned char *srcptr; /* Pointer into input string */
+ unsigned char *dstptr, /* Pointer into output buffer */
+ *dstend; /* End of output buffer */
+ int saw_8859 = 0; /* Saw an extended character that was not UTF-8? */
+
+
+ for (srcptr = (unsigned char *)src, dstptr = (unsigned char *)dst, dstend = dstptr + dstsize - 1; *srcptr;)
+ {
+ if (*srcptr < 0x80)
+ *dstptr++ = *srcptr++; /* ASCII */
+ else if (saw_8859)
+ {
+ /*
+ * Map ISO-8859-1 (most likely character set for legacy LPD clients) to
+ * UTF-8...
+ */
+
+ if (dstptr > (dstend - 2))
+ break;
+
+ *dstptr++ = 0xc0 | (*srcptr >> 6);
+ *dstptr++ = 0x80 | (*srcptr++ & 0x3f);
+ }
+ else if ((*srcptr & 0xe0) == 0xc0 && (srcptr[1] & 0xc0) == 0x80)
+ {
+ /*
+ * 2-byte UTF-8 sequence...
+ */
+
+ if (dstptr > (dstend - 2))
+ break;
+
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ }
+ else if ((*srcptr & 0xf0) == 0xe0 && (srcptr[1] & 0xc0) == 0x80 && (srcptr[2] & 0xc0) == 0x80)
+ {
+ /*
+ * 3-byte UTF-8 sequence...
+ */
+
+ if (dstptr > (dstend - 3))
+ break;
+
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ }
+ else if ((*srcptr & 0xf8) == 0xf0 && (srcptr[1] & 0xc0) == 0x80 && (srcptr[2] & 0xc0) == 0x80 && (srcptr[3] & 0xc0) == 0x80)
+ {
+ /*
+ * 4-byte UTF-8 sequence...
+ */
+
+ if (dstptr > (dstend - 4))
+ break;
+
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ *dstptr++ = *srcptr++;
+ }
+ else
+ {
+ /*
+ * Bad UTF-8 sequence, this must be an ISO-8859-1 string...
+ */
+
+ saw_8859 = 1;
+
+ if (dstptr > (dstend - 2))
+ break;
+
+ *dstptr++ = 0xc0 | (*srcptr >> 6);
+ *dstptr++ = 0x80 | (*srcptr++ & 0x3f);
+ }
+ }
+
+ *dstptr = '\0';
+}