home.social

#struct — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #struct, aggregated by home.social.

fetched live
  1. StructPadding

    Представляю свою библиотеку для обнуления байт выравнивания (padding) в unmanaged структурах. Обнуление байт паддинга (padding) обеспечивает детерминированное состояние памяти, что критически важно для двоичного сравнения или вычисления хэша. И не менее важно при бинарной сериализации.

    habr.com/ru/articles/968650/

    #padding #struct #nuget

  2. StructPadding

    Представляю свою библиотеку для обнуления байт выравнивания (padding) в unmanaged структурах. Обнуление байт паддинга (padding) обеспечивает детерминированное состояние памяти, что критически важно для двоичного сравнения или вычисления хэша. И не менее важно при бинарной сериализации.

    habr.com/ru/articles/968650/

    #padding #struct #nuget

  3. StructPadding

    Представляю свою библиотеку для обнуления байт выравнивания (padding) в unmanaged структурах. Обнуление байт паддинга (padding) обеспечивает детерминированное состояние памяти, что критически важно для двоичного сравнения или вычисления хэша. И не менее важно при бинарной сериализации.

    habr.com/ru/articles/968650/

    #padding #struct #nuget

  4. readonly struct в C#

    Привет, Хабр! Вы, вероятно, уже сталкивались с struct в C# и задумались: а зачем нужен readonly struct и когда он реально спасает, а когда, наоборот, начинает всё тормозить? Сегодня это и рассмотрим.

    habr.com/ru/companies/otus/art

    #c# #struct #readonly_struct

  5. readonly struct в C#

    Привет, Хабр! Вы, вероятно, уже сталкивались с struct в C# и задумались: а зачем нужен readonly struct и когда он реально спасает, а когда, наоборот, начинает всё тормозить? Сегодня это и рассмотрим.

    habr.com/ru/companies/otus/art

    #c# #struct #readonly_struct

  6. readonly struct в C#

    Привет, Хабр! Вы, вероятно, уже сталкивались с struct в C# и задумались: а зачем нужен readonly struct и когда он реально спасает, а когда, наоборот, начинает всё тормозить? Сегодня это и рассмотрим.

    habr.com/ru/companies/otus/art

    #c# #struct #readonly_struct

  7. Порядок инициализации полей, статики и всего остального в C#

    Всем привет! Многие сталкиваются с трудностями на собеседовании на вопросе по типу "Расскажите о порядке иницализации в C#". Либо банально когда видят квиз, стараются вспомнить, а что там должно инициализироваться? Сегодня многие вспомнят, а кто-то узнает о порядке инициализации. Затронем не только классы, а также структуры, а точнее - ключевое слово default для них. Сделаем следующие классы и посмотрим, что будет при создании объекта B:

    habr.com/ru/articles/886692/

    #c# #net #net_core #struct #инициализация #поля

  8. Порядок инициализации полей, статики и всего остального в C#

    Всем привет! Многие сталкиваются с трудностями на собеседовании на вопросе по типу "Расскажите о порядке иницализации в C#". Либо банально когда видят квиз, стараются вспомнить, а что там должно инициализироваться? Сегодня многие вспомнят, а кто-то узнает о порядке инициализации. Затронем не только классы, а также структуры, а точнее - ключевое слово default для них. Сделаем следующие классы и посмотрим, что будет при создании объекта B:

    habr.com/ru/articles/886692/

    #c# #net #net_core #struct #инициализация #поля

  9. Порядок инициализации полей, статики и всего остального в C#

    Всем привет! Многие сталкиваются с трудностями на собеседовании на вопросе по типу "Расскажите о порядке иницализации в C#". Либо банально когда видят квиз, стараются вспомнить, а что там должно инициализироваться? Сегодня многие вспомнят, а кто-то узнает о порядке инициализации. Затронем не только классы, а также структуры, а точнее - ключевое слово default для них. Сделаем следующие классы и посмотрим, что будет при создании объекта B:

    habr.com/ru/articles/886692/

    #c# #net #net_core #struct #инициализация #поля

  10. Кастомная сериализация структур в UE

    Допустим, вы создали свою USTRUCT в C++ и хотите её сериализовать. Обычно, достаточно просто пометить нужные поля как SaveGame . Но вот проблема, для этого эти поля сами должны поддерживать сериализацию. К сожалению одна из наших переменных не поддерживает сериализацию. В моем случае, это структура FNonSerializableStruct . Из-за этого сериализуется только вторая структура, хоть мы и пометили SaveGame обе.

    habr.com/ru/articles/865170/

    #usrtuct #struct #serialize #serializable #структура #сериализация #unreal_engine #ue #структуры #анрил

  11. Кастомная сериализация структур в UE

    Допустим, вы создали свою USTRUCT в C++ и хотите её сериализовать. Обычно, достаточно просто пометить нужные поля как SaveGame . Но вот проблема, для этого эти поля сами должны поддерживать сериализацию. К сожалению одна из наших переменных не поддерживает сериализацию. В моем случае, это структура FNonSerializableStruct . Из-за этого сериализуется только вторая структура, хоть мы и пометили SaveGame обе.

    habr.com/ru/articles/865170/

    #usrtuct #struct #serialize #serializable #структура #сериализация #unreal_engine #ue #структуры #анрил

  12. Кастомная сериализация структур в UE

    Допустим, вы создали свою USTRUCT в C++ и хотите её сериализовать. Обычно, достаточно просто пометить нужные поля как SaveGame . Но вот проблема, для этого эти поля сами должны поддерживать сериализацию. К сожалению одна из наших переменных не поддерживает сериализацию. В моем случае, это структура FNonSerializableStruct . Из-за этого сериализуется только вторая структура, хоть мы и пометили SaveGame обе.

    habr.com/ru/articles/865170/

    #usrtuct #struct #serialize #serializable #структура #сериализация #unreal_engine #ue #структуры #анрил

  13. In Swift I want to write a struct as a binary file, my struct looks like this:

    struct Bitmap {
    var bfh: BitmapFileHeader
    var bih: BitmapInfoHeader
    var imageData: Data
    }

    the BitmapFileHeader and BitmapInfoHeader contain only UInt32 and UInt16 variables.

    Now it should be quite easy to write it with this:
    let data = withUnsafeBytes(of: myStruct) { Data($0) }

    but the imageData won't be written because it's from type Data.

    Ok, so I have to write it like this:

    withUnsafeBytes(of: myBMP.bfh) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bih) { data.append(contentsOf: $0) }
    data.append(myBMP.imageData)

    But that inserts padding so that every variable uses 4 bytes instead of what I defined.

    So I have to write each variable like this:

    withUnsafeBytes(of: myBMP.bfh.type) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bfh.size) { data.append(contentsOf: $0) }
    and so on...

    Seriously? Is there really no easy generic way to just write the Data as is?

    #swift #struct

  14. In Swift I want to write a struct as a binary file, my struct looks like this:

    struct Bitmap {
    var bfh: BitmapFileHeader
    var bih: BitmapInfoHeader
    var imageData: Data
    }

    the BitmapFileHeader and BitmapInfoHeader contain only UInt32 and UInt16 variables.

    Now it should be quite easy to write it with this:
    let data = withUnsafeBytes(of: myStruct) { Data($0) }

    but the imageData won't be written because it's from type Data.

    Ok, so I have to write it like this:

    withUnsafeBytes(of: myBMP.bfh) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bih) { data.append(contentsOf: $0) }
    data.append(myBMP.imageData)

    But that inserts padding so that every variable uses 4 bytes instead of what I defined.

    So I have to write each variable like this:

    withUnsafeBytes(of: myBMP.bfh.type) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bfh.size) { data.append(contentsOf: $0) }
    and so on...

    Seriously? Is there really no easy generic way to just write the Data as is?

    #swift #struct

  15. In Swift I want to write a struct as a binary file, my struct looks like this:

    struct Bitmap {
    var bfh: BitmapFileHeader
    var bih: BitmapInfoHeader
    var imageData: Data
    }

    the BitmapFileHeader and BitmapInfoHeader contain only UInt32 and UInt16 variables.

    Now it should be quite easy to write it with this:
    let data = withUnsafeBytes(of: myStruct) { Data($0) }

    but the imageData won't be written because it's from type Data.

    Ok, so I have to write it like this:

    withUnsafeBytes(of: myBMP.bfh) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bih) { data.append(contentsOf: $0) }
    data.append(myBMP.imageData)

    But that inserts padding so that every variable uses 4 bytes instead of what I defined.

    So I have to write each variable like this:

    withUnsafeBytes(of: myBMP.bfh.type) { data.append(contentsOf: $0) }
    withUnsafeBytes(of: myBMP.bfh.size) { data.append(contentsOf: $0) }
    and so on...

    Seriously? Is there really no easy generic way to just write the Data as is?

    #swift #struct

  16. CW: Оголошення обмежень після класу/структури в C++

    У C++20 зʼявились концепти й обмеження для функцій, класів/структур та інших шаблонів. Для функцій та методів вимоги можна вказувати після оголошення шаблону або після функції.

    template<typename T>
        requires ...
    T f() {}
    
    template<typename T>
    T f() requires ... {}
    

    Якщо не шаблонний метод у шаблоні класу потребує додаткових вимог їх можна вказати після оголошення методу.

    template<typename T>
    class S {
        T f() requires integer<T> {}
    };
    

    У такому випадку клас може згенеруватись з будь-яким типом, але це метод буде присутній тільки якщо шаблонний тип відповідає вимогам.

    Але іноді може знадобитись використати поточний клас у вимогах. Наприклад при CRTP.

    template<typename D>
    class Base requires std::derived_from<D, Base> {...};
    

    На жаль зараз такого немає.

    #cpp #cxx #cpp20 #concepts #constrains #requires #class #template #struct #CRTP #proposal #програмування #шаблони #вимоги #обмеження #пропозиція

  17. I like the second way better too. I also like the idea of splitting the struct and its impls to its own file. Thanks everyone for your input.

    #Rust #Trait #Impl #Struct

  18. I like the second way better too. I also like the idea of splitting the struct and its impls to its own file. Thanks everyone for your input.

    #Rust #Trait #Impl #Struct

  19. I like the second way better too. I also like the idea of splitting the struct and its impls to its own file. Thanks everyone for your input.

  20. I like the second way better too. I also like the idea of splitting the struct and its impls to its own file. Thanks everyone for your input.

    #Rust #Trait #Impl #Struct

  21. I like the second way better too. I also like the idea of splitting the struct and its impls to its own file. Thanks everyone for your input.

    #Rust #Trait #Impl #Struct

  22. In Rust if I have some structs that each implement a couple traits, what is the preferred way to order things?

    trait … {}
    trait …{}

    struct …{}
    struct …{}
    struct …{}

    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}

    OR

    trait …{}
    trait …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    OR, something else entirely?

    #Rust #Trait #Impl #Struct

  23. In Rust if I have some structs that each implement a couple traits, what is the preferred way to order things?

    trait … {}
    trait …{}

    struct …{}
    struct …{}
    struct …{}

    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}

    OR

    trait …{}
    trait …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    OR, something else entirely?

    #Rust #Trait #Impl #Struct

  24. In Rust if I have some structs that each implement a couple traits, what is the preferred way to order things?

    trait … {}
    trait …{}

    struct …{}
    struct …{}
    struct …{}

    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}

    OR

    trait …{}
    trait …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    OR, something else entirely?

  25. In Rust if I have some structs that each implement a couple traits, what is the preferred way to order things?

    trait … {}
    trait …{}

    struct …{}
    struct …{}
    struct …{}

    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}

    OR

    trait …{}
    trait …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    OR, something else entirely?

    #Rust #Trait #Impl #Struct

  26. In Rust if I have some structs that each implement a couple traits, what is the preferred way to order things?

    trait … {}
    trait …{}

    struct …{}
    struct …{}
    struct …{}

    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}
    impl…for …{}

    OR

    trait …{}
    trait …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    struct …{}
    impl…for …{}
    impl…for …{}

    OR, something else entirely?

    #Rust #Trait #Impl #Struct

  27. ⬆️ @gooba42

    Another one of my favorites is carryover of #struct from #C.

    In #Java, everything is a class. Using one requires mem alloc from heap, and passed by reference, then later de-allocated. Mutable objects are costly in cycles, but also unsafe across threads.

    Swift structs are immutable, passed by value on stack, no need to allocate and deallocate, and they can have functions/methods just like classes, but not overrideable.

    Swift has a full complement of modern language constructs

  28. ⬆️ @gooba42

    Another one of my favorites is carryover of #struct from #C.

    In #Java, everything is a class. Using one requires mem alloc from heap, and passed by reference, then later de-allocated. Mutable objects are costly in cycles, but also unsafe across threads.

    Swift structs are immutable, passed by value on stack, no need to allocate and deallocate, and they can have functions/methods just like classes, but not overrideable.

    Swift has a full complement of modern language constructs

  29. ⬆️ @gooba42

    Another one of my favorites is carryover of #struct from #C.

    In #Java, everything is a class. Using one requires mem alloc from heap, and passed by reference, then later de-allocated. Mutable objects are costly in cycles, but also unsafe across threads.

    Swift structs are immutable, passed by value on stack, no need to allocate and deallocate, and they can have functions/methods just like classes, but not overrideable.

    Swift has a full complement of modern language constructs

  30. Ніяк не міг зрозуміти чому наступний код не компілюється.

    template <typename T, size_t N>
    struct Arr {
        T[N] arr;
    	
        T* begin() { return arr; }
        T* end()   { return arr + N; }
    };
    

    Хвилин пʼять сидів над ним якщо не довше.

    #cpp #arrey #class #struct #template #шаблони #масив #клас #структура #структури

  31. Ніяк не міг зрозуміти чому наступний код не компілюється.

    template <typename T, size_t N>
    struct Arr {
        T[N] arr;
    	
        T* begin() { return arr; }
        T* end()   { return arr + N; }
    };
    

    Хвилин пʼять сидів над ним якщо не довше.

    #cpp #arrey #class #struct #template #шаблони #масив #клас #структура #структури

  32. Aber ich bin fast sicher, dass #struct da sinnvoller ist. Ich habe nämlich einige feste Enums für einen Health-Status (up, down, unknown und out_of_service), aber grundsätzlich kann man beliebige haben. Zu jeden Status gibt es einen HTTP Status Code (2* oder 5*) und ggf. Details.
    Ich dachte, perfekt für Enum Varianten, aber Pustekuchen. Viel zu viel bad smelling code und serde serialisert an meinen Erwartungen vorbei (aber nachvollziehbar) und ich muss da umdenken.

  33. Aber ich bin fast sicher, dass #struct da sinnvoller ist. Ich habe nämlich einige feste Enums für einen Health-Status (up, down, unknown und out_of_service), aber grundsätzlich kann man beliebige haben. Zu jeden Status gibt es einen HTTP Status Code (2* oder 5*) und ggf. Details.
    Ich dachte, perfekt für Enum Varianten, aber Pustekuchen. Viel zu viel bad smelling code und serde serialisert an meinen Erwartungen vorbei (aber nachvollziehbar) und ich muss da umdenken.

  34. Aber ich bin fast sicher, dass #struct da sinnvoller ist. Ich habe nämlich einige feste Enums für einen Health-Status (up, down, unknown und out_of_service), aber grundsätzlich kann man beliebige haben. Zu jeden Status gibt es einen HTTP Status Code (2* oder 5*) und ggf. Details.
    Ich dachte, perfekt für Enum Varianten, aber Pustekuchen. Viel zu viel bad smelling code und serde serialisert an meinen Erwartungen vorbei (aber nachvollziehbar) und ich muss da umdenken.

  35. Aber ich bin fast sicher, dass #struct da sinnvoller ist. Ich habe nämlich einige feste Enums für einen Health-Status (up, down, unknown und out_of_service), aber grundsätzlich kann man beliebige haben. Zu jeden Status gibt es einen HTTP Status Code (2* oder 5*) und ggf. Details.
    Ich dachte, perfekt für Enum Varianten, aber Pustekuchen. Viel zu viel bad smelling code und serde serialisert an meinen Erwartungen vorbei (aber nachvollziehbar) und ich muss da umdenken.