Rust - How to migrate '\uXXXX' to new bytes string - migration

I'm wondering if there is a possibility to translate following old Rust code:
bytes!("a\u2028t")
Into current language. It seems bytes! was deprecated by b"" but I don't see a way to translate \u2028 into a byte string literal.

If you want a true byte string equivalent, you'll need to find the UTF8 encoding of U+2028, e.g. via
fn main() {
for b in "\u2028".as_bytes().iter() { print!("\\x{:x}", *b) }
}
which prints \xe2\x80\xa8 (i.e. in pre-encoded form), so b"a\xe2\x80\xa8t" should work. Also, the above hints at another method: you can often use "a\u2028t".as_bytes(), although this will not work in static contexts.

Related

What patterns exist for mocking a single function while testing? [duplicate]

This question already has answers here:
How to mock specific methods but not all of them in Rust?
(2 answers)
How to mock external dependencies in tests? [duplicate]
(1 answer)
How can I test stdin and stdout?
(1 answer)
Is there a way of detecting whether code is being called from tests in Rust?
(1 answer)
What is the proper way to use the `cfg!` macro to choose between multiple implementations?
(1 answer)
Closed 3 years ago.
I have a function generates a salted hash digest for some data. For the salt, it uses a random u32 value. It looks something like this:
use rand::RngCore;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
fn hash(msg: &str) -> String {
let salt = rand::thread_rng().next_u32();
let mut s = DefaultHasher::new();
s.write_u32(salt);
s.write(msg.as_bytes());
format!("{:x}{:x}", &salt, s.finish())
}
In a test, I'd like to validate that it produces expected values, given a known salt and string. How do I mock (swizzle?) rand::thread_rng().next_u32() in the test to generate a specific value? In other words, what could replace the comment in this example to make the test pass?
mod tests {
#[test]
fn test_hashes() {
// XXX How to mock ThreadRng::next_u32() to return 3892864592?
assert_eq!(hash("foo"), "e80866501cdda8af09a0a656");
}
}
Some approaches I've looked at:
I'm aware that the ThreadRng returned by rand::thread_rng() implements RngCore, so in theory I could set a variable somewhere to store a reference to a RngCore, and implement my own mocked variant to set during testing. I've taken this sort of approach in Go and Java, but I couldn't get the Rust type checker to allow it.
I looked at the list of mock frameworks, such as MockAll, but they appear to be designed to mock a struct or trait to pass to a method, and this code doesn't pass one, and I wouldn't necessarily want users of the library to be able to pass in a RngCore.
Use the #[cfg(test)] macro to call a different function specified in the tests module, then have that function read the value to return from elsewhere. This I got to work, but had to use an unsafe mutable static variable to set the value for the mocked method to find, which seems gross. Is there a better way?
As a reference, I'll post an answer using the #[cfg(test)] + unsafe mutable static variable technique, but hope there's a more straightforward way to do this sort of thing.
In the test module, use lazy-static to add a static variable with a Mutex for thread safety, create a function like next_u32() to return its value, and have tests set the static variable to a known value. It should fall back on returning a properly random number if it's not set, so here I've made it Vec<u32> so it can tell:
mod tests {
use super::*;
use lazy_static::lazy_static;
use std::sync::Mutex;
lazy_static! {
static ref MOCK_SALT: Mutex<Vec<u32>> = Mutex::new(vec![]);
}
// Replaces random salt generation when testing.
pub fn mock_salt() -> u32 {
let mut sd = MOCK_SALT.lock().unwrap();
if sd.is_empty() {
rand::thread_rng().next_u32()
} else {
let ret = sd[0];
sd.clear();
ret
}
}
#[test]
fn test_hashes() {
MOCK_SALT.lock().unwrap().push(3892864592);
assert_eq!(hash("foo"), "e80866501cdda8af09a0a656");
}
}
Then modify hash() to call tests::mock_salt() instead of rand::thread_rng().next_u32() when testing (the first three lines of the function body are new):
fn hash(msg: &str) -> String {
#[cfg(test)]
let salt = tests::mock_salt();
#[cfg(not(test))]
let salt = rand::thread_rng().next_u32();
let mut s = DefaultHasher::new();
s.write_u32(salt);
s.write(msg.as_bytes());
format!("{:x}{:x}", &salt, s.finish())
}
Then use of the macros allows Rust to determine, at compile time, which function to call, so there's no loss of efficiency in non-test builds. It does mean that there's some knowledge of the tests module in the source code, but it's not included in the binary, so should be relatively safe. I suppose there could be a custom derive macro to automate this somehow. Something like:
#[mock(rand::thread_rng().next_u32())]
let salt = rand::thread_rng().next_u32();
Would auto-generate the mocked method in the tests module (or elsewhere?), slot it in here, and provide functions for the tests to set the value --- only when testing, of course. Seems like a lot, though.
Playground.

How to convert a handle string to a std::string

I am trying to convert a handle string to a normal string. I though the method I was using was working, but when I look in the debugger it appears that half of my string has been chopped off on the line that creates the chars variable. Any idea why and what the proper way to convert a handle string to a normal string woudl be?
std::string convert(String^ s) {
const char* chars = (const char*)(System::Runtime::InteropServices::Marshal::
StringToHGlobalAnsi(s)).ToPointer();
string myNewString = std::string(chars);
return myNewString;
}
It's probably the debugger that's cutting off the display of the string. You didn't mention how long a string you're using, but the debugger can't display infinite length, so it has to cut it off at some point.
To verify this, try printing myNewString to the console, or to the debugger via Debug::WriteLine or OutputDebugString.
However, there is a significant issue in your code: After allocating memory with StringToHGlobalAnsi, you must free it using FreeHGlobal.
If you want to continue using StringToHGlobalAnsi, I'd fix it up like this:
std::string convert(String^ s) {
IntPtr ptr = Marshal::StringToHGlobalAnsi(s);
string myNewString = std::string((const char*)ptr.ToPointer());
Marshal::FreeHGlobal(ptr);
return myNewString;
}
However, it's probably easier to use the marshal_as methods. This will take care of everything for you.
std::string output = marshal_as<std::string>(managedString);

What is this Objective C code doing

I am a developer in C-like languages (Java/JavaScript/C#) and I am attempting to convert some Objective-C code into Java.
For the most part, it is relatively straightforward but I have hit a stumbling block with the following bit of code:
typedef struct {
char *PAGE_AREA_ONE;
char *PAGE_AREA_TWO;
char *PAGE_AREA_THREE;
} CODES;
- (CODES*) getOpCode {
CODES *result = NULL;
result = malloc(sizeof(CODES));
result->PAGE_AREA_ONE = "\x1b\x1b\x1b";
result->PAGE_AREA_TWO = "\x2d\x2d\x2d";
result->PAGE_AREA_THREE = "\x40\x40";
return result;
}
What would the Java equivalent of this be? From what I can tell in other areas of the code, it is being used to store constants. But I am not 100% certain.
Thanks.
The typedef is just creating a structure that contains three string properties. The getOpCode method is apparently trying to create a new structure and assign values to those three properties. C# code would be:
public class Codes
{
public string PageAreaOne;
public string PageAreaTwo;
public string PageAreaThree;
}
public Codes GetCodes()
{
Codes result = new Codes();
result.PageAreaOne = "\x1b\x1b\x1b"; // three ESC characters
result.PageAreaTwo = "---";
result.PageAreaThree = "##";
return result;
}
The code in question is allocating a block of memory that the size of the CODES structure, filling it with some data, and returning a pointer to the new block. The data is apparently some operation codes (that is, instructions) for something, so perhaps the data is being sent to some other device where the instructions will be executed.

How to avoid if else or switch case whe dealing with enums?

I have a member variable that tells units for a value I have measured like centimeters,kilometers,seconds,hours etc.
Now these are enums,
When I display a corresponding string, I have created a method that returns corresponding string for these enums.
Unlike Java, enums here cant have other properties associated with them.
So I have to explicitly do a if-else-if chain or a switch case to return the correct string.
I am new to Objective C. any good practice that I should be following in such scenarios ?
afaik Objective-C enums are just old-school C enums... so maybe you can use an integer value for them?
I guess if your enum values started at 0 and increased you could use some sort of array access:
const char *distanceUnitToString2(enum DistanceUnit unit)
{
const char *values[] = {
"cm",
"m",
"km"
};
// do some sanity checking here
// ...
return values[unit];
}
But this feels a little flaky to me. What if you have negative values, or you are using bitmask-style enum values like 1 << 8? You are going to end up using a very large array.
You also could use a switch and improve it a little with a macro. Something like this:
const char *distanceUnitToString(enum DistanceUnit unit)
{
#define CASE(UNIT, STRING) case (UNIT): return (STRING)
switch (unit) {
CASE(kCentimeters, "cm");
CASE(kMeters, "m");
CASE(kKiloMeters, "km");
default:
// should not get here
assert(0);
break;
}
#undef CASE
}
But you don't really save that much vs. not using the macro.
Martin James's comment is the right answer. And use a definition of the enum like:
enum units { cm = 0, m, km };
that way you can be sure that your enum translates to the correct index values.

How do I convert a System::String^ to const char*?

I'm developing an app in C++/CLI and have a csv file writing library in unmanaged code that I want to use from the managed portion. So my function looks something like this:
bool CSVWriter::Write(const char* stringToWrite);
...but I'm really struggling to convert my shiny System::String^ into something compatible. Basically I was hoping to call by doing something like:
if( m_myWriter->Write(String::Format("{0}",someValueIWantToSave)) )
{
// report success
}
using namespace System::Runtime::InteropServices;
const char* str = (const char*) (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();
From Dev Shed.
As mcandre mentions, Marshal::StringToHGlobalAnsi() is correct. But don't forget to free the newly allocated resource with Marshal::FreeHGlobal(), when the string is no longer in use.
Alternatively, you can use the msclr::interop::marshal_as template to create the string resource and automatically release it when the call exits the resource's scope.
There's a list of what types need which conversion in the overview of marshalling in C++.