Update to upstream util-linux 2.20.1
[framework/base/util-linux-ng.git] / libblkid / src / encode.c
similarity index 85%
rename from shlibs/blkid/src/encode.c
rename to libblkid/src/encode.c
index 0317be1..03d5f4e 100644 (file)
 #include <string.h>
 #include <ctype.h>
 
-#include "blkdev.h"
 #include "blkidP.h"
 
 #define UDEV_ALLOWED_CHARS_INPUT               "/ $%?,"
 
+/**
+ * SECTION: encode
+ * @title: Encoding utils
+ * @short_description: encode strings to safe udev-compatible formats
+ *
+ */
+
 /* count of characters used to encode one unicode char */
 static int utf8_encoded_expected_len(const char *str)
 {
@@ -227,6 +233,41 @@ static int replace_chars(char *str, const char *white)
        return replaced;
 }
 
+size_t blkid_encode_to_utf8(int enc, unsigned char *dest, size_t len,
+                       const unsigned char *src, size_t count)
+{
+       size_t i, j;
+       uint16_t c;
+
+       for (j = i = 0; i + 2 <= count; i += 2) {
+               if (enc == BLKID_ENC_UTF16LE)
+                       c = (src[i+1] << 8) | src[i];
+               else /* BLKID_ENC_UTF16BE */
+                       c = (src[i] << 8) | src[i+1];
+               if (c == 0) {
+                       dest[j] = '\0';
+                       break;
+               } else if (c < 0x80) {
+                       if (j+1 >= len)
+                               break;
+                       dest[j++] = (uint8_t) c;
+               } else if (c < 0x800) {
+                       if (j+2 >= len)
+                               break;
+                       dest[j++] = (uint8_t) (0xc0 | (c >> 6));
+                       dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
+               } else {
+                       if (j+3 >= len)
+                               break;
+                       dest[j++] = (uint8_t) (0xe0 | (c >> 12));
+                       dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
+                       dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
+               }
+       }
+       dest[j] = '\0';
+       return j;
+}
+
 /**
  * blkid_encode_string:
  * @str: input string to be encoded
@@ -286,6 +327,8 @@ err:
  *
  * Allows plain ascii, hex-escaping and valid utf8. Replaces all whitespaces
  * with '_'.
+ *
+ * Returns: 0 on success or -1 in case of error.
  */
 int blkid_safe_string(const char *str, char *str_safe, size_t len)
 {