Re: How to pre build vibe-d dub package

2020-05-29 Thread kookman via Digitalmars-d-learn

On Friday, 29 May 2020 at 11:45:24 UTC, Andre Pany wrote:

André


I do it by defining a configuration “build-deps” in my dub.sdl 
with target type “none” and then doing the build as two steps in 
the dockerfile:


``` dockerfile
...
WORKDIR /build
COPY dub.s* ./
RUN dub build -v —config=build-deps
COPY src ./src
RUN dub build -v —config=executable
...


Re: A custom name for variables

2020-05-29 Thread solidstate1991 via Digitalmars-d-learn

On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:

I need to create a variable with custom name, like this
import std;
void main()
{
string name;
readf(" %s", );
// some code that generates a variable of type integer and 
value 0

}
Could you help me with that?


This might be possible in certain scripting languages, but not in 
D.


Static fields are generated during compile time, and while 
something like that is possible using template mixins in the code 
(famous use in D is Phobos's bitfields, which generates 
properties for a struct or a class), it's impossible during 
runtime, and - in extension - by reading a value from console.


Re: A custom name for variables

2020-05-29 Thread Liu via Digitalmars-d-learn

On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:

I need to create a variable with custom name, like this
import std;
void main()
{
string name;
readf(" %s", );
// some code that generates a variable of type integer and 
value 0

}
Could you help me with that?


This is not possible You would need a scripting language in order 
to do that. What are you trying to do? if your explain better, we 
may try came up with a better solution


Re: Determining @trusted-status

2020-05-29 Thread Clarice via Digitalmars-d-learn
I didn't know the spec was changed to include a section on 
@safe/@trusted/@system interfaces, because otherwise I wouldn't 
have made this thread. But regardless, thank you everyone for 
your time: your posts are very helpful.





Re: Determining @trusted-status

2020-05-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 5/28/20 8:09 PM, Clarice wrote:
It seems that @safe will be de jure, whether by the current state of 
DIP1028 or otherwise. However, I'm unsure how to responsibly determine 
whether a FFI may be @trusted: the type signature and the body. Should I 
run, for example, a C library through valgrind to observe any memory 
leaks/corruption? Is it enough to trust the authors of a library (e.g. 
SDL and OpenAL) where applying @trusted is acceptable?
There's probably no one right answer, but I'd be very thankful for some 
clarity, regardless.



@trusted doesn't necessarily mean "bug free", what it means is that 
given the parameters to the function, does it certify that it will only 
do @safe things with those parameters. Note that it can do whatever it 
wants elsewhere, as long as it doesn't violate the constraints of @safe 
that the caller needs.


So whether you mark something @trusted or @system highly depends on the 
behavior of the function.


A classic example is in the documentation of @safe [1]: memcpy. mempcy 
does not provide a @safe interface, because @safe code is allowed to use 
pointers as long as you only access the one item it refers to. However, 
memcpy will access a provided number of bytes *beyond* the item.


Therefore, C's memcpy should be marked @system, not @trusted. But you 
can provide a @trusted interface to memcpy because you know the semantic 
guarantees for memcpy (i.e. what it is specified to do):


@trusted void safeMemcpy(T)(T[] dst, T[] src)
{
   // must be same length
   enforce(dst.length == src.length);
   // no overlap (undefined behavior otherwise)
   enforce(dst.ptr >= src.ptr + src.length || src.ptr >= dst.ptr + 
dst.length);

   import core.stdc.string : memcpy;
   memcpy(dst.ptr, src.ptr, dst.length * T.sizeof);
}

There is no way to call this function and violate memory safety.

One has to be extra cautious though, when passing in templated 
parameters. Hidden calls such as postblit and destructors can easily not 
be @safe, so in those cases, it's wise to wrap the unsafe parts in 
@trusted lambda functions (as others have mentioned).


In my example above, I know that arrays do not have these hidden calls, 
and I'm never directly using any of the elements, just pointers.


-Steve

[1]https://dlang.org/spec/function.html#safe-interfaces


How to pre build vibe-d dub package

2020-05-29 Thread Andre Pany via Digitalmars-d-learn

Hi,

I have a docker image in which a vibe-d application is build from 
source code. Every time a file is changed, unfortunately the 
whole vibe-d dub packages are retrieved again from dub registry 
and compiled again (which takes ages).


In my app.json I have these dependency declaration:
``` json
"dependencies": {
"vibe-d:core": "0.9.0-alpha.5",
"vibe-d:http": "0.9.0-alpha.5",
"vibe-d:tls": "0.9.0-alpha.5"
},
"subConfigurations": {
"vibe-d:tls": "notls"
},
```

and it would be great if could do s.th. like
RUN dub build vibe-d -y --override-config=vibe-d/notls
to fetch and prebuild the dub package. Therefore, if a file
is changed, only the application itself is compiled
but it just not works. It does not build all dependencies of 
vibe-d and
also notls is ignored. I tried a lot of variations but nothing 
has the effect

I need.

My workaround is for the moment to create a dummy dub application 
and compile it:


``` dockerfile
# Prebuild dub dependencies
RUN mkdir -p /tmp/foo/source && echo 'void main(){}' > 
/tmp/foo/source/app.d \
&& echo '{"name":"bla", "dependencies": {"vibe-d": 
"0.9.0-alpha.5", "vibe-d:tls": 
"0.9.0-alpha.5"},"subConfigurations": {"vibe-d:tls": "notls"}}' > 
/tmp/foo/dub.json \

&& dub build --root /tmp/foo/
```

Do I miss something here?

Kind regards
André



Re: [Windows]Need an example: How to read and list names of USB devices via Windows API without using Utilities

2020-05-29 Thread WebFreak001 via Digitalmars-d-learn

On Friday, 29 May 2020 at 09:04:30 UTC, WebFreak001 wrote:

[...]


I realized it may be useful to have a much more complete example, 
so replace the while (true) loop in my first code with this to 
get much more information dumped:



while (true)
{
enumerator.Next(WBEM_INFINITE,
1, , );
if (!ureturn)
break;
scope (exit)
clsobj.Release();

BSTR name;
VARIANT vtProp;
printf("\nEntry:\n");
clsobj.BeginEnumeration(0);
while (true)
{
enum WBEM_S_NO_MORE_DATA = 0x40005;
if (clsobj.Next(0, , , null,
null) == WBEM_S_NO_MORE_DATA)
break;
printf("\t%ls: ", name);
SysFreeString(name);
switch (vtProp.vt)
{
case VARENUM.VT_EMPTY:
printf("\n");
break;
case VARENUM.VT_NULL:
printf("null\n");
break;
case VARENUM.VT_VOID:
printf("void\n");
break;
case VARENUM.VT_I1:
printf("byte: %d\n",
cast(int) vtProp.bVal);
break;
case VARENUM.VT_UI1:
printf("ubyte: %d\n",
cast(int) vtProp.bVal);
break;
case VARENUM.VT_UI2:
printf("ushort: %d\n",
cast(int) vtProp.iVal);
break;
case VARENUM.VT_UI4:
case VARENUM.VT_UINT:
printf("uint: %u\n",
cast(uint) vtProp.intVal);
break;
case VARENUM.VT_I8:
printf("long: %ld\n",
cast(long) vtProp.llVal);
break;
case VARENUM.VT_UI8:
printf("ulong: %lu\n",
cast(ulong) vtProp.llVal);
break;
case VARENUM.VT_I2:
printf("short: %d\n",
cast(int) vtProp.iVal);
break;
case VARENUM.VT_I4:
case VARENUM.VT_INT:
printf("int: %d\n", vtProp.intVal);
break;
case VARENUM.VT_R4:
printf("float: %f\n", vtProp.fltVal);
break;
case VARENUM.VT_R8:
printf("double: %f\n", vtProp.dblVal);
break;
case VARENUM.VT_CY:
printf("currency: %ld\n",
vtProp.cyVal.int64);
break;
case VARENUM.VT_DATE:
printf("date: %lf\n", vtProp.date);
break;
case VARENUM.VT_BSTR:
printf("bstr: %ls\n", vtProp.bstrVal);
break;
case VARENUM.VT_BOOL:
if (vtProp.boolVal)
printf("true\n");
else
printf("false\n");
break;
default:
printf("\n", vtProp.vt);
break;
}
VariantClear();
}

clsobj.Get("Name", 0, , null, null);
if (vtProp.vt == VARENUM.VT_BSTR)
printf("\tName: %ls\n", vtProp.bstrVal);
}




Re: [Windows]Need an example: How to read and list names of USB devices via Windows API without using Utilities

2020-05-29 Thread WebFreak001 via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 14:16:56 UTC, BoQsc wrote:
I always wanted to know if there is any proven example on how 
to interface with USB devices by using Windows operating 
system. Any explanations, snippets in relation to topic would 
help.


What I expect:
Being able to detect if a new USB device is connected.
Being able to read USB device name.
Being able to read USB device partition/s name/s.
Being able to list all USB devices.

What is required and are there any critical problems with 
achieving any of this?


use WMI like in C++: 
https://docs.microsoft.com/en-us/windows/win32/wmisdk/creating-a-wmi-application-using-c-


If you make a port of the IDL files, check out 
https://github.com/WebFreak001/dwinrt/tree/master/generator for a 
converter converting IDL files to D definitions. However that 
project is pretty much only working for directx and WinRT, so you 
will have to adjust things if you want to use it.


If you manually port over the IDL definitions, remember that D 
interfaces & classes are reference types, so if the IDL file uses 
`IWbemServices** ppNamespace` for example, you will just change 
it to `IWbemServices* ppNamespace` (pp meaning it's an output 
parameter, for interfaces with pp prefix you should only have one 
*, for interfaces with p prefix you should have no *)


Example:

import core.stdc.config;
import core.stdc.stdio;
import core.sys.windows.com;
import core.sys.windows.oaidl;
import core.sys.windows.objidl;
import core.sys.windows.windows;
import core.sys.windows.wtypes;

void main(string[] args)
{
	// port of 
https://docs.microsoft.com/en-us/windows/win32/wmisdk/example-creating-a-wmi-application


CoInitializeEx(null, COINIT.COINIT_MULTITHREADED)
.validateHResult("CoInitializeEx");
scope (exit)
CoUninitialize();

CoInitializeSecurity(null, // security descriptor
-1, // COM negotiates service
null, // Authentication services
null, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Impersonation
null, // Authentication info
			EOLE_AUTHENTICATION_CAPABILITIES.EOAC_NONE, // Additional 
capabilities

null  // Reserved
).validateHResult("CoInitializeSecurity");

IWbemLocator loc;
CoCreateInstance(_WbemLocator, null, CLSCTX_INPROC_SERVER,
_IWbemLocator, cast(void**)).validateHResult(
"CoCreateInstance WbemLocator");
scope (exit)
loc.Release();

IWbemServices svc;
loc.ConnectServer("ROOT\\CIMV2", // WMI namespace
null, // username
null, // password
null, // locale
0, // security flags
null, // authority
null, // context object
 // IWbemServices proxy
).validateHResult("ConnectServer");
scope (exit)
svc.Release();

// Set the IWbemServices proxy so that impersonation
// of the user (client) occurs.

	// WARNING V wrong D definition (wants IUnknown* instead of 
IUnknown which is already a reference type, cast overrides this)

CoSetProxyBlanket(cast(IUnknown*) svc, // the proxy to set
RPC_C_AUTHN_WINNT, // authentication service
RPC_C_AUTHZ_NONE, // authorization service
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // authentication level
RPC_C_IMP_LEVEL_IMPERSONATE, // impersonation level
NULL, // client identity
			EOLE_AUTHENTICATION_CAPABILITIES.EOAC_NONE // proxy 
capabilities

).validateHResult("CoSetProxyBlanket");

IEnumWbemClassObject enumerator;
svc.ExecQuery("WQL", "SELECT * FROM Win32_PnPEntity",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
null, ).validateHResult("ExecQuery");
scope (exit)
enumerator.Release();

IWbemClassObject clsobj;
ULONG ureturn;
while (true)
{
enumerator.Next(WBEM_INFINITE, 1, , );
if (!ureturn)
break;
scope (exit)
clsobj.Release();

VARIANT vtProp;
clsobj.Get("Name", 0, , null, null);
// TODO: do what you want with the listed devices here
printf("Name: %ls\n", vtProp.bstrVal);
VariantClear();
}
}

// type definitions, might as well move them to a library...

HRESULT validateHResult(HRESULT result, string what)
{
if 

Re: Determining @trusted-status

2020-05-29 Thread ag0aep6g via Digitalmars-d-learn

On 29.05.20 08:28, JN wrote:
Alternatively you could just use @trusted blocks. Unsafe blocks are a 
common practice in languages like C# or Rust when it comes to calling 
unsafe code. @safe isn't about 100% bulletproof safety. @safe is (should 
be) about not having memory related errors outside of @trusted code, 
minimizing the surface area for errors.


Note that an "@trusted block" is really a nested @trusted function being 
called immediately. Being an @trusted function, the "block" must have a 
safe interface. I.e., its safety cannot depend on its inputs. The inputs 
of a nested function include the variables of the surrounding function. 
@trusted blocks often violate the letter of @trusted law, because people 
forget/ignore that.


For example, the second @trusted block here is strictly speaking not 
allowed, because its safety depends on `p`:


void main() @safe
{
import core.stdc.stdlib: free, malloc;
int* p = () @trusted {
return cast(int*) malloc(int.sizeof);
} ();
if (p is null) return;
/* ... else: do something with p ... */
() @trusted { free(p); } ();
}


Re: Determining @trusted-status

2020-05-29 Thread ag0aep6g via Digitalmars-d-learn

On 29.05.20 02:09, Clarice wrote:
It seems that @safe will be de jure, whether by the current state of 
DIP1028 or otherwise. However, I'm unsure how to responsibly determine 
whether a FFI may be @trusted: the type signature and the body. Should I 
run, for example, a C library through valgrind to observe any memory 
leaks/corruption? Is it enough to trust the authors of a library (e.g. 
SDL and OpenAL) where applying @trusted is acceptable?
There's probably no one right answer, but I'd be very thankful for some 
clarity, regardless.


There are two ways in which a function can be unsafe:

1) The function has a bug and doesn't behave as intended.
2) The function doesn't have a safe interface [1].

When applying @trusted, you are allowed to pretend that #1 doesn't 
happen. You are allowed to trust that the author of the library made no 
safety-critical mistakes.


What you have to look out for is #2. When a function has special 
requirements for how to call it, and calling it incorrectly can lead to 
undefined behavior / memory corruption, then it cannot be @trusted. It 
can only be @system. In order to use the function in @safe code, you 
need to write an @trusted wrapper that provides a safe interface and 
makes sure that the @system function is called correctly.



[1] https://dlang.org/spec/function.html#safe-interfaces


Re: Determining @trusted-status

2020-05-29 Thread JN via Digitalmars-d-learn

On Friday, 29 May 2020 at 00:09:56 UTC, Clarice wrote:
It seems that @safe will be de jure, whether by the current 
state of DIP1028 or otherwise. However, I'm unsure how to 
responsibly determine whether a FFI may be @trusted: the type 
signature and the body. Should I run, for example, a C library 
through valgrind to observe any memory leaks/corruption? Is it 
enough to trust the authors of a library (e.g. SDL and OpenAL) 
where applying @trusted is acceptable?
There's probably no one right answer, but I'd be very thankful 
for some clarity, regardless.


I think most C FFI should be @system, even if it's for popular 
libraries like SDL. Whenever you have API that takes a pointer 
and a size of array, you are risking buffer overflows and similar 
issues. It's very easy to mess up and send array length instead 
of array length * element.sizeof. A @trusted API would only 
accept a slice, which is much safer than raw pointers.


Alternatively you could just use @trusted blocks. Unsafe blocks 
are a common practice in languages like C# or Rust when it comes 
to calling unsafe code. @safe isn't about 100% bulletproof 
safety. @safe is (should be) about not having memory related 
errors outside of @trusted code, minimizing the surface area for 
errors.