no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / js / src / rust / wasm.rs
blob73c7057b66156de690bdc7ac43d45a71b34bccfa
1 /* Copyright 2020 Mozilla Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
16 #[no_mangle]
17 pub unsafe extern "C" fn wasm_text_to_binary(
18     text: *const u16,
19     text_len: usize,
20     out_bytes: *mut *mut u8,
21     out_bytes_len: *mut usize,
22     out_error: *mut *mut u8,
23     out_error_len: *mut usize,
24 ) -> bool {
25     let text_slice = std::slice::from_raw_parts(text, text_len);
26     let text = String::from_utf16_lossy(text_slice);
28     match text_to_binary(&text) {
29         Ok(bytes) => {
30             let bytes_box = bytes.into_boxed_slice();
31             let bytes_slice = Box::leak(bytes_box);
32             out_bytes.write(bytes_slice.as_mut_ptr());
33             out_bytes_len.write(bytes_slice.len());
34             true
35         }
36         Err(error) => {
37             let error = Box::leak(format!("{}\0", error).into_boxed_str());
38             out_error.write(error.as_mut_ptr());
39             out_error_len.write(error.len());
40             false
41         }
42     }
45 fn text_to_binary(text: &str) -> Result<Vec<u8>, wast::Error> {
46     let mut lexer = wast::lexer::Lexer::new(text);
47     // The 'names.wast' spec test has confusable unicode, so disable detection.
48     // This protection is not very useful for a shell testing function anyways.
49     lexer.allow_confusing_unicode(true);
50     let buf = wast::parser::ParseBuffer::new_with_lexer(lexer)?;
51     let mut ast = wast::parser::parse::<wast::Wat>(&buf)?;
52     return ast.encode();