@@ -19,7 +19,6 @@ use crate::utils::MakeMaybeUninit;
19
19
#[ cfg( feature="serde" ) ]
20
20
use serde:: { Serialize , Deserialize , Serializer , Deserializer } ;
21
21
22
-
23
22
/// A string with a fixed capacity.
24
23
///
25
24
/// The `ArrayString` is a string backed by a fixed size array. It keeps track
@@ -108,6 +107,42 @@ impl<const CAP: usize> ArrayString<CAP>
108
107
Ok ( arraystr)
109
108
}
110
109
110
+ /// Create a new `ArrayString` from a `str`, suitable for const context
111
+ ///
112
+ /// Capacity is inferred from the type parameter.
113
+ ///
114
+ /// **Panics** or causes a **const error** if the backing array is not large enough to fit the
115
+ /// string.
116
+ ///
117
+ /// ```
118
+ /// use arrayvec::ArrayString;
119
+ ///
120
+ /// const S: ArrayString<3> = ArrayString::from_str_const("");
121
+ /// ```
122
+ ///
123
+ /// A compile-time error will occur - in constants - if the input is too long:
124
+ ///
125
+ /// ```compile_fail
126
+ /// # use arrayvec::ArrayString;
127
+ /// const S1: ArrayString<3> = ArrayString::from_str_const("too long for the capacity");
128
+ /// ```
129
+ pub const fn from_str_const ( s : & str ) -> Self {
130
+ let bytes = s. as_bytes ( ) ;
131
+ let len = bytes. len ( ) ;
132
+ assert_length_lt_capacity_const ! ( len, CAP ) ;
133
+
134
+ let mut vec = Self :: new_const ( ) ;
135
+ let mut i = 0 ;
136
+ while i < len {
137
+ vec. xs [ i] = MaybeUninit :: new ( bytes[ i] ) ;
138
+ i += 1 ;
139
+ }
140
+
141
+ // Safety: we know len <= CAP and elements < len are initialized
142
+ vec. len = len as u32 ;
143
+ vec
144
+ }
145
+
111
146
/// Create a new `ArrayString` from a byte string literal.
112
147
///
113
148
/// **Errors** if the byte string literal is not valid UTF-8.
0 commit comments