introduce and use helpers lms_string_size_strndup() and lms_string_size_dup()
[platform/upstream/lightmediascanner.git] / src / lib / shared / util.c
1 /**
2  * Copyright (C) 2013  Intel Corporation. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public License
6  * as published by the Free Software Foundation; either version 2.1 of
7  * the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  *
19  * @author Lucas De Marchi <lucas.demarchi@intel.com>
20  */
21
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "util.h"
26
27 struct lms_string_size str_extract_name_from_path(
28     const char *path, unsigned int pathlen, unsigned int baselen,
29     const struct lms_string_size *ext, struct lms_charset_conv *cs_conv)
30 {
31     struct lms_string_size str;
32
33     str.len = pathlen - baselen - ext->len;
34     str.str = malloc(str.len + 1);
35     if (!str.str)
36         return (struct lms_string_size) { };
37     memcpy(str.str, path + baselen, str.len);
38     str.str[str.len] = '\0';
39     if (cs_conv)
40         lms_charset_conv(cs_conv, &str.str, &str.len);
41
42     return str;
43 }
44
45 /* Euclidean algorithm
46  * http://en.wikipedia.org/wiki/Euclidean_algorithm */
47 static unsigned int gcd(unsigned int a, unsigned int b)
48 {
49     unsigned int t;
50
51     while (b) {
52         t = b;
53         b = a % t;
54         a = t;
55     }
56
57     return a;
58 }
59
60 void reduce_gcd(unsigned int w, unsigned int h, unsigned int *dw,
61                 unsigned int *dh)
62 {
63     unsigned int f;
64
65     *dw = w;
66     *dh = h;
67
68     if (!w || !h)
69         return;
70
71     f = gcd(w, h);
72     *dw /= f;
73     *dh /= f;
74 }