arraystring 0.3.0

Fixed capacity stack based generic string
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Integrates `ArrayString` with other crates' traits

use crate::prelude::*;

#[cfg(all(feature = "diesel-traits", feature = "std"))]
use std::io::Write;

#[cfg(feature = "diesel-traits")]
use diesel::{expression::*, prelude::*, query_builder::*, row::Row, sql_types::*};

#[cfg(feature = "diesel-traits")]
use diesel::backend::Backend;

#[cfg(feature = "diesel-traits")]
use diesel::deserialize::{self, FromSql, FromSqlRow, Queryable};

#[cfg(all(feature = "diesel-traits", feature = "std"))]
use diesel::serialize::{self, Output, ToSql};

#[cfg(feature = "serde-traits")]
use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize};

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
#[cfg(feature = "serde-traits")]
impl<SIZE> Serialize for ArrayString<SIZE>
where
    SIZE: Capacity,
{
    #[inline]
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        Serialize::serialize(self.as_str(), ser)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
#[cfg(feature = "serde-traits")]
impl<'a, SIZE> Deserialize<'a> for ArrayString<SIZE>
where
    SIZE: Capacity,
{
    #[inline]
    fn deserialize<D: Deserializer<'a>>(des: D) -> Result<Self, D::Error> {
        <&str>::deserialize(des).map(Self::from_str_truncate)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE: Capacity> Expression for ArrayString<SIZE> {
    type SqlType = VarChar;
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE: Capacity, QS> SelectableExpression<QS> for ArrayString<SIZE> {}
#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE: Capacity, QS> AppearsOnTable<QS> for ArrayString<SIZE> {}
#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE: Capacity> NonAggregate for ArrayString<SIZE> {}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE, DB> QueryFragment<DB> for ArrayString<SIZE>
where
    SIZE: Capacity,
    DB: Backend + HasSqlType<VarChar>,
{
    #[inline]
    fn walk_ast(&self, mut pass: AstPass<DB>) -> QueryResult<()> {
        pass.push_bind_param::<Varchar, _>(&self.as_str())?;
        Ok(())
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE, ST, DB> FromSql<ST, DB> for ArrayString<SIZE>
where
    SIZE: Capacity,
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    #[inline]
    fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
        let ptr: *const str = FromSql::<ST, DB>::from_sql(bytes)?;
        // We know that the pointer impl will never return null
        Ok(Self::from_str_truncate(unsafe { &*ptr }))
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE, ST, DB> FromSqlRow<ST, DB> for ArrayString<SIZE>
where
    SIZE: Capacity,
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    const FIELDS_NEEDED: usize = 1;

    #[inline]
    fn build_from_row<T: Row<DB>>(row: &mut T) -> deserialize::Result<Self> {
        FromSql::<ST, DB>::from_sql(row.take())
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<SIZE, ST, DB> Queryable<ST, DB> for ArrayString<SIZE>
where
    SIZE: Capacity,
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    type Row = Self;

    #[inline]
    fn build(row: Self::Row) -> Self {
        row
    }
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(all(feature = "diesel-traits", feature = "std")))
)]
#[cfg(all(feature = "diesel-traits", feature = "std"))]
impl<SIZE, DB> ToSql<VarChar, DB> for ArrayString<SIZE>
where
    SIZE: Capacity,
    DB: Backend,
{
    #[inline]
    fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
        ToSql::<VarChar, DB>::to_sql(self.as_str(), out)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl Expression for CacheString {
    type SqlType = VarChar;
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<QS> SelectableExpression<QS> for CacheString {}
#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<QS> AppearsOnTable<QS> for CacheString {}
#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl NonAggregate for CacheString {}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<DB> QueryFragment<DB> for CacheString
where
    DB: Backend + HasSqlType<VarChar>,
{
    #[inline]
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
        self.0.walk_ast(pass)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<ST, DB> FromSql<ST, DB> for CacheString
where
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    #[inline]
    fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
        Ok(CacheString(FromSql::from_sql(bytes)?))
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<ST, DB> FromSqlRow<ST, DB> for CacheString
where
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    const FIELDS_NEEDED: usize = 1;

    #[inline]
    fn build_from_row<T: Row<DB>>(row: &mut T) -> deserialize::Result<Self> {
        Ok(CacheString(FromSqlRow::build_from_row(row)?))
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
#[cfg(feature = "diesel-traits")]
impl<ST, DB> Queryable<ST, DB> for CacheString
where
    DB: Backend,
    *const str: FromSql<ST, DB>,
{
    type Row = Self;

    #[inline]
    fn build(row: Self::Row) -> Self {
        row
    }
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(all(feature = "diesel-traits", feature = "std")))
)]
#[cfg(all(feature = "diesel-traits", feature = "std"))]
impl<DB> ToSql<VarChar, DB> for CacheString
where
    DB: Backend,
{
    #[inline]
    fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
        ToSql::to_sql(&self.0, out)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
#[cfg(feature = "serde-traits")]
impl Serialize for CacheString {
    #[inline]
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(ser)
    }
}

#[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
#[cfg(feature = "serde-traits")]
impl<'a> Deserialize<'a> for CacheString {
    #[inline]
    fn deserialize<D: Deserializer<'a>>(des: D) -> Result<Self, D::Error> {
        Ok(CacheString(Deserialize::deserialize(des)?))
    }
}

#[cfg(test)]
mod tests {
    #![allow(proc_macro_derive_resolution_fallback)]
    #![allow(unused_import_braces)]

    use super::*;
    use crate::ArrayString;

    #[cfg(feature = "serde-traits")]
    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct DeriveSerde(pub ArrayString<typenum::U8>);

    #[cfg(feature = "serde-traits")]
    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct Derive2Serde(pub CacheString);

    #[test]
    #[cfg(feature = "serde-traits")]
    fn serde_derive_json() {
        let string =
            serde_json::to_string(&DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap()))
                .unwrap();
        let s: DeriveSerde = serde_json::from_str(&string).unwrap();
        assert_eq!(
            s,
            DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap())
        );
    }

    #[test]
    #[cfg(feature = "serde-traits")]
    fn serde_derive2_json() {
        let string = serde_json::to_string(&Derive2Serde(CacheString(
            ArrayString::try_from_str("abcdefg").unwrap(),
        )))
        .unwrap();
        let s: DeriveSerde = serde_json::from_str(&string).unwrap();
        assert_eq!(
            s,
            DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap())
        );
    }

    #[test]
    #[cfg(feature = "serde-traits")]
    fn serde_json() {
        let string =
            serde_json::to_string(&ArrayString::<typenum::U8>::try_from_str("abcdefg").unwrap())
                .unwrap();
        let s: ArrayString<typenum::U8> = serde_json::from_str(&string).unwrap();
        assert_eq!(
            s,
            ArrayString::<typenum::U8>::try_from_str("abcdefg").unwrap()
        );
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    use diesel::{debug_query, insert_into, mysql, pg, sqlite, update};

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[macro_use]
    table! {
        derives (name) {
            name -> VarChar,
        }
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[derive(Queryable, Insertable, Clone, Debug)]
    #[table_name = "derives"]
    struct DeriveDiesel {
        pub name: ArrayString<typenum::U32>,
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[derive(Queryable, Insertable, Clone, Debug)]
    #[table_name = "derives"]
    struct Derive2Diesel {
        pub name: CacheString,
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[derive(Queryable, Insertable, Clone, Debug)]
    #[table_name = "derives"]
    struct Derive3Diesel<'a> {
        pub name: &'a str,
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[test]
    fn diesel_derive_query_compare_insert() {
        let array = DeriveDiesel {
            name: ArrayString::try_from_str("Name1").unwrap(),
        };
        let cache = Derive2Diesel {
            name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
        };
        let string = Derive3Diesel { name: "Name1" };

        let insert_array = insert_into(derives::table).values(&array);
        let insert_cache = insert_into(derives::table).values(&cache);
        let insert_string = insert_into(derives::table).values(&string);
        assert_eq!(
            debug_query::<pg::Pg, _>(&insert_array).to_string(),
            debug_query::<pg::Pg, _>(&insert_string).to_string()
        );
        assert_eq!(
            debug_query::<pg::Pg, _>(&insert_cache).to_string(),
            debug_query::<pg::Pg, _>(&insert_string).to_string()
        );
        assert_eq!(
            debug_query::<mysql::Mysql, _>(&insert_array).to_string(),
            debug_query::<mysql::Mysql, _>(&insert_string).to_string()
        );
        assert_eq!(
            debug_query::<mysql::Mysql, _>(&insert_cache).to_string(),
            debug_query::<mysql::Mysql, _>(&insert_string).to_string()
        );
        assert_eq!(
            debug_query::<sqlite::Sqlite, _>(&insert_array).to_string(),
            debug_query::<sqlite::Sqlite, _>(&insert_string).to_string()
        );
        assert_eq!(
            debug_query::<sqlite::Sqlite, _>(&insert_cache).to_string(),
            debug_query::<sqlite::Sqlite, _>(&insert_string).to_string()
        );
    }

    #[test]
    fn diesel_derive_query_compare_update() {
        let array = DeriveDiesel {
            name: ArrayString::try_from_str("Name1").unwrap(),
        };
        let cache = Derive2Diesel {
            name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
        };
        let string = Derive3Diesel { name: "Name1" };
        let update_array = update(derives::table).set(derives::name.eq(&array.name));
        let update_cache = update(derives::table).set(derives::name.eq(&cache.name));
        let update_string = update(derives::table).set(derives::name.eq(&string.name));
        assert_eq!(
            debug_query::<pg::Pg, _>(&update_array).to_string(),
            debug_query::<pg::Pg, _>(&update_string).to_string()
        );
        assert_eq!(
            debug_query::<pg::Pg, _>(&update_cache).to_string(),
            debug_query::<pg::Pg, _>(&update_string).to_string()
        );
        assert_eq!(
            debug_query::<mysql::Mysql, _>(&update_array).to_string(),
            debug_query::<mysql::Mysql, _>(&update_string).to_string()
        );
        assert_eq!(
            debug_query::<mysql::Mysql, _>(&update_cache).to_string(),
            debug_query::<mysql::Mysql, _>(&update_string).to_string()
        );
        assert_eq!(
            debug_query::<sqlite::Sqlite, _>(&update_array).to_string(),
            debug_query::<sqlite::Sqlite, _>(&update_string).to_string()
        );
        assert_eq!(
            debug_query::<sqlite::Sqlite, _>(&update_cache).to_string(),
            debug_query::<sqlite::Sqlite, _>(&update_string).to_string()
        );
    }

    #[test]
    #[ignore]
    #[cfg(feature = "std")]
    fn diesel_select_query_compiles() {
        let conn = pg::PgConnection::establish("").unwrap();
        let select_array: Vec<DeriveDiesel> = derives::table
            .select(derives::all_columns)
            .load(&conn)
            .unwrap();
        let select_cache: Vec<Derive2Diesel> = derives::table
            .select(derives::all_columns)
            .load(&conn)
            .unwrap();
        assert_eq!(
            select_cache
                .into_iter()
                .map(|d| d.name.to_string())
                .collect::<Vec<_>>(),
            select_array
                .into_iter()
                .map(|d| d.name.to_string())
                .collect::<Vec<_>>()
        );
        let _: std::time::SystemTime = derives::table.select(dsl::now).first(&conn).unwrap();
        let _: std::time::SystemTime = derives::table.select(dsl::now).first(&conn).unwrap();

        let conn = mysql::MysqlConnection::establish("").unwrap();
        let select_array: Vec<DeriveDiesel> = derives::table
            .select(derives::all_columns)
            .load(&conn)
            .unwrap();
        let select_cache: Vec<Derive2Diesel> = derives::table
            .select(derives::all_columns)
            .load(&conn)
            .unwrap();
        assert_eq!(
            select_array
                .into_iter()
                .map(|d| d.name.to_string())
                .collect::<Vec<_>>(),
            select_cache
                .into_iter()
                .map(|d| d.name.to_string())
                .collect::<Vec<_>>()
        );
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[test]
    fn diesel_derive_query_sqlite() {
        let conn = diesel::sqlite::SqliteConnection::establish(":memory:").unwrap();
        let _ = diesel::sql_query("CREATE TABLE derives (name VARCHAR(32));")
            .execute(&conn)
            .unwrap();
        let string = DeriveDiesel {
            name: ArrayString::try_from_str("Name1").unwrap(),
        };

        let _ = insert_into(derives::table)
            .values(&string)
            .execute(&conn)
            .unwrap();

        let queried: DeriveDiesel = derives::table.first(&conn).unwrap();
        assert_eq!(queried.name.as_str(), "Name1");
    }

    #[cfg(all(feature = "diesel-traits", feature = "std"))]
    #[test]
    fn diesel_derive2_query_sqlite() {
        let conn = diesel::sqlite::SqliteConnection::establish(":memory:").unwrap();
        let _ = diesel::sql_query("CREATE TABLE derives (name VARCHAR(32));")
            .execute(&conn)
            .unwrap();
        let string = Derive2Diesel {
            name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
        };

        let _ = insert_into(derives::table)
            .values(&string)
            .execute(&conn)
            .unwrap();

        let queried: Derive2Diesel = derives::table.first(&conn).unwrap();
        assert_eq!(queried.name.as_str(), "Name1");
    }
}