embedded_cotoutf8 0.1.6

COTO is a library that translates numerical primitives into readable ASCII UTF-8 arrays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#![no_std]

/**
COTO is derived from the Gujarati word કોતો, meaning 'engrave.' It refers to a concept where data sizes are fixed. COTO is a library that translates numerical primitives into readable ASCII UTF-8 arrays.

## Example󰙨

Convert primitives data type to specific Byte(character) array for str

```rust
    // for i8
    let num: i8 = -127;
    let binding = num.coto_utf8();
    let result = core::str::from_utf8(&binding).unwrap();
    assert_eq!(result, "-127");
    // for f32
    let num: f32 = 1524.001;
    let binding = num.coto_utf8();
    let result = core::str::from_utf8(&binding).unwrap();
    println!("{}", result); // OUTPUT:` 1524.024`

```

Debug or Display for ufmt _By default ufmt feature enabled_ or fmt

```rust
    use embedded_cotoutf8::DebugODisplay;

    let num = DebugODisplay(44245.12f32);
    println!("{}", num);
    ufmt::uwriteln!(serial, "{}", num); // for ufmt
```

implemented for `i8`,`i16`,`132`,`i64`,`u8`,`u16`,`u32`,`f32`,`f64`
*/
use core::{
    f64,
    fmt::{Debug, Display},
};

use ufmt::{uDebug, uDisplay};

pub trait COtoUTF8<const O: usize> {
    fn coto_utf8(&self) -> [u8; O];
}

// u8 - max value 255 (3 digits)
impl COtoUTF8<3> for u8 {
    fn coto_utf8(&self) -> [u8; 3] {
        let mut result = [0u8; 3];
        let mut n = *self;

        if n == 0 {
            result[2] = b'0';
            return result;
        }

        let mut pos = 2;
        while n > 0 {
            result[pos] = (n % 10) + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        result
    }
}

// u16 - max value 65535 (5 digits)
impl COtoUTF8<5> for u16 {
    fn coto_utf8(&self) -> [u8; 5] {
        let mut result = [0u8; 5];
        let mut n = *self;

        if n == 0 {
            result[4] = b'0';
            return result;
        }

        let mut pos = 4;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        result
    }
}

// u32 - max value 4294967295 (10 digits)
impl COtoUTF8<10> for u32 {
    fn coto_utf8(&self) -> [u8; 10] {
        let mut result = [0u8; 10];
        let mut n = *self;

        if n == 0 {
            result[9] = b'0';
            return result;
        }

        let mut pos = 9;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        result
    }
}

// u64 - max value 18446744073709551615 (20 digits)
impl COtoUTF8<20> for u64 {
    fn coto_utf8(&self) -> [u8; 20] {
        let mut result = [0u8; 20];
        let mut n = *self;

        if n == 0 {
            result[19] = b'0';
            return result;
        }

        let mut pos = 19;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        result
    }
}

// i8 - range -128 to 127 (4 digits including sign)
impl COtoUTF8<4> for i8 {
    fn coto_utf8(&self) -> [u8; 4] {
        let mut result = [0u8; 4];
        let mut n = self.abs() as u8;

        if *self == 0 {
            result[3] = b'0';
            return result;
        }

        let mut pos = 3;
        while n > 0 {
            result[pos] = (n % 10) + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        if *self < 0 {
            result[pos] = b'-';
        }

        result
    }
}

// i16 - range -32768 to 32767 (6 digits including sign)
impl COtoUTF8<6> for i16 {
    fn coto_utf8(&self) -> [u8; 6] {
        let mut result = [0u8; 6];
        let mut n = self.abs() as u16;

        if *self == 0 {
            result[5] = b'0';
            return result;
        }

        let mut pos = 5;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        if *self < 0 {
            result[pos] = b'-';
        }

        result
    }
}

// i32 - range -2147483648 to 2147483647 (11 digits including sign)
impl COtoUTF8<11> for i32 {
    fn coto_utf8(&self) -> [u8; 11] {
        let mut result = [0u8; 11];
        let mut n = self.abs() as u32;

        if *self == 0 {
            result[10] = b'0';
            return result;
        }

        let mut pos = 10;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        if *self < 0 {
            result[pos] = b'-';
        }

        result
    }
}

// i64 - range -9223372036854775808 to 9223372036854775807 (20 digits including sign)
impl COtoUTF8<20> for i64 {
    fn coto_utf8(&self) -> [u8; 20] {
        let mut result = [0u8; 20];
        let mut n = self.abs() as u64; // Use u64 to handle i64::MIN safely

        if *self == 0 {
            result[19] = b'0';
            return result;
        }

        let mut pos = 19;
        while n > 0 {
            result[pos] = (n % 10) as u8 + b'0';
            n /= 10;
            pos = pos.saturating_sub(1);
        }

        if *self < 0 {
            result[pos] = b'-';
        }

        result
    }
}

pub trait COtoHex<const O: usize> {
    fn coto_hex(&self) -> [u8; O];
}

pub struct DebugODisplay<T: COtoUTF8<O>, const O: usize>(pub T);

impl<T, const O: usize> Debug for DebugODisplay<T, O>
where
    T: COtoUTF8<O>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(core::str::from_utf8(&self.0.coto_utf8()).unwrap())?;
        Ok(())
    }
}

impl<T, const O: usize> Display for DebugODisplay<T, O>
where
    T: COtoUTF8<O>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(core::str::from_utf8(&self.0.coto_utf8()).unwrap())?;
        Ok(())
    }
}

#[cfg(feature = "ufmt")]
impl<T, const O: usize> uDebug for DebugODisplay<T, O>
where
    T: COtoUTF8<O>,
{
    fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
    where
        W: ufmt::uWrite + ?Sized,
    {
        f.write_str(core::str::from_utf8(&self.0.coto_utf8()).unwrap())?;
        Ok(())
    }
}

#[cfg(feature = "ufmt")]
impl<T, const O: usize> uDisplay for DebugODisplay<T, O>
where
    T: COtoUTF8<O>,
{
    fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
    where
        W: ufmt::uWrite + ?Sized,
    {
        f.write_str(core::str::from_utf8(&self.0.coto_utf8()).unwrap())?;
        Ok(())
    }
}

impl COtoHex<2> for u8 {
    fn coto_hex(&self) -> [u8; 2] {
        let mut sample = [0u8; 2];

        for (i, j) in sample.iter_mut().enumerate() {
            *j = match (self >> (4 * i) & 0x0F) % 16 {
                int @ 0..=9 => b'0' + int,
                alpha @ 10..=15 => 55 + alpha,
                _ => 0,
            }
        }
        sample.reverse();
        sample
    }
}

impl COtoHex<4> for u16 {
    fn coto_hex(&self) -> [u8; 4] {
        let mut sample = [0u8; 4];

        for (i, j) in sample.iter_mut().enumerate() {
            *j = match ((self >> (4 * i) & 0x0F) % 16) as u8 {
                int @ 0..=9 => b'0' + int,
                alpha @ 10..=15 => 55 + alpha,
                _ => 0,
            }
        }
        sample.reverse();
        sample
    }
}

impl COtoHex<8> for u32 {
    fn coto_hex(&self) -> [u8; 8] {
        let mut sample = [0u8; 8];

        for (i, j) in sample.iter_mut().enumerate() {
            *j = match ((self >> (4 * i) & 0x0F) % 16) as u8 {
                int @ 0..=9 => b'0' + int,
                alpha @ 10..=15 => 55 + alpha,
                _ => 0,
            }
        }
        sample.reverse();
        sample
    }
}

impl COtoUTF8<9> for f32 {
    fn coto_utf8(&self) -> [u8; 9] {
        let mut buffer = [0u8; 9];
        buffer[0] = if self.is_sign_negative() { b'-' } else { b' ' };
        if self.is_infinite() {
            buffer[1..].copy_from_slice(b"INFINITY");
        } else {
            let mut num = if *self < 0. { -*self } else { *self };
            let mut exponential: i8 = 0;
            while !(0. ..=10.).contains(&num) {
                if num < 0. {
                    exponential -= 1;
                    num *= 10.;
                } else {
                    exponential += 1;
                    num /= 10.;
                }
            }
            if (-6..=3).contains(&exponential) {
                let exponent = exponential.max(0) as usize;
                buffer[2 + exponent] = b'.';
                let cotonum = ((self * 1_000_000.0) as i32).coto_utf8();
                buffer[1..={ exponent + 1 }].copy_from_slice(&cotonum[{ 4 - exponent }..=4]);
                buffer[{ 3 + exponent }..].copy_from_slice(&cotonum[{ 5 + exponent }..]);
            } else {
                buffer[6] = exponential.coto_utf8()[0].max(b'+');
                buffer[7..].copy_from_slice(&exponential.coto_utf8()[2..]);
                buffer[5] = b'E';
                buffer[1..=3].copy_from_slice(&num.coto_utf8()[1..=3])
            }
        }
        buffer
    }
}

impl COtoUTF8<11> for f64 {
    fn coto_utf8(&self) -> [u8; 11] {
        let mut buffer = [0u8; 11];
        buffer[0] = if self.is_sign_negative() { b'-' } else { b' ' };
        if self.is_infinite() {
            buffer[1..].copy_from_slice(b"INFINITY");
        } else {
            let mut num = if *self < 0. { -*self } else { *self };
            let mut exponential: i16 = 0;
            while !(0. ..=10.).contains(&num) {
                if num < 0. {
                    exponential -= 1;
                    num *= 10.;
                } else {
                    exponential += 1;
                    num /= 10.;
                }
            }
            if (-8..=5).contains(&exponential) {
                let exponent = exponential.max(0) as usize;
                buffer[2 + exponent] = b'.';
                let cotonum = ((self * 100_000_000.0) as i64).coto_utf8();
                buffer[1..={ exponent + 1 }].copy_from_slice(&cotonum[{ 11 - exponent }..=11]);
                buffer[{ 3 + exponent }..].copy_from_slice(&cotonum[{ 12 + exponent }..]);
            } else {
                buffer[7] = exponential.coto_utf8()[0].max(b'+');
                buffer[8..].copy_from_slice(&exponential.coto_utf8()[3..]);
                buffer[6] = b'E';
                buffer[1..=5].copy_from_slice(&num.coto_utf8()[1..=5])
            }
        }
        buffer
    }
}

#[test]
fn utf8test() {
    assert_eq!("123", core::str::from_utf8(&123u8.coto_utf8()).unwrap());
    assert_eq!(
        "12345",
        core::str::from_utf8(&12345u16.coto_utf8()).unwrap()
    );
    assert_eq!(
        "1234567890",
        core::str::from_utf8(&1234567890u32.coto_utf8()).unwrap()
    );
    assert_eq!("\0123", core::str::from_utf8(&123i8.coto_utf8()).unwrap());
    assert_eq!(
        "-12345",
        core::str::from_utf8(&(-12345i16).coto_utf8()).unwrap()
    );
    assert_eq!(
        "\01234567890",
        core::str::from_utf8(&1234567890i32.coto_utf8()).unwrap()
    );
    assert_eq!(
        " 1.234567",
        core::str::from_utf8(&1.234567f32.coto_utf8()).unwrap()
    )
}