MCPcopy Create free account
hub / github.com/awslabs/llrt / byte_length

Function byte_length

modules/llrt_buffer/src/buffer.rs:185–218  ·  view source on GitHub ↗
(ctx: Ctx<'js>, value: Value<'js>, encoding: Opt<String>)

Source from the content-addressed store, hash-verified

183 std::mem::forget(vec);
184
185 // This conversion is safe because MaybeUninit has the same memory layout as u8, meaning the underlying bytes are identical.
186 // Since Vec<MaybeUninit> and Vec share the same memory representation, a simple reinterpretation of the pointer is valid.
187 // Additionally, Vec::from_raw_parts correctly reconstructs the vector using the original length and capacity, ensuring that memory ownership remains consistent.
188 // The call to std::mem::forget(vec) prevents the original Vec<MaybeUninit> from being dropped, avoiding double frees or memory corruption.
189 // However, this conversion is only safe if all elements of MaybeUninit are properly initialized.
190 // If any uninitialized values exist, reading them as u8 would lead to undefined behavior.
191 unsafe { Vec::from_raw_parts(ptr, len, capacity) }
192}
193
194fn alloc_unsafe_slow(ctx: Ctx<'_>, size: usize) -> Result<Value<'_>> {
195 let layout = std::alloc::Layout::array::<u8>(size).or_throw(&ctx)?;
196
197 let bytes = unsafe {
198 let ptr = std::alloc::alloc(layout);
199 if ptr.is_null() {
200 return Err(Exception::throw_internal(&ctx, "Memory allocation failed"));
201 }
202 Vec::from_raw_parts(ptr, size, size)
203 };
204 Buffer(bytes).into_js(&ctx)
205}
206
207fn byte_length<'js>(ctx: Ctx<'js>, value: Value<'js>, encoding: Opt<String>) -> Result<usize> {
208 //slow path
209 if let Some(encoding) = encoding.0 {
210 let encoder = Encoder::from_str(&encoding).or_throw(&ctx)?;
211 let a = ObjectBytes::from(&ctx, &value)?;
212 let bytes = a.as_bytes(&ctx)?;
213 return Ok(encoder.decode(bytes).or_throw(&ctx)?.len());
214 }
215 //fast path
216 if let Some(val) = value.as_string() {
217 return Ok(val.to_string()?.len());
218 }
219
220 if value.is_array() {
221 let array = value.as_array().unwrap();

Callers

nothing calls this directly

Calls 8

fromFunction · 0.85
or_throwMethod · 0.80
or_throw_msgMethod · 0.80
as_objectMethod · 0.80
as_bytesMethod · 0.45
lenMethod · 0.45
decodeMethod · 0.45
to_stringMethod · 0.45

Tested by

no test coverage detected