Check if copy possible during compilation time for ArrayString

I need copy ArrayString<N> to ArrayString<M>,
and want check is it possible at compile time. In other words I want validate M >= N at compile time.

More details:

struct Foo {
   s: ArrayString<20>,
   ...
}
struct Boo {
  s: ArrayString<16>,
  ...
}

fn f(foo: &mut Foo, boo: &Boo) {
    // here I want to check that foo.s.capcity() >= boo.s.capacity()
    foo.s = boo.s.as_str().try_into().unwrap();
}

Of course simple static assert doesn't compile:

const _: () = assert!(foo.s.capacity() >= boo.s.capacity());

possible solution is this:

const fn all_good() -> bool {
   let foo = Foo {
      s: ArrayString::new_const(),
      ...
   };
   let foo_s_cap = foo.s.capacity();
   std::mem::forget(foo);
   let boo = Boo {
      s: ArrayString::new_const(),
      ...
   };
   let boo_s_cap = boo.s.capacity();
   std::mem::forget(boo);
   foo_s_cap >= boo_s_cap
}

const _:() = assert!(all_good());

this works, but it is too verbose, and required that all other fields of Foo and Boo are const initialized.

Is it possible to make compile time validation of Foo::s.capacity() >= Boo::s.capacity() with 1-5 lines of code?

How about:

impl Foo { const LEN: usize = 20; }
struct Foo {
   s: ArrayString<{ Self::LEN }>,
   // ...
}

impl Boo { const LEN: usize = 16; }
struct Boo {
  s: ArrayString<{ Self::LEN }>,
  // ...
}

const _: () = assert!(Foo::LEN >= Boo::LEN);
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.